xbuild: use the AdditionalReferencePath items to locate assemblies
[mono.git] / mcs / mcs / anonymous.cs
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-2011 Novell, Inc.
10 // Copyright 2011 Xamarin Inc
11 //
12
13 using System;
14 using System.Collections.Generic;
15 using Mono.CompilerServices.SymbolWriter;
16 using System.Diagnostics;
17
18 #if STATIC
19 using IKVM.Reflection;
20 using IKVM.Reflection.Emit;
21 #else
22 using System.Reflection;
23 using System.Reflection.Emit;
24 #endif
25
26 namespace Mono.CSharp {
27
28         public abstract class CompilerGeneratedContainer : ClassOrStruct
29         {
30                 protected CompilerGeneratedContainer (TypeContainer parent, MemberName name, Modifiers mod)
31                         : this (parent, name, mod, MemberKind.Class)
32                 {
33                 }
34
35                 protected CompilerGeneratedContainer (TypeContainer parent, MemberName name, Modifiers mod, MemberKind kind)
36                         : base (parent, name, null, kind)
37                 {
38                         Debug.Assert ((mod & Modifiers.AccessibilityMask) != 0);
39
40                         ModFlags = mod | Modifiers.COMPILER_GENERATED | Modifiers.SEALED;
41                         spec = new TypeSpec (Kind, null, this, null, ModFlags);
42                 }
43
44                 protected void CheckMembersDefined ()
45                 {
46                         if (HasMembersDefined)
47                                 throw new InternalErrorException ("Helper class already defined!");
48                 }
49
50                 protected override bool DoDefineMembers ()
51                 {
52                         if (Kind == MemberKind.Class && !IsStatic && !PartialContainer.HasInstanceConstructor) {
53                                 DefineDefaultConstructor (false);
54                         }
55
56                         return base.DoDefineMembers ();
57                 }
58
59                 protected static MemberName MakeMemberName (MemberBase host, string name, int unique_id, TypeParameters tparams, Location loc)
60                 {
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);
66
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);
71                         }
72
73                         return new MemberName (tname, args, loc);
74                 }
75
76                 public static string MakeName (string host, string typePrefix, string name, int id)
77                 {
78                         return "<" + host + ">" + typePrefix + "__" + name + id.ToString ("X");
79                 }
80
81                 protected override TypeSpec[] ResolveBaseTypes (out FullNamedExpression base_class)
82                 {
83                         base_type = Compiler.BuiltinTypes.Object;
84
85                         base_class = null;
86                         return null;
87                 }
88         }
89
90         public class HoistedStoreyClass : CompilerGeneratedContainer
91         {
92                 public sealed class HoistedField : Field
93                 {
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)
97                         {
98                         }
99
100                         protected override bool ResolveMemberType ()
101                         {
102                                 if (!base.ResolveMemberType ())
103                                         return false;
104
105                                 HoistedStoreyClass parent = ((HoistedStoreyClass) Parent).GetGenericStorey ();
106                                 if (parent != null && parent.Mutator != null)
107                                         member_type = parent.Mutator.Mutate (MemberType);
108
109                                 return true;
110                         }
111                 }
112
113                 protected TypeParameterMutator mutator;
114
115                 public HoistedStoreyClass (TypeDefinition parent, MemberName name, TypeParameters tparams, Modifiers mods, MemberKind kind)
116                         : base (parent, name, mods | Modifiers.PRIVATE, kind)
117                 {
118
119                         if (tparams != null) {
120                                 var type_params = name.TypeParameters;
121                                 var src = new TypeParameterSpec[tparams.Count];
122                                 var dst = new TypeParameterSpec[tparams.Count];
123
124                                 for (int i = 0; i < tparams.Count; ++i) {
125                                         type_params[i] = tparams[i].CreateHoistedCopy (spec);
126
127                                         src[i] = tparams[i].Type;
128                                         dst[i] = type_params[i].Type;
129                                 }
130
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]);
136                                 }
137
138                                 mutator = new TypeParameterMutator (tparams, type_params);
139                         }
140                 }
141
142                 #region Properties
143
144                 public TypeParameterMutator Mutator {
145                         get {
146                                 return mutator;
147                         }
148                         set {
149                                 mutator = value;
150                         }
151                 }
152
153                 #endregion
154
155                 public HoistedStoreyClass GetGenericStorey ()
156                 {
157                         TypeContainer storey = this;
158                         while (storey != null && storey.CurrentTypeParameters == null)
159                                 storey = storey.Parent;
160
161                         return storey as HoistedStoreyClass;
162                 }
163         }
164
165
166         //
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)
170         //
171         public class AnonymousMethodStorey : HoistedStoreyClass
172         {
173                 struct StoreyFieldPair
174                 {
175                         public readonly AnonymousMethodStorey Storey;
176                         public readonly Field Field;
177
178                         public StoreyFieldPair (AnonymousMethodStorey storey, Field field)
179                         {
180                                 this.Storey = storey;
181                                 this.Field = field;
182                         }
183                 }
184
185                 //
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.
190                 //
191                 sealed class ThisInitializer : Statement
192                 {
193                         readonly HoistedThis hoisted_this;
194
195                         public ThisInitializer (HoistedThis hoisted_this)
196                         {
197                                 this.hoisted_this = hoisted_this;
198                         }
199
200                         protected override void DoEmit (EmitContext ec)
201                         {
202                                 hoisted_this.EmitAssign (ec, new CompilerGeneratedThis (ec.CurrentType, loc), false, false);
203                         }
204
205                         protected override void CloneTo (CloneContext clonectx, Statement target)
206                         {
207                                 // Nothing to clone
208                         }
209                 }
210
211                 // Unique storey ID
212                 public readonly int ID;
213
214                 public readonly ExplicitBlock OriginalSourceBlock;
215
216                 // A list of StoreyFieldPair with local field keeping parent storey instance
217                 List<StoreyFieldPair> used_parent_storeys;
218                 List<ExplicitBlock> children_references;
219
220                 // A list of hoisted parameters
221                 protected List<HoistedParameter> hoisted_params;
222                 List<HoistedParameter> hoisted_local_params;
223                 protected List<HoistedVariable> hoisted_locals;
224
225                 // Hoisted this
226                 protected HoistedThis hoisted_this;
227
228                 // Local variable which holds this storey instance
229                 public Expression Instance;
230
231                 bool initialize_hoisted_this;
232
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),
235                                 tparams, 0, kind)
236                 {
237                         OriginalSourceBlock = block;
238                         ID = parent.Module.CounterAnonymousContainers++;
239                 }
240
241                 public void AddCapturedThisField (EmitContext ec)
242                 {
243                         TypeExpr type_expr = new TypeExpression (ec.CurrentType, Location);
244                         Field f = AddCompilerGeneratedField ("$this", type_expr);
245                         hoisted_this = new HoistedThis (this, f);
246
247                         initialize_hoisted_this = true;
248                 }
249
250                 public Field AddCapturedVariable (string name, TypeSpec type)
251                 {
252                         CheckMembersDefined ();
253
254                         FullNamedExpression field_type = new TypeExpression (type, Location);
255                         if (!spec.IsGenericOrParentIsGeneric)
256                                 return AddCompilerGeneratedField (name, field_type);
257
258                         const Modifiers mod = Modifiers.INTERNAL | Modifiers.COMPILER_GENERATED;
259                         Field f = new HoistedField (this, field_type, mod, name, null, Location);
260                         AddField (f);
261                         return f;
262                 }
263
264                 protected Field AddCompilerGeneratedField (string name, FullNamedExpression type)
265                 {
266                         return AddCompilerGeneratedField (name, type, false);
267                 }
268
269                 protected Field AddCompilerGeneratedField (string name, FullNamedExpression type, bool privateAccess)
270                 {
271                         Modifiers mod = Modifiers.COMPILER_GENERATED | (privateAccess ? Modifiers.PRIVATE : Modifiers.INTERNAL);
272                         Field f = new Field (this, type, mod, new MemberName (name, Location), null);
273                         AddField (f);
274                         return f;
275                 }
276
277                 //
278                 // Creates a link between hoisted variable block and the anonymous method storey
279                 //
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
283                 //
284                 public void AddReferenceFromChildrenBlock (ExplicitBlock block)
285                 {
286                         if (children_references == null)
287                                 children_references = new List<ExplicitBlock> ();
288
289                         if (!children_references.Contains (block))
290                                 children_references.Add (block);
291                 }
292
293                 public void AddParentStoreyReference (EmitContext ec, AnonymousMethodStorey storey)
294                 {
295                         CheckMembersDefined ();
296
297                         if (used_parent_storeys == null)
298                                 used_parent_storeys = new List<StoreyFieldPair> ();
299                         else if (used_parent_storeys.Exists (i => i.Storey == storey))
300                                 return;
301
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));
305                 }
306
307                 public void CaptureLocalVariable (ResolveContext ec, LocalVariable localVariable)
308                 {
309                         if (this is StateMachine) {
310                                 if (ec.CurrentBlock.ParametersBlock != localVariable.Block.ParametersBlock)
311                                         ec.CurrentBlock.Explicit.HasCapturedVariable = true;
312                         } else {
313                                 ec.CurrentBlock.Explicit.HasCapturedVariable = true;
314                         }
315
316                         var hoisted = localVariable.HoistedVariant;
317                         if (hoisted != null && hoisted.Storey != this && hoisted.Storey is StateMachine) {
318                                 // TODO: It's too late the field is defined in HoistedLocalVariable ctor
319                                 hoisted.Storey.hoisted_locals.Remove (hoisted);
320                                 hoisted = null;
321                         }
322
323                         if (hoisted == null) {
324                                 hoisted = new HoistedLocalVariable (this, localVariable, GetVariableMangledName (localVariable));
325                                 localVariable.HoistedVariant = hoisted;
326
327                                 if (hoisted_locals == null)
328                                         hoisted_locals = new List<HoistedVariable> ();
329
330                                 hoisted_locals.Add (hoisted);
331                         }
332
333                         if (ec.CurrentBlock.Explicit != localVariable.Block.Explicit && !(hoisted.Storey is StateMachine))
334                                 hoisted.Storey.AddReferenceFromChildrenBlock (ec.CurrentBlock.Explicit);
335                 }
336
337                 public void CaptureParameter (ResolveContext ec, ParametersBlock.ParameterInfo parameterInfo, ParameterReference parameterReference)
338                 {
339                         if (!(this is StateMachine)) {
340                                 ec.CurrentBlock.Explicit.HasCapturedVariable = true;
341                         }
342
343                         var hoisted = parameterInfo.Parameter.HoistedVariant;
344
345                         if (parameterInfo.Block.StateMachine != null) {
346                                 //
347                                 // Another storey in same block exists but state machine does not
348                                 // have parameter captured. We need to add it there as well to
349                                 // proxy parameter value correctly.
350                                 //
351                                 if (hoisted == null && parameterInfo.Block.StateMachine != this) {
352                                         var storey = parameterInfo.Block.StateMachine;
353
354                                         hoisted = new HoistedParameter (storey, parameterReference);
355                                         parameterInfo.Parameter.HoistedVariant = hoisted;
356
357                                         if (storey.hoisted_params == null)
358                                                 storey.hoisted_params = new List<HoistedParameter> ();
359
360                                         storey.hoisted_params.Add (hoisted);
361                                 }
362
363                                 //
364                                 // Lift captured parameter from value type storey to reference type one. Otherwise
365                                 // any side effects would be done on a copy
366                                 //
367                                 if (hoisted != null && hoisted.Storey != this && hoisted.Storey is StateMachine) {
368                                         if (hoisted_local_params == null)
369                                                 hoisted_local_params = new List<HoistedParameter> ();
370
371                                         hoisted_local_params.Add (hoisted);
372                                         hoisted = null;
373                                 }
374                         }
375
376                         if (hoisted == null) {
377                                 hoisted = new HoistedParameter (this, parameterReference);
378                                 parameterInfo.Parameter.HoistedVariant = hoisted;
379
380                                 if (hoisted_params == null)
381                                         hoisted_params = new List<HoistedParameter> ();
382
383                                 hoisted_params.Add (hoisted);
384                         }
385
386                         //
387                         // Register link between current block and parameter storey. It will
388                         // be used when setting up storey definition to deploy storey reference
389                         // when parameters are used from multiple blocks
390                         //
391                         if (ec.CurrentBlock.Explicit != parameterInfo.Block) {
392                                 hoisted.Storey.AddReferenceFromChildrenBlock (ec.CurrentBlock.Explicit);
393                         }
394                 }
395
396                 TypeExpr CreateStoreyTypeExpression (EmitContext ec)
397                 {
398                         //
399                         // Create an instance of storey type
400                         //
401                         TypeExpr storey_type_expr;
402                         if (CurrentTypeParameters != null) {
403                                 //
404                                 // Use current method type parameter (MVAR) for top level storey only. All
405                                 // nested storeys use class type parameter (VAR)
406                                 //
407                                 var tparams = ec.CurrentAnonymousMethod != null && ec.CurrentAnonymousMethod.Storey != null ?
408                                         ec.CurrentAnonymousMethod.Storey.CurrentTypeParameters :
409                                         ec.CurrentTypeParameters;
410
411                                 TypeArguments targs = new TypeArguments ();
412
413                                 //
414                                 // Use type parameter name instead of resolved type parameter
415                                 // specification to resolve to correctly nested type parameters
416                                 //
417                                 for (int i = 0; i < tparams.Count; ++i)
418                                         targs.Add (new SimpleName (tparams [i].Name, Location)); //  new TypeParameterExpr (tparams[i], Location));
419
420                                 storey_type_expr = new GenericTypeExpr (Definition, targs, Location);
421                         } else {
422                                 storey_type_expr = new TypeExpression (CurrentType, Location);
423                         }
424
425                         return storey_type_expr;
426                 }
427
428                 public void SetNestedStoryParent (AnonymousMethodStorey parentStorey)
429                 {
430                         Parent = parentStorey;
431                         spec.IsGeneric = false;
432                         spec.DeclaringType = parentStorey.CurrentType;
433                         MemberName.TypeParameters = null;
434                 }
435
436                 protected override bool DoResolveTypeParameters ()
437                 {
438                         // Although any storey can have type parameters they are all clones of method type
439                         // parameters therefore have to mutate MVAR references in any of cloned constraints
440                         if (CurrentTypeParameters != null) {
441                                 for (int i = 0; i < CurrentTypeParameters.Count; ++i) {
442                                         var spec = CurrentTypeParameters[i].Type;
443                                         spec.BaseType = mutator.Mutate (spec.BaseType);
444                                         if (spec.InterfacesDefined != null) {
445                                                 var mutated = new TypeSpec[spec.InterfacesDefined.Length];
446                                                 for (int ii = 0; ii < mutated.Length; ++ii) {
447                                                         mutated[ii] = mutator.Mutate (spec.InterfacesDefined[ii]);
448                                                 }
449
450                                                 spec.InterfacesDefined = mutated;
451                                         }
452
453                                         if (spec.TypeArguments != null) {
454                                                 spec.TypeArguments = mutator.Mutate (spec.TypeArguments);
455                                         }
456                                 }
457                         }
458
459                         //
460                         // Update parent cache as we most likely passed the point
461                         // where the cache was constructed
462                         //
463                         Parent.CurrentType.MemberCache.AddMember (this.spec);
464
465                         return true;
466                 }
467
468                 //
469                 // Initializes all hoisted variables
470                 //
471                 public void EmitStoreyInstantiation (EmitContext ec, ExplicitBlock block)
472                 {
473                         // There can be only one instance variable for each storey type
474                         if (Instance != null)
475                                 throw new InternalErrorException ();
476
477                         //
478                         // Create an instance of this storey
479                         //
480                         ResolveContext rc = new ResolveContext (ec.MemberContext);
481                         rc.CurrentBlock = block;
482
483                         var storey_type_expr = CreateStoreyTypeExpression (ec);
484                         var source = new New (storey_type_expr, null, Location).Resolve (rc);
485
486                         //
487                         // When the current context is async (or iterator) lift local storey
488                         // instantiation to the currect storey
489                         //
490                         if (ec.CurrentAnonymousMethod is StateMachineInitializer && (block.HasYield || block.HasAwait)) {
491                                 //
492                                 // Unfortunately, normal capture mechanism could not be used because we are
493                                 // too late in the pipeline and standart assign cannot be used either due to
494                                 // recursive nature of GetStoreyInstanceExpression
495                                 //
496                                 var field = ec.CurrentAnonymousMethod.Storey.AddCompilerGeneratedField (
497                                         LocalVariable.GetCompilerGeneratedName (block), storey_type_expr, true);
498
499                                 field.Define ();
500                                 field.Emit ();
501
502                                 var fexpr = new FieldExpr (field, Location);
503                                 fexpr.InstanceExpression = new CompilerGeneratedThis (ec.CurrentType, Location);
504                                 fexpr.EmitAssign (ec, source, false, false);
505                                 Instance = fexpr;
506                         } else {
507                                 var local = TemporaryVariableReference.Create (source.Type, block, Location);
508                                 if (source.Type.IsStruct) {
509                                         local.LocalInfo.CreateBuilder (ec);
510                                 } else {
511                                         local.EmitAssign (ec, source);
512                                 }
513
514                                 Instance = local;
515                         }
516
517                         EmitHoistedFieldsInitialization (rc, ec);
518
519                         // TODO: Implement properly
520                         //SymbolWriter.DefineScopeVariable (ID, Instance.Builder);
521                 }
522
523                 void EmitHoistedFieldsInitialization (ResolveContext rc, EmitContext ec)
524                 {
525                         //
526                         // Initialize all storey reference fields by using local or hoisted variables
527                         //
528                         if (used_parent_storeys != null) {
529                                 foreach (StoreyFieldPair sf in used_parent_storeys) {
530                                         //
531                                         // Get instance expression of storey field
532                                         //
533                                         Expression instace_expr = GetStoreyInstanceExpression (ec);
534                                         var fs = sf.Field.Spec;
535                                         if (TypeManager.IsGenericType (instace_expr.Type))
536                                                 fs = MemberCache.GetMember (instace_expr.Type, fs);
537
538                                         FieldExpr f_set_expr = new FieldExpr (fs, Location);
539                                         f_set_expr.InstanceExpression = instace_expr;
540
541                                         // TODO: CompilerAssign expression
542                                         SimpleAssign a = new SimpleAssign (f_set_expr, sf.Storey.GetStoreyInstanceExpression (ec));
543                                         if (a.Resolve (rc) != null)
544                                                 a.EmitStatement (ec);
545                                 }
546                         }
547
548                         //
549                         // Initialize hoisted `this' only once, everywhere else will be
550                         // referenced indirectly
551                         //
552                         if (initialize_hoisted_this) {
553                                 rc.CurrentBlock.AddScopeStatement (new ThisInitializer (hoisted_this));
554                         }
555
556                         //
557                         // Setting currect anonymous method to null blocks any further variable hoisting
558                         //
559                         AnonymousExpression ae = ec.CurrentAnonymousMethod;
560                         ec.CurrentAnonymousMethod = null;
561
562                         if (hoisted_params != null) {
563                                 EmitHoistedParameters (ec, hoisted_params);
564                         }
565
566                         ec.CurrentAnonymousMethod = ae;
567                 }
568
569                 protected virtual void EmitHoistedParameters (EmitContext ec, List<HoistedParameter> hoisted)
570                 {
571                         foreach (HoistedParameter hp in hoisted) {
572                                 if (hp == null)
573                                         continue;
574
575                                 //
576                                 // Parameters could be proxied via local fields for value type storey
577                                 //
578                                 if (hoisted_local_params != null) {
579                                         var local_param = hoisted_local_params.Find (l => l.Parameter.Parameter == hp.Parameter.Parameter);
580                                         var source = new FieldExpr (local_param.Field, Location);
581                                         source.InstanceExpression = new CompilerGeneratedThis (CurrentType, Location);
582                                         hp.EmitAssign (ec, source, false, false);
583                                         continue;
584                                 }
585
586                                 hp.EmitHoistingAssignment (ec);
587                         }
588                 }
589
590                 //
591                 // Returns a field which holds referenced storey instance
592                 //
593                 Field GetReferencedStoreyField (AnonymousMethodStorey storey)
594                 {
595                         if (used_parent_storeys == null)
596                                 return null;
597
598                         foreach (StoreyFieldPair sf in used_parent_storeys) {
599                                 if (sf.Storey == storey)
600                                         return sf.Field;
601                         }
602
603                         return null;
604                 }
605
606                 //
607                 // Creates storey instance expression regardless of currect IP
608                 //
609                 public Expression GetStoreyInstanceExpression (EmitContext ec)
610                 {
611                         AnonymousExpression am = ec.CurrentAnonymousMethod;
612
613                         //
614                         // Access from original block -> storey
615                         //
616                         if (am == null)
617                                 return Instance;
618
619                         //
620                         // Access from anonymous method implemented as a static -> storey
621                         //
622                         if (am.Storey == null)
623                                 return Instance;
624
625                         Field f = am.Storey.GetReferencedStoreyField (this);
626                         if (f == null) {
627                                 if (am.Storey == this) {
628                                         //
629                                         // Access from inside of same storey (S -> S)
630                                         //
631                                         return new CompilerGeneratedThis (CurrentType, Location);
632                                 }
633
634                                 //
635                                 // External field access
636                                 //
637                                 return Instance;
638                         }
639
640                         //
641                         // Storey was cached to local field
642                         //
643                         FieldExpr f_ind = new FieldExpr (f, Location);
644                         f_ind.InstanceExpression = new CompilerGeneratedThis (CurrentType, Location);
645                         return f_ind;
646                 }
647
648                 protected virtual string GetVariableMangledName (LocalVariable local_info)
649                 {
650                         //
651                         // No need to mangle anonymous method hoisted variables cause they
652                         // are hoisted in their own scopes
653                         //
654                         return local_info.Name;
655                 }
656
657                 public HoistedThis HoistedThis {
658                         get {
659                                 return hoisted_this;
660                         }
661                         set {
662                                 hoisted_this = value;
663                         }
664                 }
665
666                 public IList<ExplicitBlock> ReferencesFromChildrenBlock {
667                         get { return children_references; }
668                 }
669         }
670
671         public abstract class HoistedVariable
672         {
673                 //
674                 // Hoisted version of variable references used in expression
675                 // tree has to be delayed until we know its location. The variable
676                 // doesn't know its location until all stories are calculated
677                 //
678                 class ExpressionTreeVariableReference : Expression
679                 {
680                         readonly HoistedVariable hv;
681
682                         public ExpressionTreeVariableReference (HoistedVariable hv)
683                         {
684                                 this.hv = hv;
685                         }
686
687                         public override bool ContainsEmitWithAwait ()
688                         {
689                                 return false;
690                         }
691
692                         public override Expression CreateExpressionTree (ResolveContext ec)
693                         {
694                                 return hv.CreateExpressionTree ();
695                         }
696
697                         protected override Expression DoResolve (ResolveContext ec)
698                         {
699                                 eclass = ExprClass.Value;
700                                 type = ec.Module.PredefinedTypes.Expression.Resolve ();
701                                 return this;
702                         }
703
704                         public override void Emit (EmitContext ec)
705                         {
706                                 ResolveContext rc = new ResolveContext (ec.MemberContext);
707                                 Expression e = hv.GetFieldExpression (ec).CreateExpressionTree (rc, false);
708                                 // This should never fail
709                                 e = e.Resolve (rc);
710                                 if (e != null)
711                                         e.Emit (ec);
712                         }
713                 }
714         
715                 protected readonly AnonymousMethodStorey storey;
716                 protected Field field;
717                 Dictionary<AnonymousExpression, FieldExpr> cached_inner_access; // TODO: Hashtable is too heavyweight
718                 FieldExpr cached_outer_access;
719
720                 protected HoistedVariable (AnonymousMethodStorey storey, string name, TypeSpec type)
721                         : this (storey, storey.AddCapturedVariable (name, type))
722                 {
723                 }
724
725                 protected HoistedVariable (AnonymousMethodStorey storey, Field field)
726                 {
727                         this.storey = storey;
728                         this.field = field;
729                 }
730
731                 public AnonymousMethodStorey Storey {
732                         get {
733                                 return storey;
734                         }
735                 }
736
737                 public void AddressOf (EmitContext ec, AddressOp mode)
738                 {
739                         GetFieldExpression (ec).AddressOf (ec, mode);
740                 }
741
742                 public Expression CreateExpressionTree ()
743                 {
744                         return new ExpressionTreeVariableReference (this);
745                 }
746
747                 public void Emit (EmitContext ec)
748                 {
749                         GetFieldExpression (ec).Emit (ec);
750                 }
751
752                 public Expression EmitToField (EmitContext ec)
753                 {
754                         return GetFieldExpression (ec);
755                 }
756
757                 //
758                 // Creates field access expression for hoisted variable
759                 //
760                 protected virtual FieldExpr GetFieldExpression (EmitContext ec)
761                 {
762                         if (ec.CurrentAnonymousMethod == null || ec.CurrentAnonymousMethod.Storey == null) {
763                                 if (cached_outer_access != null)
764                                         return cached_outer_access;
765
766                                 //
767                                 // When setting top-level hoisted variable in generic storey
768                                 // change storey generic types to method generic types (VAR -> MVAR)
769                                 //
770                                 if (storey.Instance.Type.IsGenericOrParentIsGeneric) {
771                                         var fs = MemberCache.GetMember (storey.Instance.Type, field.Spec);
772                                         cached_outer_access = new FieldExpr (fs, field.Location);
773                                 } else {
774                                         cached_outer_access = new FieldExpr (field, field.Location);
775                                 }
776
777                                 cached_outer_access.InstanceExpression = storey.GetStoreyInstanceExpression (ec);
778                                 return cached_outer_access;
779                         }
780
781                         FieldExpr inner_access;
782                         if (cached_inner_access != null) {
783                                 if (!cached_inner_access.TryGetValue (ec.CurrentAnonymousMethod, out inner_access))
784                                         inner_access = null;
785                         } else {
786                                 inner_access = null;
787                                 cached_inner_access = new Dictionary<AnonymousExpression, FieldExpr> (4);
788                         }
789
790                         if (inner_access == null) {
791                                 if (field.Parent.IsGenericOrParentIsGeneric) {
792                                         var fs = MemberCache.GetMember (field.Parent.CurrentType, field.Spec);
793                                         inner_access = new FieldExpr (fs, field.Location);
794                                 } else {
795                                         inner_access = new FieldExpr (field, field.Location);
796                                 }
797
798                                 inner_access.InstanceExpression = storey.GetStoreyInstanceExpression (ec);
799                                 cached_inner_access.Add (ec.CurrentAnonymousMethod, inner_access);
800                         }
801
802                         return inner_access;
803                 }
804
805                 public void Emit (EmitContext ec, bool leave_copy)
806                 {
807                         GetFieldExpression (ec).Emit (ec, leave_copy);
808                 }
809
810                 public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool isCompound)
811                 {
812                         GetFieldExpression (ec).EmitAssign (ec, source, leave_copy, false);
813                 }
814         }
815
816         public class HoistedParameter : HoistedVariable
817         {
818                 sealed class HoistedFieldAssign : CompilerAssign
819                 {
820                         public HoistedFieldAssign (Expression target, Expression source)
821                                 : base (target, source, target.Location)
822                         {
823                         }
824
825                         protected override Expression ResolveConversions (ResolveContext ec)
826                         {
827                                 //
828                                 // Implicit conversion check fails for hoisted type arguments
829                                 // as they are of different types (!!0 x !0)
830                                 //
831                                 return this;
832                         }
833                 }
834
835                 readonly ParameterReference parameter;
836
837                 public HoistedParameter (AnonymousMethodStorey scope, ParameterReference par)
838                         : base (scope, par.Name, par.Type)
839                 {
840                         this.parameter = par;
841                 }
842
843                 public HoistedParameter (HoistedParameter hp, string name)
844                         : base (hp.storey, name, hp.parameter.Type)
845                 {
846                         this.parameter = hp.parameter;
847                 }
848
849                 #region Properties
850
851                 public Field Field {
852                         get {
853                                 return field;
854                         }
855                 }
856
857                 public bool IsAssigned { get; set; }
858
859                 public ParameterReference Parameter {
860                         get {
861                                 return parameter;
862                         }
863                 }
864
865                 #endregion
866
867                 public void EmitHoistingAssignment (EmitContext ec)
868                 {
869                         //
870                         // Remove hoisted redirection to emit assignment from original parameter
871                         //
872                         var temp = parameter.Parameter.HoistedVariant;
873                         parameter.Parameter.HoistedVariant = null;
874
875                         var a = new HoistedFieldAssign (GetFieldExpression (ec), parameter);
876                         a.EmitStatement (ec);
877
878                         parameter.Parameter.HoistedVariant = temp;
879                 }
880         }
881
882         class HoistedLocalVariable : HoistedVariable
883         {
884                 public HoistedLocalVariable (AnonymousMethodStorey storey, LocalVariable local, string name)
885                         : base (storey, name, local.Type)
886                 {
887                 }
888         }
889
890         public class HoistedThis : HoistedVariable
891         {
892                 public HoistedThis (AnonymousMethodStorey storey, Field field)
893                         : base (storey, field)
894                 {
895                 }
896
897                 public Field Field {
898                         get {
899                                 return field;
900                         }
901                 }
902         }
903
904         //
905         // Anonymous method expression as created by parser
906         //
907         public class AnonymousMethodExpression : Expression
908         {
909                 //
910                 // Special conversion for nested expression tree lambdas
911                 //
912                 class Quote : ShimExpression
913                 {
914                         public Quote (Expression expr)
915                                 : base (expr)
916                         {
917                         }
918
919                         public override Expression CreateExpressionTree (ResolveContext ec)
920                         {
921                                 var args = new Arguments (1);
922                                 args.Add (new Argument (expr.CreateExpressionTree (ec)));
923                                 return CreateExpressionFactoryCall (ec, "Quote", args);
924                         }
925
926                         protected override Expression DoResolve (ResolveContext rc)
927                         {
928                                 expr = expr.Resolve (rc);
929                                 if (expr == null)
930                                         return null;
931
932                                 eclass = expr.eclass;
933                                 type = expr.Type;
934                                 return this;
935                         }
936                 }
937
938                 readonly Dictionary<TypeSpec, Expression> compatibles;
939
940                 public ParametersBlock Block;
941
942                 public AnonymousMethodExpression (Location loc)
943                 {
944                         this.loc = loc;
945                         this.compatibles = new Dictionary<TypeSpec, Expression> ();
946                 }
947
948                 #region Properties
949
950                 public override string ExprClassName {
951                         get {
952                                 return "anonymous method";
953                         }
954                 }
955
956                 public virtual bool HasExplicitParameters {
957                         get {
958                                 return Parameters != ParametersCompiled.Undefined;
959                         }
960                 }
961
962                 public ParametersCompiled Parameters {
963                         get {
964                                 return Block.Parameters;
965                         }
966                 }
967
968                 public ReportPrinter TypeInferenceReportPrinter {
969                         get; set;
970                 }
971
972                 #endregion
973
974                 //
975                 // Returns true if the body of lambda expression can be implicitly
976                 // converted to the delegate of type `delegate_type'
977                 //
978                 public bool ImplicitStandardConversionExists (ResolveContext ec, TypeSpec delegate_type)
979                 {
980                         using (ec.With (ResolveContext.Options.InferReturnType, false)) {
981                                 using (ec.Set (ResolveContext.Options.ProbingMode)) {
982                                         var prev = ec.Report.SetPrinter (TypeInferenceReportPrinter ?? new NullReportPrinter ());
983
984                                         var res = Compatible (ec, delegate_type) != null;
985
986                                         ec.Report.SetPrinter (prev);
987
988                                         return res;
989                                 }
990                         }
991                 }
992
993                 TypeSpec CompatibleChecks (ResolveContext ec, TypeSpec delegate_type)
994                 {
995                         if (delegate_type.IsDelegate)
996                                 return delegate_type;
997
998                         if (delegate_type.IsExpressionTreeType) {
999                                 delegate_type = delegate_type.TypeArguments [0];
1000                                 if (delegate_type.IsDelegate)
1001                                         return delegate_type;
1002
1003                                 ec.Report.Error (835, loc, "Cannot convert `{0}' to an expression tree of non-delegate type `{1}'",
1004                                         GetSignatureForError (), delegate_type.GetSignatureForError ());
1005                                 return null;
1006                         }
1007
1008                         ec.Report.Error (1660, loc, "Cannot convert `{0}' to non-delegate type `{1}'",
1009                                       GetSignatureForError (), delegate_type.GetSignatureForError ());
1010                         return null;
1011                 }
1012
1013                 protected bool VerifyExplicitParameters (ResolveContext ec, TypeSpec delegate_type, AParametersCollection parameters)
1014                 {
1015                         if (VerifyParameterCompatibility (ec, delegate_type, parameters, ec.IsInProbingMode))
1016                                 return true;
1017
1018                         if (!ec.IsInProbingMode)
1019                                 ec.Report.Error (1661, loc,
1020                                         "Cannot convert `{0}' to delegate type `{1}' since there is a parameter mismatch",
1021                                         GetSignatureForError (), delegate_type.GetSignatureForError ());
1022
1023                         return false;
1024                 }
1025
1026                 protected bool VerifyParameterCompatibility (ResolveContext ec, TypeSpec delegate_type, AParametersCollection invoke_pd, bool ignore_errors)
1027                 {
1028                         if (Parameters.Count != invoke_pd.Count) {
1029                                 if (ignore_errors)
1030                                         return false;
1031                                 
1032                                 ec.Report.Error (1593, loc, "Delegate `{0}' does not take `{1}' arguments",
1033                                               delegate_type.GetSignatureForError (), Parameters.Count.ToString ());
1034                                 return false;
1035                         }
1036
1037                         bool has_implicit_parameters = !HasExplicitParameters;
1038                         bool error = false;
1039
1040                         for (int i = 0; i < Parameters.Count; ++i) {
1041                                 Parameter.Modifier p_mod = invoke_pd.FixedParameters [i].ModFlags;
1042                                 if (Parameters.FixedParameters [i].ModFlags != p_mod && p_mod != Parameter.Modifier.PARAMS) {
1043                                         if (ignore_errors)
1044                                                 return false;
1045                                         
1046                                         if (p_mod == Parameter.Modifier.NONE)
1047                                                 ec.Report.Error (1677, loc, "Parameter `{0}' should not be declared with the `{1}' keyword",
1048                                                               (i + 1).ToString (), Parameter.GetModifierSignature (Parameters.FixedParameters [i].ModFlags));
1049                                         else
1050                                                 ec.Report.Error (1676, loc, "Parameter `{0}' must be declared with the `{1}' keyword",
1051                                                               (i+1).ToString (), Parameter.GetModifierSignature (p_mod));
1052                                         error = true;
1053                                 }
1054
1055                                 if (has_implicit_parameters)
1056                                         continue;
1057
1058                                 TypeSpec type = invoke_pd.Types [i];
1059                                 
1060                                 // We assume that generic parameters are always inflated
1061                                 if (TypeManager.IsGenericParameter (type))
1062                                         continue;
1063                                 
1064                                 if (TypeManager.HasElementType (type) && TypeManager.IsGenericParameter (TypeManager.GetElementType (type)))
1065                                         continue;
1066                                 
1067                                 if (!TypeSpecComparer.IsEqual (invoke_pd.Types [i], Parameters.Types [i])) {
1068                                         if (ignore_errors)
1069                                                 return false;
1070                                         
1071                                         ec.Report.Error (1678, loc, "Parameter `{0}' is declared as type `{1}' but should be `{2}'",
1072                                                       (i+1).ToString (),
1073                                                       Parameters.Types [i].GetSignatureForError (),
1074                                                       invoke_pd.Types [i].GetSignatureForError ());
1075                                         error = true;
1076                                 }
1077                         }
1078
1079                         return !error;
1080                 }
1081
1082                 //
1083                 // Infers type arguments based on explicit arguments
1084                 //
1085                 public bool ExplicitTypeInference (ResolveContext ec, TypeInferenceContext type_inference, TypeSpec delegate_type)
1086                 {
1087                         if (!HasExplicitParameters)
1088                                 return false;
1089
1090                         if (!delegate_type.IsDelegate) {
1091                                 if (!delegate_type.IsExpressionTreeType)
1092                                         return false;
1093
1094                                 delegate_type = TypeManager.GetTypeArguments (delegate_type) [0];
1095                                 if (!delegate_type.IsDelegate)
1096                                         return false;
1097                         }
1098                         
1099                         AParametersCollection d_params = Delegate.GetParameters (delegate_type);
1100                         if (d_params.Count != Parameters.Count)
1101                                 return false;
1102
1103                         var ptypes = Parameters.Types;
1104                         var dtypes = d_params.Types;
1105                         for (int i = 0; i < Parameters.Count; ++i) {
1106                                 if (type_inference.ExactInference (ptypes[i], dtypes[i]) == 0) {
1107                                         //
1108                                         // Continue when 0 (quick path) does not mean inference failure. Checking for
1109                                         // same type handles cases like int -> int
1110                                         //
1111                                         if (ptypes[i] == dtypes[i])
1112                                                 continue;
1113
1114                                         return false;
1115                                 }
1116                         }
1117
1118                         return true;
1119                 }
1120
1121                 public TypeSpec InferReturnType (ResolveContext ec, TypeInferenceContext tic, TypeSpec delegate_type)
1122                 {
1123                         Expression expr;
1124                         AnonymousExpression am;
1125
1126                         if (compatibles.TryGetValue (delegate_type, out expr)) {
1127                                 am = expr as AnonymousExpression;
1128                                 return am == null ? null : am.ReturnType;
1129                         }
1130
1131                         using (ec.Set (ResolveContext.Options.ProbingMode | ResolveContext.Options.InferReturnType)) {
1132                                 ReportPrinter prev;
1133                                 if (TypeInferenceReportPrinter != null) {
1134                                         prev = ec.Report.SetPrinter (TypeInferenceReportPrinter);
1135                                 } else {
1136                                         prev = null;
1137                                 }
1138
1139                                 var body = CompatibleMethodBody (ec, tic, null, delegate_type);
1140                                 if (body != null) {
1141                                         am = body.Compatible (ec, body);
1142                                 } else {
1143                                         am = null;
1144                                 }
1145
1146                                 if (TypeInferenceReportPrinter != null) {
1147                                         ec.Report.SetPrinter (prev);
1148                                 }
1149                         }
1150
1151                         if (am == null)
1152                                 return null;
1153
1154 //                      compatibles.Add (delegate_type, am);
1155                         return am.ReturnType;
1156                 }
1157
1158                 public override bool ContainsEmitWithAwait ()
1159                 {
1160                         return false;
1161                 }
1162
1163                 //
1164                 // Returns AnonymousMethod container if this anonymous method
1165                 // expression can be implicitly converted to the delegate type `delegate_type'
1166                 //
1167                 public Expression Compatible (ResolveContext ec, TypeSpec type)
1168                 {
1169                         Expression am;
1170                         if (compatibles.TryGetValue (type, out am))
1171                                 return am;
1172
1173                         TypeSpec delegate_type = CompatibleChecks (ec, type);
1174                         if (delegate_type == null)
1175                                 return null;
1176
1177                         //
1178                         // At this point its the first time we know the return type that is 
1179                         // needed for the anonymous method.  We create the method here.
1180                         //
1181
1182                         var invoke_mb = Delegate.GetInvokeMethod (delegate_type);
1183                         TypeSpec return_type = invoke_mb.ReturnType;
1184
1185                         //
1186                         // Second: the return type of the delegate must be compatible with 
1187                         // the anonymous type.   Instead of doing a pass to examine the block
1188                         // we satisfy the rule by setting the return type on the EmitContext
1189                         // to be the delegate type return type.
1190                         //
1191
1192                         var body = CompatibleMethodBody (ec, null, return_type, delegate_type);
1193                         if (body == null)
1194                                 return null;
1195
1196                         bool etree_conversion = delegate_type != type;
1197
1198                         try {
1199                                 if (etree_conversion) {
1200                                         if (ec.HasSet (ResolveContext.Options.ExpressionTreeConversion)) {
1201                                                 //
1202                                                 // Nested expression tree lambda use same scope as parent
1203                                                 // lambda, this also means no variable capturing between this
1204                                                 // and parent scope
1205                                                 //
1206                                                 am = body.Compatible (ec, ec.CurrentAnonymousMethod);
1207
1208                                                 //
1209                                                 // Quote nested expression tree
1210                                                 //
1211                                                 if (am != null)
1212                                                         am = new Quote (am);
1213                                         } else {
1214                                                 int errors = ec.Report.Errors;
1215
1216                                                 if (Block.IsAsync) {
1217                                                         ec.Report.Error (1989, loc, "Async lambda expressions cannot be converted to expression trees");
1218                                                 }
1219
1220                                                 using (ec.Set (ResolveContext.Options.ExpressionTreeConversion)) {
1221                                                         am = body.Compatible (ec);
1222                                                 }
1223
1224                                                 //
1225                                                 // Rewrite expressions into expression tree when targeting Expression<T>
1226                                                 //
1227                                                 if (am != null && errors == ec.Report.Errors)
1228                                                         am = CreateExpressionTree (ec, delegate_type);
1229                                         }
1230                                 } else {
1231                                         am = body.Compatible (ec);
1232
1233                                         if (body.DirectMethodGroupConversion != null) {
1234                                                 var errors_printer = new SessionReportPrinter ();
1235                                                 var old = ec.Report.SetPrinter (errors_printer);
1236                                                 var expr = new ImplicitDelegateCreation (delegate_type, body.DirectMethodGroupConversion, loc) {
1237                                                         AllowSpecialMethodsInvocation = true
1238                                                 }.Resolve (ec);
1239                                                 ec.Report.SetPrinter (old);
1240                                                 if (expr != null && errors_printer.ErrorsCount == 0)
1241                                                         am = expr;
1242                                         }
1243                                 }
1244                         } catch (CompletionResult) {
1245                                 throw;
1246                         } catch (FatalException) {
1247                                 throw;
1248                         } catch (Exception e) {
1249                                 throw new InternalErrorException (e, loc);
1250                         }
1251
1252                         if (!ec.IsInProbingMode) {
1253                                 compatibles.Add (type, am ?? EmptyExpression.Null);
1254                         }
1255
1256                         return am;
1257                 }
1258
1259                 protected virtual Expression CreateExpressionTree (ResolveContext ec, TypeSpec delegate_type)
1260                 {
1261                         return CreateExpressionTree (ec);
1262                 }
1263
1264                 public override Expression CreateExpressionTree (ResolveContext ec)
1265                 {
1266                         ec.Report.Error (1946, loc, "An anonymous method cannot be converted to an expression tree");
1267                         return null;
1268                 }
1269
1270                 protected virtual ParametersCompiled ResolveParameters (ResolveContext ec, TypeInferenceContext tic, TypeSpec delegate_type)
1271                 {
1272                         var delegate_parameters = Delegate.GetParameters (delegate_type);
1273
1274                         if (Parameters == ParametersCompiled.Undefined) {
1275                                 //
1276                                 // We provide a set of inaccessible parameters
1277                                 //
1278                                 Parameter[] fixedpars = new Parameter[delegate_parameters.Count];
1279
1280                                 for (int i = 0; i < delegate_parameters.Count; i++) {
1281                                         Parameter.Modifier i_mod = delegate_parameters.FixedParameters [i].ModFlags;
1282                                         if ((i_mod & Parameter.Modifier.OUT) != 0) {
1283                                                 if (!ec.IsInProbingMode) {
1284                                                         ec.Report.Error (1688, loc,
1285                                                                 "Cannot convert anonymous method block without a parameter list to delegate type `{0}' because it has one or more `out' parameters",
1286                                                                 delegate_type.GetSignatureForError ());
1287                                                 }
1288
1289                                                 return null;
1290                                         }
1291                                         fixedpars[i] = new Parameter (
1292                                                 new TypeExpression (delegate_parameters.Types [i], loc), null,
1293                                                 delegate_parameters.FixedParameters [i].ModFlags, null, loc);
1294                                 }
1295
1296                                 return ParametersCompiled.CreateFullyResolved (fixedpars, delegate_parameters.Types);
1297                         }
1298
1299                         if (!VerifyExplicitParameters (ec, delegate_type, delegate_parameters)) {
1300                                 return null;
1301                         }
1302
1303                         return Parameters;
1304                 }
1305
1306                 protected override Expression DoResolve (ResolveContext ec)
1307                 {
1308                         if (ec.HasSet (ResolveContext.Options.ConstantScope)) {
1309                                 ec.Report.Error (1706, loc, "Anonymous methods and lambda expressions cannot be used in the current context");
1310                                 return null;
1311                         }
1312
1313                         //
1314                         // Set class type, set type
1315                         //
1316
1317                         eclass = ExprClass.Value;
1318
1319                         //
1320                         // This hack means `The type is not accessible
1321                         // anywhere', we depend on special conversion
1322                         // rules.
1323                         // 
1324                         type = InternalType.AnonymousMethod;
1325
1326                         if (!DoResolveParameters (ec))
1327                                 return null;
1328
1329 #if !STATIC
1330                         // FIXME: The emitted code isn't very careful about reachability
1331                         // so, ensure we have a 'ret' at the end
1332                         BlockContext bc = ec as BlockContext;
1333                         if (bc != null && bc.CurrentBranching != null && bc.CurrentBranching.CurrentUsageVector.IsUnreachable)
1334                                 bc.NeedReturnLabel ();
1335 #endif
1336                         return this;
1337                 }
1338
1339                 protected virtual bool DoResolveParameters (ResolveContext rc)
1340                 {
1341                         return Parameters.Resolve (rc);
1342                 }
1343
1344                 public override void Emit (EmitContext ec)
1345                 {
1346                         // nothing, as we only exist to not do anything.
1347                 }
1348
1349                 public static void Error_AddressOfCapturedVar (ResolveContext ec, IVariableReference var, Location loc)
1350                 {
1351                         ec.Report.Error (1686, loc,
1352                                 "Local variable or parameter `{0}' cannot have their address taken and be used inside an anonymous method, lambda expression or query expression",
1353                                 var.Name);
1354                 }
1355
1356                 public override string GetSignatureForError ()
1357                 {
1358                         return ExprClassName;
1359                 }
1360
1361                 AnonymousMethodBody CompatibleMethodBody (ResolveContext ec, TypeInferenceContext tic, TypeSpec return_type, TypeSpec delegate_type)
1362                 {
1363                         ParametersCompiled p = ResolveParameters (ec, tic, delegate_type);
1364                         if (p == null)
1365                                 return null;
1366
1367                         ParametersBlock b = ec.IsInProbingMode ? (ParametersBlock) Block.PerformClone () : Block;
1368
1369                         if (b.IsAsync) {
1370                                 var rt = return_type;
1371                                 if (rt != null && rt.Kind != MemberKind.Void && rt != ec.Module.PredefinedTypes.Task.TypeSpec && !rt.IsGenericTask) {
1372                                         ec.Report.Error (4010, loc, "Cannot convert async {0} to delegate type `{1}'",
1373                                                 GetSignatureForError (), delegate_type.GetSignatureForError ());
1374
1375                                         return null;
1376                                 }
1377
1378                                 b = b.ConvertToAsyncTask (ec, ec.CurrentMemberDefinition.Parent.PartialContainer, p, return_type, delegate_type, loc);
1379                         }
1380
1381                         return CompatibleMethodFactory (return_type ?? InternalType.ErrorType, delegate_type, p, b);
1382                 }
1383
1384                 protected virtual AnonymousMethodBody CompatibleMethodFactory (TypeSpec return_type, TypeSpec delegate_type, ParametersCompiled p, ParametersBlock b)
1385                 {
1386                         return new AnonymousMethodBody (p, b, return_type, delegate_type, loc);
1387                 }
1388
1389                 protected override void CloneTo (CloneContext clonectx, Expression t)
1390                 {
1391                         AnonymousMethodExpression target = (AnonymousMethodExpression) t;
1392
1393                         target.Block = (ParametersBlock) clonectx.LookupBlock (Block);
1394                 }
1395                 
1396                 public override object Accept (StructuralVisitor visitor)
1397                 {
1398                         return visitor.Visit (this);
1399                 }
1400         }
1401
1402         //
1403         // Abstract expression for any block which requires variables hoisting
1404         //
1405         public abstract class AnonymousExpression : ExpressionStatement
1406         {
1407                 protected class AnonymousMethodMethod : Method
1408                 {
1409                         public readonly AnonymousExpression AnonymousMethod;
1410                         public readonly AnonymousMethodStorey Storey;
1411
1412                         public AnonymousMethodMethod (TypeDefinition parent, AnonymousExpression am, AnonymousMethodStorey storey,
1413                                                           TypeExpr return_type,
1414                                                           Modifiers mod, MemberName name,
1415                                                           ParametersCompiled parameters)
1416                                 : base (parent, return_type, mod | Modifiers.COMPILER_GENERATED,
1417                                                 name, parameters, null)
1418                         {
1419                                 this.AnonymousMethod = am;
1420                                 this.Storey = storey;
1421
1422                                 Parent.PartialContainer.Members.Add (this);
1423                                 Block = new ToplevelBlock (am.block, parameters);
1424                         }
1425
1426                         public override EmitContext CreateEmitContext (ILGenerator ig, SourceMethodBuilder sourceMethod)
1427                         {
1428                                 EmitContext ec = new EmitContext (this, ig, ReturnType, sourceMethod);
1429                                 ec.CurrentAnonymousMethod = AnonymousMethod;
1430                                 return ec;
1431                         }
1432
1433                         protected override void DefineTypeParameters ()
1434                         {
1435                                 // Type parameters were cloned
1436                         }
1437
1438                         protected override bool ResolveMemberType ()
1439                         {
1440                                 if (!base.ResolveMemberType ())
1441                                         return false;
1442
1443                                 if (Storey != null && Storey.Mutator != null) {
1444                                         if (!parameters.IsEmpty) {
1445                                                 var mutated = Storey.Mutator.Mutate (parameters.Types);
1446                                                 if (mutated != parameters.Types)
1447                                                         parameters = ParametersCompiled.CreateFullyResolved ((Parameter[]) parameters.FixedParameters, mutated);
1448                                         }
1449
1450                                         member_type = Storey.Mutator.Mutate (member_type);
1451                                 }
1452
1453                                 return true;
1454                         }
1455
1456                         public override void Emit ()
1457                         {
1458                                 if (MethodBuilder == null) {
1459                                         Define ();
1460                                 }
1461
1462                                 base.Emit ();
1463                         }
1464                 }
1465
1466                 protected readonly ParametersBlock block;
1467
1468                 public TypeSpec ReturnType;
1469
1470                 protected AnonymousExpression (ParametersBlock block, TypeSpec return_type, Location loc)
1471                 {
1472                         this.ReturnType = return_type;
1473                         this.block = block;
1474                         this.loc = loc;
1475                 }
1476
1477                 public abstract string ContainerType { get; }
1478                 public abstract bool IsIterator { get; }
1479                 public abstract AnonymousMethodStorey Storey { get; }
1480
1481                 //
1482                 // The block that makes up the body for the anonymous method
1483                 //
1484                 public ParametersBlock Block {
1485                         get {
1486                                 return block;
1487                         }
1488                 }
1489
1490                 public AnonymousExpression Compatible (ResolveContext ec)
1491                 {
1492                         return Compatible (ec, this);
1493                 }
1494
1495                 public AnonymousExpression Compatible (ResolveContext ec, AnonymousExpression ae)
1496                 {
1497                         if (block.Resolved)
1498                                 return this;
1499
1500                         // TODO: Implement clone
1501                         BlockContext aec = new BlockContext (ec, block, ReturnType);
1502                         aec.CurrentAnonymousMethod = ae;
1503
1504                         var am = this as AnonymousMethodBody;
1505
1506                         if (ec.HasSet (ResolveContext.Options.InferReturnType) && am != null) {
1507                                 am.ReturnTypeInference = new TypeInferenceContext ();
1508                         }
1509
1510                         var bc = ec as BlockContext;
1511                         if (bc != null)
1512                                 aec.FlowOffset = bc.FlowOffset;
1513
1514                         var errors = ec.Report.Errors;
1515
1516                         bool res = Block.Resolve (ec.CurrentBranching, aec, null);
1517
1518                         if (am != null && am.ReturnTypeInference != null) {
1519                                 am.ReturnTypeInference.FixAllTypes (ec);
1520                                 ReturnType = am.ReturnTypeInference.InferredTypeArguments [0];
1521                                 am.ReturnTypeInference = null;
1522
1523                                 //
1524                                 // If e is synchronous the inferred return type is T
1525                                 // If e is asynchronous the inferred return type is Task<T>
1526                                 //
1527                                 if (block.IsAsync && ReturnType != null) {
1528                                         ReturnType = ec.Module.PredefinedTypes.TaskGeneric.TypeSpec.MakeGenericType (ec, new [] { ReturnType });
1529                                 }
1530                         }
1531
1532                         if (res && errors != ec.Report.Errors)
1533                                 return null;
1534
1535                         return res ? this : null;
1536                 }
1537
1538                 public override bool ContainsEmitWithAwait ()
1539                 {
1540                         return false;
1541                 }
1542
1543                 public void SetHasThisAccess ()
1544                 {
1545                         ExplicitBlock b = block;
1546                         do {
1547                                 if (b.HasCapturedThis)
1548                                         return;
1549
1550                                 b.HasCapturedThis = true;
1551                                 b = b.Parent == null ? null : b.Parent.Explicit;
1552                         } while (b != null);
1553                 }
1554         }
1555
1556         public class AnonymousMethodBody : AnonymousExpression
1557         {
1558                 protected readonly ParametersCompiled parameters;
1559                 AnonymousMethodStorey storey;
1560
1561                 AnonymousMethodMethod method;
1562                 Field am_cache;
1563                 string block_name;
1564                 TypeInferenceContext return_inference;
1565
1566                 public AnonymousMethodBody (ParametersCompiled parameters,
1567                                         ParametersBlock block, TypeSpec return_type, TypeSpec delegate_type,
1568                                         Location loc)
1569                         : base (block, return_type, loc)
1570                 {
1571                         this.type = delegate_type;
1572                         this.parameters = parameters;
1573                 }
1574
1575                 #region Properties
1576
1577                 public override string ContainerType {
1578                         get { return "anonymous method"; }
1579                 }
1580
1581                 //
1582                 // Method-group instance for lambdas which can be replaced with
1583                 // simple method group call
1584                 //
1585                 public MethodGroupExpr DirectMethodGroupConversion {
1586                         get; set;
1587                 }
1588
1589                 public override bool IsIterator {
1590                         get {
1591                                 return false;
1592                         }
1593                 }
1594
1595                 public ParametersCompiled Parameters {
1596                         get {
1597                                 return parameters;
1598                         }
1599                 }
1600
1601                 public TypeInferenceContext ReturnTypeInference {
1602                         get {
1603                                 return return_inference;
1604                         }
1605                         set {
1606                                 return_inference = value;
1607                         }
1608                 }
1609
1610                 public override AnonymousMethodStorey Storey {
1611                         get {
1612                                 return storey;
1613                         }
1614                 }
1615
1616                 #endregion
1617
1618                 public override Expression CreateExpressionTree (ResolveContext ec)
1619                 {
1620                         ec.Report.Error (1945, loc, "An expression tree cannot contain an anonymous method expression");
1621                         return null;
1622                 }
1623
1624                 bool Define (ResolveContext ec)
1625                 {
1626                         if (!Block.Resolved && Compatible (ec) == null)
1627                                 return false;
1628
1629                         if (block_name == null) {
1630                                 MemberCore mc = (MemberCore) ec.MemberContext;
1631                                 block_name = mc.MemberName.Basename;
1632                         }
1633
1634                         return true;
1635                 }
1636
1637                 //
1638                 // Creates a host for the anonymous method
1639                 //
1640                 AnonymousMethodMethod DoCreateMethodHost (EmitContext ec)
1641                 {
1642                         //
1643                         // Anonymous method body can be converted to
1644                         //
1645                         // 1, an instance method in current scope when only `this' is hoisted
1646                         // 2, a static method in current scope when neither `this' nor any variable is hoisted
1647                         // 3, an instance method in compiler generated storey when any hoisted variable exists
1648                         //
1649
1650                         Modifiers modifiers;
1651                         TypeDefinition parent = null;
1652
1653                         var src_block = Block.Original.Explicit;
1654                         if (src_block.HasCapturedVariable || src_block.HasCapturedThis) {
1655                                 parent = storey = FindBestMethodStorey ();
1656
1657                                 if (storey == null) {
1658                                         var top_block = src_block.ParametersBlock.TopBlock;
1659                                         var sm = top_block.StateMachine;
1660
1661                                         if (src_block.HasCapturedThis) {
1662                                                 //
1663                                                 // Remove hoisted 'this' request when simple instance method is
1664                                                 // enough (no hoisted variables only 'this')
1665                                                 //
1666                                                 if (src_block.ParametersBlock.StateMachine == null)
1667                                                         top_block.RemoveThisReferenceFromChildrenBlock (src_block);
1668
1669                                                 //
1670                                                 // Special case where parent class is used to emit instance method
1671                                                 // because currect storey is of value type (async host). We cannot
1672                                                 // use ldftn on non-boxed instances either to share mutated state
1673                                                 //
1674                                                 if (sm != null && sm.Kind == MemberKind.Struct) {
1675                                                         parent = sm.Parent.PartialContainer;
1676                                                 }
1677                                         }
1678
1679                                         //
1680                                         // For iterators we can host everything in one class
1681                                         //
1682                                         if (sm is IteratorStorey)
1683                                                 parent = storey = sm;
1684                                 }
1685
1686                                 modifiers = storey != null ? Modifiers.INTERNAL : Modifiers.PRIVATE;
1687                         } else {
1688                                 if (ec.CurrentAnonymousMethod != null)
1689                                         parent = storey = ec.CurrentAnonymousMethod.Storey;
1690
1691                                 modifiers = Modifiers.STATIC | Modifiers.PRIVATE;
1692                         }
1693
1694                         if (parent == null)
1695                                 parent = ec.CurrentTypeDefinition.Parent.PartialContainer;
1696
1697                         string name = CompilerGeneratedContainer.MakeName (parent != storey ? block_name : null,
1698                                 "m", null, ec.Module.CounterAnonymousMethods++);
1699
1700                         MemberName member_name;
1701                         if (storey == null && ec.CurrentTypeParameters != null) {
1702
1703                                 var hoisted_tparams = ec.CurrentTypeParameters;
1704                                 var type_params = new TypeParameters (hoisted_tparams.Count);
1705                                 for (int i = 0; i < hoisted_tparams.Count; ++i) {
1706                                     type_params.Add (hoisted_tparams[i].CreateHoistedCopy (null));
1707                                 }
1708
1709                                 member_name = new MemberName (name, type_params, Location);
1710                         } else {
1711                                 member_name = new MemberName (name, Location);
1712                         }
1713
1714                         return new AnonymousMethodMethod (parent,
1715                                 this, storey, new TypeExpression (ReturnType, Location), modifiers,
1716                                 member_name, parameters);
1717                 }
1718
1719                 protected override Expression DoResolve (ResolveContext ec)
1720                 {
1721                         if (!Define (ec))
1722                                 return null;
1723
1724                         eclass = ExprClass.Value;
1725                         return this;
1726                 }
1727
1728                 public override void Emit (EmitContext ec)
1729                 {
1730                         //
1731                         // Use same anonymous method implementation for scenarios where same
1732                         // code is used from multiple blocks, e.g. field initializers
1733                         //
1734                         if (method == null) {
1735                                 //
1736                                 // Delay an anonymous method definition to avoid emitting unused code
1737                                 // for unreachable blocks or expression trees
1738                                 //
1739                                 method = DoCreateMethodHost (ec);
1740                                 method.Define ();
1741                                 method.PrepareEmit ();
1742                         }
1743
1744                         bool is_static = (method.ModFlags & Modifiers.STATIC) != 0;
1745                         if (is_static && am_cache == null) {
1746                                 //
1747                                 // Creates a field cache to store delegate instance if it's not generic
1748                                 //
1749                                 if (!method.MemberName.IsGeneric) {
1750                                         var parent = method.Parent.PartialContainer;
1751                                         int id = parent.AnonymousMethodsCounter++;
1752                                         var cache_type = storey != null && storey.Mutator != null ? storey.Mutator.Mutate (type) : type;
1753
1754                                         am_cache = new Field (parent, new TypeExpression (cache_type, loc),
1755                                                 Modifiers.STATIC | Modifiers.PRIVATE | Modifiers.COMPILER_GENERATED,
1756                                                 new MemberName (CompilerGeneratedContainer.MakeName (null, "f", "am$cache", id), loc), null);
1757                                         am_cache.Define ();
1758                                         parent.AddField (am_cache);
1759                                 } else {
1760                                         // TODO: Implement caching of generated generic static methods
1761                                         //
1762                                         // Idea:
1763                                         //
1764                                         // Some extra class is needed to capture variable generic type
1765                                         // arguments. Maybe we could re-use anonymous types, with a unique
1766                                         // anonymous method id, but they are quite heavy.
1767                                         //
1768                                         // Consider : "() => typeof(T);"
1769                                         //
1770                                         // We need something like
1771                                         // static class Wrap<Tn, Tm, DelegateType> {
1772                                         //              public static DelegateType cache;
1773                                         // }
1774                                         //
1775                                         // We then specialize local variable to capture all generic parameters
1776                                         // and delegate type, e.g. "Wrap<Ta, Tb, DelegateTypeInst> cache;"
1777                                         //
1778                                 }
1779                         }
1780
1781                         Label l_initialized = ec.DefineLabel ();
1782
1783                         if (am_cache != null) {
1784                                 ec.Emit (OpCodes.Ldsfld, am_cache.Spec);
1785                                 ec.Emit (OpCodes.Brtrue_S, l_initialized);
1786                         }
1787
1788                         //
1789                         // Load method delegate implementation
1790                         //
1791
1792                         if (is_static) {
1793                                 ec.EmitNull ();
1794                         } else if (storey != null) {
1795                                 Expression e = storey.GetStoreyInstanceExpression (ec).Resolve (new ResolveContext (ec.MemberContext));
1796                                 if (e != null) {
1797                                         e.Emit (ec);
1798                                 }
1799                         } else {
1800                                 ec.EmitThis ();
1801
1802                                 //
1803                                 // Special case for value type storey where this is not lifted but
1804                                 // droped off to parent class
1805                                 //
1806                                 for (var b = Block.Parent; b != null; b = b.Parent) {
1807                                         if (b.ParametersBlock.StateMachine != null) {
1808                                                 ec.Emit (OpCodes.Ldfld, b.ParametersBlock.StateMachine.HoistedThis.Field.Spec);
1809                                                 break;
1810                                         }
1811                                 }
1812                         }
1813
1814                         var delegate_method = method.Spec;
1815                         if (storey != null && storey.MemberName.IsGeneric) {
1816                                 TypeSpec t = storey.Instance.Type;
1817
1818                                 //
1819                                 // Mutate anonymous method instance type if we are in nested
1820                                 // hoisted generic anonymous method storey
1821                                 //
1822                                 if (ec.IsAnonymousStoreyMutateRequired) {
1823                                         t = storey.Mutator.Mutate (t);
1824                                 }
1825
1826                                 ec.Emit (OpCodes.Ldftn, TypeBuilder.GetMethod (t.GetMetaInfo (), (MethodInfo) delegate_method.GetMetaInfo ()));
1827                         } else {
1828                                 if (delegate_method.IsGeneric)
1829                                         delegate_method = delegate_method.MakeGenericMethod (ec.MemberContext, method.TypeParameters);
1830
1831                                 ec.Emit (OpCodes.Ldftn, delegate_method);
1832                         }
1833
1834                         var constructor_method = Delegate.GetConstructor (type);
1835                         ec.Emit (OpCodes.Newobj, constructor_method);
1836
1837                         if (am_cache != null) {
1838                                 ec.Emit (OpCodes.Stsfld, am_cache.Spec);
1839                                 ec.MarkLabel (l_initialized);
1840                                 ec.Emit (OpCodes.Ldsfld, am_cache.Spec);
1841                         }
1842                 }
1843
1844                 public override void EmitStatement (EmitContext ec)
1845                 {
1846                         throw new NotImplementedException ();
1847                 }
1848
1849                 //
1850                 // Look for the best storey for this anonymous method
1851                 //
1852                 AnonymousMethodStorey FindBestMethodStorey ()
1853                 {
1854                         //
1855                         // Use the nearest parent block which has a storey
1856                         //
1857                         for (Block b = Block.Parent; b != null; b = b.Parent) {
1858                                 AnonymousMethodStorey s = b.Explicit.AnonymousMethodStorey;
1859                                 if (s != null)
1860                                         return s;
1861                         }
1862                                         
1863                         return null;
1864                 }
1865
1866                 public override string GetSignatureForError ()
1867                 {
1868                         return type.GetSignatureForError ();
1869                 }
1870         }
1871
1872         //
1873         // Anonymous type container
1874         //
1875         public class AnonymousTypeClass : CompilerGeneratedContainer
1876         {
1877                 public const string ClassNamePrefix = "<>__AnonType";
1878                 public const string SignatureForError = "anonymous type";
1879                 
1880                 readonly IList<AnonymousTypeParameter> parameters;
1881
1882                 private AnonymousTypeClass (ModuleContainer parent, MemberName name, IList<AnonymousTypeParameter> parameters, Location loc)
1883                         : base (parent, name, parent.Evaluator != null ? Modifiers.PUBLIC : Modifiers.INTERNAL)
1884                 {
1885                         this.parameters = parameters;
1886                 }
1887
1888                 public static AnonymousTypeClass Create (TypeContainer parent, IList<AnonymousTypeParameter> parameters, Location loc)
1889                 {
1890                         string name = ClassNamePrefix + parent.Module.CounterAnonymousTypes++;
1891
1892                         ParametersCompiled all_parameters;
1893                         TypeParameters tparams = null;
1894                         SimpleName[] t_args;
1895
1896                         if (parameters.Count == 0) {
1897                                 all_parameters = ParametersCompiled.EmptyReadOnlyParameters;
1898                                 t_args = null;
1899                         } else {
1900                                 t_args = new SimpleName[parameters.Count];
1901                                 tparams = new TypeParameters ();
1902                                 Parameter[] ctor_params = new Parameter[parameters.Count];
1903                                 for (int i = 0; i < parameters.Count; ++i) {
1904                                         AnonymousTypeParameter p = parameters[i];
1905                                         for (int ii = 0; ii < i; ++ii) {
1906                                                 if (parameters[ii].Name == p.Name) {
1907                                                         parent.Compiler.Report.Error (833, parameters[ii].Location,
1908                                                                 "`{0}': An anonymous type cannot have multiple properties with the same name",
1909                                                                         p.Name);
1910
1911                                                         p = new AnonymousTypeParameter (null, "$" + i.ToString (), p.Location);
1912                                                         parameters[i] = p;
1913                                                         break;
1914                                                 }
1915                                         }
1916
1917                                         t_args[i] = new SimpleName ("<" + p.Name + ">__T", p.Location);
1918                                         tparams.Add (new TypeParameter (i, new MemberName (t_args[i].Name, p.Location), null, null, Variance.None));
1919                                         ctor_params[i] = new Parameter (t_args[i], p.Name, Parameter.Modifier.NONE, null, p.Location);
1920                                 }
1921
1922                                 all_parameters = new ParametersCompiled (ctor_params);
1923                         }
1924
1925                         //
1926                         // Create generic anonymous type host with generic arguments
1927                         // named upon properties names
1928                         //
1929                         AnonymousTypeClass a_type = new AnonymousTypeClass (parent.Module, new MemberName (name, tparams, loc), parameters, loc);
1930
1931                         Constructor c = new Constructor (a_type, name, Modifiers.PUBLIC | Modifiers.DEBUGGER_HIDDEN,
1932                                 null, all_parameters, loc);
1933                         c.Block = new ToplevelBlock (parent.Module.Compiler, c.ParameterInfo, loc);
1934
1935                         // 
1936                         // Create fields and constructor body with field initialization
1937                         //
1938                         bool error = false;
1939                         for (int i = 0; i < parameters.Count; ++i) {
1940                                 AnonymousTypeParameter p = parameters [i];
1941
1942                                 Field f = new Field (a_type, t_args [i], Modifiers.PRIVATE | Modifiers.READONLY | Modifiers.DEBUGGER_HIDDEN,
1943                                         new MemberName ("<" + p.Name + ">", p.Location), null);
1944
1945                                 if (!a_type.AddField (f)) {
1946                                         error = true;
1947                                         continue;
1948                                 }
1949
1950                                 c.Block.AddStatement (new StatementExpression (
1951                                         new SimpleAssign (new MemberAccess (new This (p.Location), f.Name),
1952                                                 c.Block.GetParameterReference (i, p.Location))));
1953
1954                                 ToplevelBlock get_block = new ToplevelBlock (parent.Module.Compiler, p.Location);
1955                                 get_block.AddStatement (new Return (
1956                                         new MemberAccess (new This (p.Location), f.Name), p.Location));
1957
1958                                 Property prop = new Property (a_type, t_args [i], Modifiers.PUBLIC,
1959                                         new MemberName (p.Name, p.Location), null);
1960                                 prop.Get = new Property.GetMethod (prop, 0, null, p.Location);
1961                                 prop.Get.Block = get_block;
1962                                 a_type.AddMember (prop);
1963                         }
1964
1965                         if (error)
1966                                 return null;
1967
1968                         a_type.AddConstructor (c);
1969                         return a_type;
1970                 }
1971                 
1972                 protected override bool DoDefineMembers ()
1973                 {
1974                         if (!base.DoDefineMembers ())
1975                                 return false;
1976
1977                         Location loc = Location;
1978
1979                         var equals_parameters = ParametersCompiled.CreateFullyResolved (
1980                                 new Parameter (new TypeExpression (Compiler.BuiltinTypes.Object, loc), "obj", 0, null, loc), Compiler.BuiltinTypes.Object);
1981
1982                         Method equals = new Method (this, new TypeExpression (Compiler.BuiltinTypes.Bool, loc),
1983                                 Modifiers.PUBLIC | Modifiers.OVERRIDE | Modifiers.DEBUGGER_HIDDEN, new MemberName ("Equals", loc),
1984                                 equals_parameters, null);
1985
1986                         equals_parameters[0].Resolve (equals, 0);
1987
1988                         Method tostring = new Method (this, new TypeExpression (Compiler.BuiltinTypes.String, loc),
1989                                 Modifiers.PUBLIC | Modifiers.OVERRIDE | Modifiers.DEBUGGER_HIDDEN, new MemberName ("ToString", loc),
1990                                 Mono.CSharp.ParametersCompiled.EmptyReadOnlyParameters, null);
1991
1992                         ToplevelBlock equals_block = new ToplevelBlock (Compiler, equals.ParameterInfo, loc);
1993
1994                         TypeExpr current_type;
1995                         if (CurrentTypeParameters != null) {
1996                                 var targs = new TypeArguments ();
1997                                 for (int i = 0; i < CurrentTypeParameters.Count; ++i) {
1998                                         targs.Add (new TypeParameterExpr (CurrentTypeParameters[i], Location));
1999                                 }
2000
2001                                 current_type = new GenericTypeExpr (Definition, targs, loc);
2002                         } else {
2003                                 current_type = new TypeExpression (Definition, loc);
2004                         }
2005
2006                         var li_other = LocalVariable.CreateCompilerGenerated (CurrentType, equals_block, loc);
2007                         equals_block.AddStatement (new BlockVariable (new TypeExpression (li_other.Type, loc), li_other));
2008                         var other_variable = new LocalVariableReference (li_other, loc);
2009
2010                         MemberAccess system_collections_generic = new MemberAccess (new MemberAccess (
2011                                 new QualifiedAliasMember ("global", "System", loc), "Collections", loc), "Generic", loc);
2012
2013                         Expression rs_equals = null;
2014                         Expression string_concat = new StringConstant (Compiler.BuiltinTypes, "{", loc);
2015                         Expression rs_hashcode = new IntConstant (Compiler.BuiltinTypes, -2128831035, loc);
2016                         for (int i = 0; i < parameters.Count; ++i) {
2017                                 var p = parameters [i];
2018                                 var f = (Field) Members [i * 2];
2019
2020                                 MemberAccess equality_comparer = new MemberAccess (new MemberAccess (
2021                                         system_collections_generic, "EqualityComparer",
2022                                                 new TypeArguments (new SimpleName (CurrentTypeParameters [i].Name, loc)), loc),
2023                                                 "Default", loc);
2024
2025                                 Arguments arguments_equal = new Arguments (2);
2026                                 arguments_equal.Add (new Argument (new MemberAccess (new This (f.Location), f.Name)));
2027                                 arguments_equal.Add (new Argument (new MemberAccess (other_variable, f.Name)));
2028
2029                                 Expression field_equal = new Invocation (new MemberAccess (equality_comparer,
2030                                         "Equals", loc), arguments_equal);
2031
2032                                 Arguments arguments_hashcode = new Arguments (1);
2033                                 arguments_hashcode.Add (new Argument (new MemberAccess (new This (f.Location), f.Name)));
2034                                 Expression field_hashcode = new Invocation (new MemberAccess (equality_comparer,
2035                                         "GetHashCode", loc), arguments_hashcode);
2036
2037                                 IntConstant FNV_prime = new IntConstant (Compiler.BuiltinTypes, 16777619, loc);                         
2038                                 rs_hashcode = new Binary (Binary.Operator.Multiply,
2039                                         new Binary (Binary.Operator.ExclusiveOr, rs_hashcode, field_hashcode),
2040                                         FNV_prime);
2041
2042                                 Expression field_to_string = new Conditional (new BooleanExpression (new Binary (Binary.Operator.Inequality,
2043                                         new MemberAccess (new This (f.Location), f.Name), new NullLiteral (loc))),
2044                                         new Invocation (new MemberAccess (
2045                                                 new MemberAccess (new This (f.Location), f.Name), "ToString"), null),
2046                                         new StringConstant (Compiler.BuiltinTypes, string.Empty, loc), loc);
2047
2048                                 if (rs_equals == null) {
2049                                         rs_equals = field_equal;
2050                                         string_concat = new Binary (Binary.Operator.Addition,
2051                                                 string_concat,
2052                                                 new Binary (Binary.Operator.Addition,
2053                                                         new StringConstant (Compiler.BuiltinTypes, " " + p.Name + " = ", loc),
2054                                                         field_to_string));
2055                                         continue;
2056                                 }
2057
2058                                 //
2059                                 // Implementation of ToString () body using string concatenation
2060                                 //                              
2061                                 string_concat = new Binary (Binary.Operator.Addition,
2062                                         new Binary (Binary.Operator.Addition,
2063                                                 string_concat,
2064                                                 new StringConstant (Compiler.BuiltinTypes, ", " + p.Name + " = ", loc)),
2065                                         field_to_string);
2066
2067                                 rs_equals = new Binary (Binary.Operator.LogicalAnd, rs_equals, field_equal);
2068                         }
2069
2070                         string_concat = new Binary (Binary.Operator.Addition,
2071                                 string_concat,
2072                                 new StringConstant (Compiler.BuiltinTypes, " }", loc));
2073
2074                         //
2075                         // Equals (object obj) override
2076                         //              
2077                         var other_variable_assign = new TemporaryVariableReference (li_other, loc);
2078                         equals_block.AddStatement (new StatementExpression (
2079                                 new SimpleAssign (other_variable_assign,
2080                                         new As (equals_block.GetParameterReference (0, loc),
2081                                                 current_type, loc), loc)));
2082
2083                         Expression equals_test = new Binary (Binary.Operator.Inequality, other_variable, new NullLiteral (loc));
2084                         if (rs_equals != null)
2085                                 equals_test = new Binary (Binary.Operator.LogicalAnd, equals_test, rs_equals);
2086                         equals_block.AddStatement (new Return (equals_test, loc));
2087
2088                         equals.Block = equals_block;
2089                         equals.Define ();
2090                         equals.PrepareEmit ();
2091                         Members.Add (equals);
2092
2093                         //
2094                         // GetHashCode () override
2095                         //
2096                         Method hashcode = new Method (this, new TypeExpression (Compiler.BuiltinTypes.Int, loc),
2097                                 Modifiers.PUBLIC | Modifiers.OVERRIDE | Modifiers.DEBUGGER_HIDDEN,
2098                                 new MemberName ("GetHashCode", loc),
2099                                 Mono.CSharp.ParametersCompiled.EmptyReadOnlyParameters, null);
2100
2101                         //
2102                         // Modified FNV with good avalanche behavior and uniform
2103                         // distribution with larger hash sizes.
2104                         //
2105                         // const int FNV_prime = 16777619;
2106                         // int hash = (int) 2166136261;
2107                         // foreach (int d in data)
2108                         //     hash = (hash ^ d) * FNV_prime;
2109                         // hash += hash << 13;
2110                         // hash ^= hash >> 7;
2111                         // hash += hash << 3;
2112                         // hash ^= hash >> 17;
2113                         // hash += hash << 5;
2114
2115                         ToplevelBlock hashcode_top = new ToplevelBlock (Compiler, loc);
2116                         Block hashcode_block = new Block (hashcode_top, loc, loc);
2117                         hashcode_top.AddStatement (new Unchecked (hashcode_block, loc));
2118
2119                         var li_hash = LocalVariable.CreateCompilerGenerated (Compiler.BuiltinTypes.Int, hashcode_top, loc);
2120                         hashcode_block.AddStatement (new BlockVariable (new TypeExpression (li_hash.Type, loc), li_hash));
2121                         LocalVariableReference hash_variable_assign = new LocalVariableReference (li_hash, loc);
2122                         hashcode_block.AddStatement (new StatementExpression (
2123                                 new SimpleAssign (hash_variable_assign, rs_hashcode)));
2124
2125                         var hash_variable = new LocalVariableReference (li_hash, loc);
2126                         hashcode_block.AddStatement (new StatementExpression (
2127                                 new CompoundAssign (Binary.Operator.Addition, hash_variable,
2128                                         new Binary (Binary.Operator.LeftShift, hash_variable, new IntConstant (Compiler.BuiltinTypes, 13, loc)))));
2129                         hashcode_block.AddStatement (new StatementExpression (
2130                                 new CompoundAssign (Binary.Operator.ExclusiveOr, hash_variable,
2131                                         new Binary (Binary.Operator.RightShift, hash_variable, new IntConstant (Compiler.BuiltinTypes, 7, loc)))));
2132                         hashcode_block.AddStatement (new StatementExpression (
2133                                 new CompoundAssign (Binary.Operator.Addition, hash_variable,
2134                                         new Binary (Binary.Operator.LeftShift, hash_variable, new IntConstant (Compiler.BuiltinTypes, 3, loc)))));
2135                         hashcode_block.AddStatement (new StatementExpression (
2136                                 new CompoundAssign (Binary.Operator.ExclusiveOr, hash_variable,
2137                                         new Binary (Binary.Operator.RightShift, hash_variable, new IntConstant (Compiler.BuiltinTypes, 17, loc)))));
2138                         hashcode_block.AddStatement (new StatementExpression (
2139                                 new CompoundAssign (Binary.Operator.Addition, hash_variable,
2140                                         new Binary (Binary.Operator.LeftShift, hash_variable, new IntConstant (Compiler.BuiltinTypes, 5, loc)))));
2141
2142                         hashcode_block.AddStatement (new Return (hash_variable, loc));
2143                         hashcode.Block = hashcode_top;
2144                         hashcode.Define ();
2145                         hashcode.PrepareEmit ();
2146                         Members.Add (hashcode);
2147
2148                         //
2149                         // ToString () override
2150                         //
2151
2152                         ToplevelBlock tostring_block = new ToplevelBlock (Compiler, loc);
2153                         tostring_block.AddStatement (new Return (string_concat, loc));
2154                         tostring.Block = tostring_block;
2155                         tostring.Define ();
2156                         tostring.PrepareEmit ();
2157                         Members.Add (tostring);
2158
2159                         return true;
2160                 }
2161
2162                 public override string GetSignatureForError ()
2163                 {
2164                         return SignatureForError;
2165                 }
2166
2167                 public override CompilationSourceFile GetCompilationSourceFile ()
2168                 {
2169                         return null;
2170                 }
2171
2172                 public IList<AnonymousTypeParameter> Parameters {
2173                         get {
2174                                 return parameters;
2175                         }
2176                 }
2177         }
2178 }