Update copyright notices
[mono.git] / mcs / mcs / anonymous.cs
1 //
2 // anonymous.cs: Support for anonymous methods
3 //
4 // Author:
5 //   Miguel de Icaza (miguel@ximain.com)
6 //   Marek Safar (marek.safar@gmail.com)
7 //
8 // Dual licensed under the terms of the MIT X11 or GNU GPL
9 // Copyright 2003-2008 Novell, Inc.
10 //
11 // TODO: Ideally, we should have the helper classes emited as a hierarchy to map
12 // their nesting, and have the visibility set to private, instead of NestedAssembly
13 //
14 //
15 //
16
17 using System;
18 using System.Text;
19 using System.Collections;
20 using System.Reflection;
21 using System.Reflection.Emit;
22
23 namespace Mono.CSharp {
24
25         public abstract class CompilerGeneratedClass : Class
26         {
27                 GenericMethod generic_method;
28                 static int next_index = 0;
29
30                 private static MemberName MakeProxyName (GenericMethod generic, Location loc)
31                 {
32                         string name = MakeName (null, "CompilerGenerated");
33                         if (generic != null) {
34                                 TypeArguments args = new TypeArguments (loc);
35                                 foreach (TypeParameter tparam in generic.CurrentTypeParameters)
36                                         args.Add (new SimpleName (tparam.Name, loc));
37                                 return new MemberName (name, args, loc);
38                         } else
39                                 return new MemberName (name, loc);
40                 }
41
42                 public static string MakeName (string host, string prefix)
43                 {
44                         return "<" + host + ">c__" + prefix + next_index++;
45                 }
46                 
47                 public static void Reset ()
48                 {
49                         next_index = 0;
50                 }
51
52                 protected CompilerGeneratedClass (DeclSpace parent,
53                                         MemberName name, int mod, Location loc) :
54                         base (parent.NamespaceEntry, parent, name, mod | Modifiers.COMPILER_GENERATED, null)
55                 {
56                         parent.PartialContainer.AddCompilerGeneratedClass (this);
57                 }
58
59                 protected CompilerGeneratedClass (DeclSpace parent, GenericMethod generic,
60                                                   int mod, Location loc)
61                         : this (parent, MakeProxyName (generic, loc), mod, loc)
62                 {
63                         this.generic_method = generic;
64
65                         if (generic != null) {
66                                 ArrayList list = new ArrayList ();
67                                 foreach (TypeParameter tparam in generic.TypeParameters) {
68                                         if (tparam.Constraints != null)
69                                                 list.Add (tparam.Constraints.Clone ());
70                                 }
71                                 SetParameterInfo (list);
72                         }
73
74                 }
75
76                 protected override bool DefineNestedTypes ()
77                 {
78                         RootContext.RegisterCompilerGeneratedType (TypeBuilder);
79                         return base.DefineNestedTypes ();
80                 }
81
82                 protected override bool DoDefineMembers ()
83                 {
84                         members_defined = true;
85
86                         if (!base.DoDefineMembers ())
87                                 return false;
88
89                         if (CompilerGenerated != null) {
90                                 foreach (CompilerGeneratedClass c in CompilerGenerated) {
91                                         if (!c.DefineMembers ())
92                                                 throw new InternalErrorException ();
93                                 }
94                         }
95
96                         return true;
97                 }
98
99                 protected override bool DoResolveMembers ()
100                 {
101                         if (CompilerGenerated != null) {
102                                 foreach (CompilerGeneratedClass c in CompilerGenerated) {
103                                         if (!c.ResolveMembers ())
104                                                 return false;
105                                 }
106                         }
107
108                         return base.DoResolveMembers ();
109                 }
110
111                 public GenericMethod GenericMethod {
112                         get { return generic_method; }
113                 }
114
115                 public Parameters InflateParameters (Parameters ps)
116                 {
117                         if (generic_method == null)
118                                 return ps;
119
120                         int n = ps.Count;
121                         if (n == 0)
122                                 return ps;
123
124                         Parameter[] inflated_params = new Parameter [n];
125                         Type[] inflated_types = new Type [n];
126
127                         for (int i = 0; i < n; ++i) {
128                                 Parameter p = ps [i];
129                                 Type it = InflateType (p.ExternalType ()).ResolveAsTypeTerminal (this, false).Type;
130                                 inflated_types [i] = it;
131                                 inflated_params [i] = new Parameter (it, p.Name, p.ModFlags, p.OptAttributes, p.Location);
132                         }
133                         return Parameters.CreateFullyResolved (inflated_params, inflated_types);
134                 }
135
136                 public TypeExpr InflateType (Type it)
137                 {
138 #if GMCS_SOURCE
139                         if (generic_method == null)
140                                 return new TypeExpression (it, Location);
141
142                         if (it.IsGenericParameter && (it.DeclaringMethod != null)) {
143                                 int pos = it.GenericParameterPosition;
144                                 it = CurrentTypeParameters [pos].Type;
145                         } else if (it.IsGenericType) {
146                                 Type[] args = it.GetGenericArguments ();
147
148                                 TypeArguments inflated = new TypeArguments (Location);
149                                 foreach (Type t in args)
150                                         inflated.Add (InflateType (t));
151
152                                 return new ConstructedType (it, inflated, Location);
153                         } else if (it.IsArray) {
154                                 TypeExpr et_expr = InflateType (it.GetElementType ());
155                                 int rank = it.GetArrayRank ();
156
157                                 Type et = et_expr.ResolveAsTypeTerminal (this, false).Type;
158                                 it = et.MakeArrayType (rank);
159                         }
160 #endif
161
162                         return new TypeExpression (it, Location);
163                 }
164
165                 public Field CaptureVariable (string name, TypeExpr type)
166                 {
167                         if (members_defined)
168                                 throw new InternalErrorException ("Helper class already defined!");
169                         if (type == null)
170                                 throw new ArgumentNullException ();
171
172                         return new CapturedVariableField (this, name, type);
173                 }
174
175                 bool members_defined;
176
177                 internal void CheckMembersDefined ()
178                 {
179                         if (members_defined)
180                                 throw new InternalErrorException ("Helper class already defined!");
181                 }
182
183                 protected class CapturedVariableField : Field
184                 {
185                         public CapturedVariableField (CompilerGeneratedClass helper, string name,
186                                                       TypeExpr type)
187                                 : base (helper, type, Modifiers.INTERNAL, name, null, helper.Location)
188                         {
189                                 helper.AddField (this);
190                         }
191                 }
192         }
193
194         public class ScopeInfo : CompilerGeneratedClass
195         {
196                 protected readonly RootScopeInfo RootScope;
197                 new public readonly DeclSpace Parent;
198                 public readonly int ID = ++next_id;
199                 public readonly Block ScopeBlock;
200                 protected ScopeInitializer scope_initializer;
201
202                 readonly Hashtable locals = new Hashtable ();
203                 readonly Hashtable captured_scopes = new Hashtable ();
204                 Hashtable captured_params;
205
206                 static int next_id;
207
208                 public static ScopeInfo CreateScope (Block block)
209                 {
210                         ToplevelBlock toplevel = block.Toplevel;
211                         AnonymousContainer ac = toplevel.AnonymousContainer;
212
213                         Report.Debug (128, "CREATE SCOPE", block, block.ScopeInfo, toplevel, ac);
214
215                         if (ac == null)
216                                 return new ScopeInfo (block, toplevel.RootScope.Parent,
217                                                       toplevel.RootScope.GenericMethod);
218
219                         Report.Debug (128, "CREATE SCOPE #1", ac, ac.Host, ac.Scope, ac.Block,
220                                       ac.Container,
221                                       ac.Location);
222
223                         Block b;
224                         ScopeInfo parent = null;
225
226                         for (b = ac.Block; b != null; b = b.Parent) {
227                                 if (b.ScopeInfo != null) {
228                                         parent = b.ScopeInfo;
229                                         break;
230                                 }
231                         }
232
233                         Report.Debug (128, "CREATE SCOPE #2", parent);
234
235                         ScopeInfo new_scope = new ScopeInfo (block, parent, null);
236
237                         Report.Debug (128, "CREATE SCOPE #3", new_scope);
238
239                         return new_scope;
240                 }
241
242                 private static int default_modflags (DeclSpace parent)
243                 {
244                         return parent is CompilerGeneratedClass ? Modifiers.PUBLIC : Modifiers.PRIVATE;
245                 }
246
247                 protected ScopeInfo (Block block, DeclSpace parent, GenericMethod generic)
248                         : base (parent, generic, default_modflags (parent), block.StartLocation)
249                 {
250                         Parent = parent;
251                         RootScope = block.Toplevel.RootScope;
252                         ScopeBlock = block;
253
254                         Report.Debug (128, "NEW SCOPE", this, block,
255                                       block.Parent, block.Toplevel);
256
257                         RootScope.AddScope (this);
258                 }
259
260                 protected ScopeInfo (ToplevelBlock toplevel, DeclSpace parent,
261                                      GenericMethod generic, Location loc)
262                         : base (parent, generic, default_modflags (parent), loc)
263                 {
264                         Parent = parent;
265                         RootScope = (RootScopeInfo) this;
266                         ScopeBlock = toplevel;
267
268                         Report.Debug (128, "NEW ROOT SCOPE", this, toplevel, loc);
269                 }
270
271                 protected CapturedScope[] CapturedScopes {
272                         get {
273                                 CapturedScope[] list = new CapturedScope [captured_scopes.Count];
274                                 captured_scopes.Values.CopyTo (list, 0);
275                                 return list;
276                         }
277                 }
278
279                 protected CapturedVariable GetCapturedScope (ScopeInfo scope)
280                 {
281                         return (CapturedVariable) captured_scopes [scope];
282                 }
283
284                 protected void EmitScopeInstance (EmitContext ec)
285                 {
286                         if (scope_initializer == null) {
287                                 //
288                                 // This is needed if someone overwrites the Emit method
289                                 // of Statement and manually calls Block.Emit without
290                                 // this snippet first:
291                                 // 
292                                 //   ec.EmitScopeInitFromBlock (The_Block);
293                                 //   The_Block.Emit (ec);
294                                 // 
295                                 throw new InternalErrorException ();
296                         }
297
298                         scope_initializer.Emit (ec);
299                 }
300
301                 public ExpressionStatement GetScopeInitializer (EmitContext ec)
302                 {
303                         Report.Debug (128, "GET SCOPE INITIALIZER",
304                                       this, GetType (), scope_initializer, ScopeBlock);
305
306                         if (scope_initializer == null) {
307                                 scope_initializer = CreateScopeInitializer ();
308                                 if (scope_initializer.Resolve (ec) == null)
309                                         throw new InternalErrorException ();
310                         }
311
312                         return scope_initializer;
313                 }
314
315                 public Type GetScopeType (EmitContext ec)
316                 {
317                         if (!IsGeneric)
318                                 return TypeBuilder;
319
320                         TypeArguments targs = new TypeArguments (Location);
321
322                         if (ec.DeclContainer.Parent.IsGeneric)
323                                 foreach (TypeParameter t in ec.DeclContainer.Parent.TypeParameters)
324                                         targs.Add (new TypeParameterExpr (t, Location));
325                         if (ec.DeclContainer.IsGeneric)
326                                 foreach (TypeParameter t in ec.DeclContainer.CurrentTypeParameters)
327                                         targs.Add (new TypeParameterExpr (t, Location));
328
329                         Report.Debug (128, "GET SCOPE TYPE", this, TypeBuilder, targs,
330                                       ec.DeclContainer, ec.DeclContainer.GetType (),
331                                       ec.DeclContainer.Parent.Name);
332
333                         TypeExpr te = new ConstructedType (TypeBuilder, targs, Location);
334                         te = te.ResolveAsTypeTerminal (ec, false);
335                         if ((te == null) || (te.Type == null))
336                                 return null;
337                         return te.Type;
338                 }
339
340                 protected override bool DoDefineMembers ()
341                 {
342                         Report.Debug (64, "SCOPE INFO DEFINE MEMBERS", this, GetType (), IsGeneric,
343                                       Parent.IsGeneric, GenericMethod);
344
345                         foreach (CapturedScope child in CapturedScopes) {
346                                 if (!child.DefineMembers ())
347                                         return false;
348                         }
349
350                         return base.DoDefineMembers ();
351                 }
352
353                 protected override bool DoResolveMembers ()
354                 {
355                         Report.Debug (64, "SCOPE INFO RESOLVE MEMBERS", this, GetType (), IsGeneric,
356                                       Parent.IsGeneric, GenericMethod);
357
358                         return base.DoResolveMembers ();
359                 }
360
361                 public Variable CaptureScope (ScopeInfo child)
362                 {
363                         CheckMembersDefined ();
364                         Report.Debug (128, "CAPTURE SCOPE", this, GetType (), child, child.GetType ());
365                         if (child == this)
366                                 throw new InternalErrorException ();
367                         CapturedScope captured = (CapturedScope) captured_scopes [child];
368                         if (captured == null) {
369                                 captured = new CapturedScope (this, child);
370                                 captured_scopes.Add (child, captured);
371                         }
372                         return captured;
373                 }
374
375                 public Variable AddLocal (LocalInfo local)
376                 {
377                         Report.Debug (128, "CAPTURE LOCAL", this, local);
378                         Variable var = (Variable) locals [local];
379                         if (var == null) {
380                                 var = new CapturedLocal (this, local);
381                                 locals.Add (local, var);
382                                 local.IsCaptured = true;
383                         }
384                         return var;
385                 }
386
387                 public Variable GetCapturedVariable (LocalInfo local)
388                 {
389                         return (Variable) locals [local];
390                 }
391
392                 public bool HostsParameters {
393                         get { return captured_params != null; }
394                 }
395
396                 public Variable GetCapturedParameter (Parameter par)
397                 {
398                         if (captured_params != null)
399                                 return (Variable) captured_params [par];
400                         else
401                                 return null;
402                 }
403
404                 public Variable AddParameter (Parameter par, int idx)
405                 {
406                         if (captured_params == null)
407                                 captured_params = new Hashtable ();
408
409                         Variable var = (Variable) captured_params [par];
410                         if (var == null) {
411                                 var = new CapturedParameter (this, par, idx);
412                                 captured_params.Add (par, var);
413                                 par.IsCaptured = true;
414                         }
415
416                         return var;
417                 }
418
419                 public override void EmitType ()
420                 {
421                         SymbolWriter.DefineAnonymousScope (ID);
422                         foreach (CapturedLocal local in locals.Values)
423                                 local.EmitSymbolInfo ();
424
425                         if (captured_params != null) {
426                                 foreach (CapturedParameter param in captured_params.Values)
427                                         param.EmitSymbolInfo ();
428                         }
429
430                         foreach (CapturedScope scope in CapturedScopes) {
431                                 scope.EmitSymbolInfo ();
432                         }
433
434                         base.EmitType ();
435                 }
436
437                 protected string MakeFieldName (string local_name)
438                 {
439                         return "<" + ID + ":" + local_name + ">";
440                 }
441
442                 protected virtual ScopeInitializer CreateScopeInitializer ()
443                 {
444                         return new ScopeInitializer (this);
445                 }
446
447                 protected abstract class CapturedVariable : Variable
448                 {
449                         public readonly ScopeInfo Scope;
450                         public readonly string Name;
451
452                         public FieldExpr FieldInstance;
453                         protected Field field;
454
455                         protected CapturedVariable (ScopeInfo scope, string name)
456                         {
457                                 this.Scope = scope;
458                                 this.Name = name;
459                         }
460
461                         protected CapturedVariable (ScopeInfo scope, string name, Type type)
462                                 : this (scope, name)
463                         {
464                                 this.field = scope.CaptureVariable (
465                                         scope.MakeFieldName (name), scope.RootScope.InflateType (type));
466                         }
467
468                         public Field Field {
469                                 get { return field; }
470                         }
471
472                         public override Type Type {
473                                 get { return Field.MemberType; }
474                         }
475
476                         public override bool HasInstance {
477                                 get { return true; }
478                         }
479
480                         public override bool NeedsTemporary {
481                                 get { return true; }
482                         }
483
484                         protected FieldInfo GetField (EmitContext ec)
485                         {
486                                 if ((ec.CurrentBlock != null) &&
487                                     (ec.CurrentBlock.Toplevel != Scope.ScopeBlock.Toplevel))
488                                         return Field.FieldBuilder;
489                                 else
490                                         return FieldInstance.FieldInfo;
491                         }
492
493                         public abstract void EmitSymbolInfo ();
494
495                         public override void EmitInstance (EmitContext ec)
496                         {
497                                 if ((ec.CurrentAnonymousMethod != null) &&
498                                     (ec.CurrentAnonymousMethod.Scope == Scope)) {
499                                         ec.ig.Emit (OpCodes.Ldarg_0);
500                                         return;
501                                 }
502
503                                 Scope.EmitScopeInstance (ec);
504                         }
505
506                         public override void Emit (EmitContext ec)
507                         {
508                                 ec.ig.Emit (OpCodes.Ldfld, GetField (ec));
509                         }
510
511                         public override void EmitAssign (EmitContext ec)
512                         {
513                                 ec.ig.Emit (OpCodes.Stfld, GetField (ec));
514                         }
515
516                         public override void EmitAddressOf (EmitContext ec)
517                         {
518                                 ec.ig.Emit (OpCodes.Ldflda, GetField (ec));
519                         }
520                 }
521
522                 protected class CapturedParameter : CapturedVariable {
523                         public readonly Parameter Parameter;
524                         public readonly int Idx;
525
526                         public CapturedParameter (ScopeInfo scope, Parameter par, int idx)
527                                 : base (scope, par.Name, par.ParameterType)
528                         {
529                                 this.Parameter = par;
530                                 this.Idx = idx;
531                         }
532
533                         public override void EmitSymbolInfo ()
534                         {
535                                 SymbolWriter.DefineCapturedParameter (
536                                         Scope.ID, Parameter.Name, Field.Name);
537                         }
538
539                         public override string ToString ()
540                         {
541                                 return String.Format ("{0} ({1}:{2}:{3})", GetType (), Field,
542                                                       Parameter.Name, Idx);
543                         }
544                 }
545
546                 protected class CapturedLocal : CapturedVariable {
547                         public readonly LocalInfo Local;
548
549                         public CapturedLocal (ScopeInfo scope, LocalInfo local)
550                                 : base (scope, local.Name, local.VariableType)
551                         {
552                                 this.Local = local;
553                         }
554
555                         public override void EmitSymbolInfo ()
556                         {
557                                 SymbolWriter.DefineCapturedLocal (
558                                         Scope.ID, Local.Name, Field.Name);
559                         }
560
561                         public override string ToString ()
562                         {
563                                 return String.Format ("{0} ({1}:{2})", GetType (), Field,
564                                                       Local.Name);
565                         }
566                 }
567
568                 protected class CapturedThis : CapturedVariable {
569                         public CapturedThis (RootScopeInfo host)
570                                 : base (host, "<>THIS", host.ParentType)
571                         { }
572
573                         public override void EmitSymbolInfo ()
574                         {
575                                 SymbolWriter.DefineCapturedThis (Scope.ID, Field.Name);
576                         }
577                 }
578
579                 protected class CapturedScope : CapturedVariable {
580                         public readonly ScopeInfo ChildScope;
581
582                         public CapturedScope (ScopeInfo root, ScopeInfo child)
583                                 : base (root, "scope" + child.ID)
584                         {
585                                 this.ChildScope = child;
586                         }
587
588                         public override void EmitSymbolInfo ()
589                         {
590                                 SymbolWriter.DefineCapturedScope (Scope.ID, ChildScope.ID, Field.Name);
591                         }
592
593                         public bool DefineMembers ()
594                         {
595                                 Type type = ChildScope.IsGeneric ?
596                                         ChildScope.CurrentType : ChildScope.TypeBuilder;
597                                 Report.Debug (128, "CAPTURED SCOPE DEFINE MEMBERS", this, Scope,
598                                               ChildScope, Name, type);
599                                 if (type == null)
600                                         throw new InternalErrorException ();
601                                 field = Scope.CaptureVariable (
602                                         Scope.MakeFieldName (Name), Scope.InflateType (type));
603                                 return true;
604                         }
605
606                         public override string ToString ()
607                         {
608                                 return String.Format ("CapturedScope ({1} captured in {0})",
609                                                       Scope, ChildScope);
610                         }
611                 }
612
613                 static void DoPath (StringBuilder sb, ScopeInfo start)
614                 {
615                         sb.Append ((start.ID).ToString ());
616                 }
617                 
618                 public override string ToString ()
619                 {
620                         StringBuilder sb = new StringBuilder ();
621                         
622                         sb.Append ("{");
623                         DoPath (sb, this);
624                         sb.Append ("}");
625
626                         return sb.ToString ();
627                 }
628
629                 protected class ScopeInitializer : ExpressionStatement
630                 {
631                         ScopeInfo scope;
632                         CapturedVariable captured_scope;
633                         LocalBuilder scope_instance;
634                         ConstructorInfo scope_ctor;
635
636                         bool initialized;
637
638                         public ScopeInitializer (ScopeInfo scope)
639                         {
640                                 this.scope = scope;
641                                 this.loc = scope.Location;
642                                 eclass = ExprClass.Value;
643                         }
644
645                         public ScopeInfo Scope {
646                                 get { return scope; }
647                         }
648
649                         public override Expression DoResolve (EmitContext ec)
650                         {
651                                 if (scope_ctor != null)
652                                         return this;
653
654                                 Report.Debug (64, "RESOLVE SCOPE INITIALIZER BASE", this, Scope,
655                                               ec, ec.CurrentBlock);
656
657                                 type = Scope.GetScopeType (ec);
658                                 if (type == null)
659                                         throw new InternalErrorException ();
660
661                                 if (!DoResolveInternal (ec))
662                                         throw new InternalErrorException ();
663
664                                 return this;
665                         }
666
667                         protected virtual bool DoResolveInternal (EmitContext ec)
668                         {
669                                 MethodGroupExpr mg = (MethodGroupExpr) MemberLookupFinal (
670                                         ec, ec.ContainerType, type, ".ctor", MemberTypes.Constructor,
671                                         AllBindingFlags | BindingFlags.DeclaredOnly, loc);
672                                 if (mg == null)
673                                         throw new InternalErrorException ();
674
675                                 scope_ctor = (ConstructorInfo) mg.Methods [0];
676
677                                 Report.Debug (128, "RESOLVE THE INIT", this, Scope, Scope.RootScope,
678                                               Scope.RootScope.GetType ());
679
680                                 ScopeInfo host = Scope.RootScope;
681                                 if ((Scope != host) && (Scope.RootScope is IteratorHost)) {
682                                         captured_scope = host.GetCapturedScope (Scope);
683                                         Type root = host.GetScopeType (ec);
684                                         FieldExpr fe = (FieldExpr) Expression.MemberLookup (
685                                                 type, root, captured_scope.Field.Name, loc);
686                                         if (fe == null)
687                                                 throw new InternalErrorException ();
688
689                                         fe.InstanceExpression = this;
690                                         captured_scope.FieldInstance = fe;
691
692                                         Report.Debug (128, "RESOLVE THE INIT #1", this,
693                                                       captured_scope, fe);
694                                 } else {
695                                         scope_instance = ec.ig.DeclareLocal (type);
696                                         if (!Scope.RootScope.IsIterator)
697                                                 SymbolWriter.DefineScopeVariable (Scope.ID, scope_instance);
698                                 }
699
700                                 foreach (CapturedLocal local in Scope.locals.Values) {
701                                         FieldExpr fe = (FieldExpr) Expression.MemberLookup (
702                                                 ec.ContainerType, type, local.Field.Name, loc);
703                                         Report.Debug (64, "RESOLVE SCOPE INITIALIZER #2", this, Scope,
704                                                       Scope, ec, ec.ContainerType, type,
705                                                       local.Field, local.Field.Name, loc, fe);
706                                         if (fe == null)
707                                                 throw new InternalErrorException ();
708
709                                         fe.InstanceExpression = this;
710                                         local.FieldInstance = fe;
711                                 }
712
713                                 if (Scope.HostsParameters) {
714                                         foreach (CapturedParameter cp in Scope.captured_params.Values) {
715                                                 FieldExpr fe = (FieldExpr) Expression.MemberLookup (
716                                                         ec.ContainerType, type, cp.Field.Name, loc);
717                                                 if (fe == null)
718                                                         throw new InternalErrorException ();
719
720                                                 fe.InstanceExpression = this;
721                                                 cp.FieldInstance = fe;
722                                         }
723                                 }
724
725                                 foreach (CapturedScope scope in Scope.CapturedScopes) {
726                                         FieldExpr fe = (FieldExpr) Expression.MemberLookup (
727                                                 ec.ContainerType, type, scope.Field.Name, loc);
728                                         Report.Debug (64, "RESOLVE SCOPE INITIALIZER #3", this, Scope,
729                                                       scope, ec, ec.ContainerType, type,
730                                                       scope.Field, scope.Field.Name, loc, fe);
731                                         if (fe == null)
732                                                 throw new InternalErrorException ();
733
734                                         fe.InstanceExpression = this;
735                                         scope.FieldInstance = fe;
736                                 }
737
738                                 return true;
739                         }
740
741                         protected virtual void EmitParameterReference (EmitContext ec,
742                                                                        CapturedParameter cp)
743                         {
744                                 int extra = ec.MethodIsStatic ? 0 : 1;
745                                 ParameterReference.EmitLdArg (ec.ig, cp.Idx + extra);
746                         }
747
748                         static int next_id;
749                         int id = ++next_id;
750
751                         protected virtual void DoEmit (EmitContext ec)
752                         {
753                                 if ((ec.CurrentBlock != null) &&
754                                     (ec.CurrentBlock.Toplevel != Scope.ScopeBlock.Toplevel)) {
755                                         ec.ig.Emit (OpCodes.Ldarg_0);
756
757                                         if (ec.CurrentAnonymousMethod != null) {
758                                                 ScopeInfo host = ec.CurrentAnonymousMethod.Scope;
759                                                 Variable captured = host.GetCapturedScope (scope);
760                                                 Report.Debug (128, "EMIT SCOPE INSTANCE #2",
761                                                               ec.CurrentAnonymousMethod, host,
762                                                               scope, captured);
763                                                 if (captured != null)
764                                                         captured.Emit (ec);
765                                         }
766                                 } else if (scope_instance != null)
767                                         ec.ig.Emit (OpCodes.Ldloc, scope_instance);
768                                 else {
769                                         Report.Debug (128, "DO EMIT", this, Scope, ec,
770                                                       scope_instance, captured_scope);
771                                         captured_scope.EmitInstance (ec);
772                                         captured_scope.Emit (ec);
773                                 }
774                         }
775
776                         protected void DoEmitInstance (EmitContext ec)
777                         {
778                                 Report.Debug (128, "DO EMIT INSTANCE", this, Scope, ec,
779                                               scope_instance, captured_scope);
780
781                                 if (scope_instance != null)
782                                         ec.ig.Emit (OpCodes.Ldloc, scope_instance);
783                                 else
784                                         captured_scope.EmitInstance (ec);
785                         }
786
787                         protected virtual void EmitScopeConstructor (EmitContext ec)
788                         {
789                                 ec.ig.Emit (OpCodes.Newobj, scope_ctor);
790                         }
791
792                         public override void Emit (EmitContext ec)
793                         {
794                                 if (!initialized)
795                                         throw new InternalErrorException (
796                                                 "Scope {0} not initialized yet", scope);
797
798                                 DoEmit (ec);
799                         }
800
801                         public override void EmitStatement (EmitContext ec)
802                         {
803                                 if (initialized)
804                                         return;
805
806                                 DoEmitStatement (ec);
807                                 initialized = true;
808                         }
809
810                         protected virtual void DoEmitStatement (EmitContext ec)
811                         {
812                                 Report.Debug (128, "EMIT SCOPE INITIALIZER STATEMENT", this, id,
813                                               Scope, scope_instance, ec);
814
815                                 ec.ig.Emit (OpCodes.Nop);
816                                 ec.ig.Emit (OpCodes.Ldc_I4, id);
817                                 ec.ig.Emit (OpCodes.Pop);
818                                 ec.ig.Emit (OpCodes.Nop);
819
820                                 if (scope_instance == null)
821                                         ec.ig.Emit (OpCodes.Ldarg_0);
822                                 EmitScopeConstructor (ec);
823                                 if (scope_instance != null)
824                                         ec.ig.Emit (OpCodes.Stloc, scope_instance);
825                                 else
826                                         captured_scope.EmitAssign (ec);
827
828                                 if (Scope.HostsParameters) {
829                                         foreach (CapturedParameter cp in Scope.captured_params.Values) {
830                                                 Report.Debug (128, "EMIT SCOPE INIT #6", this,
831                                                               ec, ec.IsStatic, Scope, cp, cp.Field.Name);
832                                                 DoEmitInstance (ec);
833                                                 EmitParameterReference (ec, cp);
834                                                 ec.ig.Emit (OpCodes.Stfld, cp.FieldInstance.FieldInfo);
835                                         }
836                                 }
837
838                                 if (Scope is IteratorHost)
839                                         return;
840
841                                 foreach (CapturedScope scope in Scope.CapturedScopes) {
842                                         ScopeInfo child = scope.ChildScope;
843
844                                         Report.Debug (128, "EMIT SCOPE INIT #5", this, Scope,
845                                                       scope.Scope, scope.ChildScope);
846
847                                         ExpressionStatement init = child.GetScopeInitializer (ec);
848                                         init.EmitStatement (ec);
849
850                                         DoEmit (ec);
851                                         scope.ChildScope.EmitScopeInstance (ec);
852                                         scope.EmitAssign (ec);
853                                 }
854                         }
855                 }
856         }
857
858         public class RootScopeInfo : ScopeInfo
859         {
860                 public RootScopeInfo (ToplevelBlock toplevel, DeclSpace parent,
861                                       GenericMethod generic, Location loc)
862                         : base (toplevel, parent, generic, loc)
863                 {
864                         scopes = new ArrayList ();
865                 }
866
867                 TypeExpr parent_type;
868                 CapturedVariableField parent_link;
869                 CapturedThis this_variable;
870                 protected ArrayList scopes;
871
872                 public virtual bool IsIterator {
873                         get { return false; }
874                 }
875
876                 public RootScopeInfo ParentHost {
877                         get { return Parent.PartialContainer as RootScopeInfo; }
878                 }
879
880                 public Type ParentType {
881                         get { return parent_type.Type; }
882                 }
883
884                 public Field ParentLink {
885                         get { return parent_link; }
886                 }
887
888                 protected CapturedThis THIS {
889                         get { return this_variable; }
890                 }
891
892                 public Variable CaptureThis ()
893                 {
894                         if (ParentHost != null)
895                                 return ParentHost.CaptureThis ();
896
897                         CheckMembersDefined ();
898                         if (this_variable == null)
899                                 this_variable = new CapturedThis (this);
900                         return this_variable;
901                 }
902
903                 public void AddScope (ScopeInfo scope)
904                 {
905                         scopes.Add (scope);
906                 }
907
908                 bool linked;
909                 public void LinkScopes ()
910                 {
911                         Report.Debug (128, "LINK SCOPES", this, linked, scopes);
912
913                         if (linked)
914                                 return;
915
916                         linked = true;
917                         if (ParentHost != null)
918                                 ParentHost.LinkScopes ();
919
920                         foreach (ScopeInfo si in scopes) {
921                                 if (!si.Define ())
922                                         throw new InternalErrorException ();
923                                 if (si.DefineType () == null)
924                                         throw new InternalErrorException ();
925                                 if (!si.ResolveType ())
926                                         throw new InternalErrorException ();
927                         }
928
929                         foreach (ScopeInfo si in scopes) {
930                                 if (!si.ResolveMembers ())
931                                         throw new InternalErrorException ();
932                                 if (!si.DefineMembers ())
933                                         throw new InternalErrorException ();
934                         }
935                 }
936
937                 protected override ScopeInitializer CreateScopeInitializer ()
938                 {
939                         return new RootScopeInitializer (this);
940                 }
941
942                 protected override bool DefineNestedTypes ()
943                 {
944                         if (Parent.IsGeneric) {
945                                 parent_type = new ConstructedType (
946                                         Parent.TypeBuilder, Parent.TypeParameters, Location);
947                                 parent_type = parent_type.ResolveAsTypeTerminal (this, false);
948                                 if ((parent_type == null) || (parent_type.Type == null))
949                                         return false;
950                         } else {
951                                 parent_type = new TypeExpression (Parent.TypeBuilder, Location);
952                         }
953
954                         CompilerGeneratedClass parent = Parent.PartialContainer as CompilerGeneratedClass;
955                         if (parent != null)
956                                 parent_link = new CapturedVariableField (this, "<>parent", parent_type);
957
958                         return base.DefineNestedTypes ();
959                 }
960
961                 protected override bool DoDefineMembers ()
962                 {
963                         ArrayList args = new ArrayList ();
964                         if (this is IteratorHost)
965                                 args.Add (new Parameter (
966                                         TypeManager.int32_type, "$PC", Parameter.Modifier.NONE,
967                                         null, Location));
968
969                         Field pfield;
970                         if (Parent is CompilerGeneratedClass)
971                                 pfield = parent_link;
972                         else
973                                 pfield = this_variable !=  null ? this_variable.Field : null;
974                         if (pfield != null)
975                                 args.Add (new Parameter (
976                                         pfield.MemberType, "parent", Parameter.Modifier.NONE,
977                                         null, Location));
978
979                         Parameter[] ctor_params = new Parameter [args.Count];
980                         args.CopyTo (ctor_params, 0);
981                         Constructor ctor = new Constructor (
982                                 this, MemberName.Name, Modifiers.PUBLIC,
983                                 new Parameters (ctor_params),
984                                 new GeneratedBaseInitializer (Location),
985                                 Location);
986                         AddConstructor (ctor);
987
988                         ctor.Block = new ToplevelBlock (null, Location);
989                         ctor.Block.AddStatement (new TheCtor (this));
990
991                         return base.DoDefineMembers ();
992                 }
993
994                 protected virtual void EmitScopeConstructor (EmitContext ec)
995                 {
996                         int pos = (this is IteratorHost) ? 2 : 1;
997
998                         Field pfield;
999                         if (Parent is CompilerGeneratedClass)
1000                                 pfield = parent_link;
1001                         else
1002                                 pfield = this_variable !=  null ? this_variable.Field : null;
1003
1004                         if (pfield != null) {
1005                                 ec.ig.Emit (OpCodes.Ldarg_0);
1006                                 ec.ig.Emit (OpCodes.Ldarg, pos);
1007                                 ec.ig.Emit (OpCodes.Stfld, pfield.FieldBuilder);
1008                                 pos++;
1009                         }
1010                 }
1011
1012                 public override void EmitType ()
1013                 {
1014                         base.EmitType ();
1015                         if (THIS != null)
1016                                 THIS.EmitSymbolInfo ();
1017                 }
1018
1019                 protected class TheCtor : Statement
1020                 {
1021                         RootScopeInfo host;
1022
1023                         public TheCtor (RootScopeInfo host)
1024                         {
1025                                 this.host = host;
1026                         }
1027
1028                         public override bool Resolve (EmitContext ec)
1029                         {
1030                                 return true;
1031                         }
1032
1033                         protected override void DoEmit (EmitContext ec)
1034                         {
1035                                 host.EmitScopeConstructor (ec);
1036                         }
1037                 }
1038
1039                 protected class RootScopeInitializer : ScopeInitializer
1040                 {
1041                         RootScopeInfo host;
1042
1043                         public RootScopeInitializer (RootScopeInfo host)
1044                                 : base (host)
1045                         {
1046                                 this.host = host;
1047                         }
1048
1049                         public RootScopeInfo Host {
1050                                 get { return host; }
1051                         }
1052
1053                         protected override bool DoResolveInternal (EmitContext ec)
1054                         {
1055                                 Report.Debug (64, "RESOLVE ANONYMOUS METHOD HOST INITIALIZER",
1056                                               this, Host, Host.ParentType, loc);
1057
1058                                 if (Host.THIS != null) {
1059                                         FieldExpr fe = (FieldExpr) Expression.MemberLookup (
1060                                                 ec.ContainerType, type, Host.THIS.Field.Name, loc);
1061                                         if (fe == null)
1062                                                 throw new InternalErrorException ();
1063
1064                                         fe.InstanceExpression = this;
1065                                         Host.THIS.FieldInstance = fe;
1066                                 }
1067
1068                                 return base.DoResolveInternal (ec);
1069                         }
1070
1071                         protected virtual bool IsGetEnumerator {
1072                                 get { return false; }
1073                         }
1074
1075                         protected override void EmitScopeConstructor (EmitContext ec)
1076                         {
1077                                 if (host.THIS != null) {
1078                                         ec.ig.Emit (OpCodes.Ldarg_0);
1079                                         if (IsGetEnumerator)
1080                                                 ec.ig.Emit (OpCodes.Ldfld, host.THIS.Field.FieldBuilder);
1081                                         else if (host.THIS.Type.IsValueType)
1082                                                 Expression.LoadFromPtr (ec.ig, host.THIS.Type);
1083                                 } else if (host.ParentLink != null)
1084                                         ec.ig.Emit (OpCodes.Ldarg_0);
1085
1086                                 base.EmitScopeConstructor (ec);
1087                         }
1088                 }
1089
1090         }
1091
1092         public interface IAnonymousContainer
1093         {
1094                 Block Container {
1095                         get;
1096                 }
1097
1098                 GenericMethod GenericMethod {
1099                         get;
1100                 }
1101
1102                 RootScopeInfo RootScope {
1103                         get;
1104                 }
1105
1106                 bool IsIterator {
1107                         get;
1108                 }
1109         }
1110
1111         public interface IAnonymousHost
1112         {
1113                 //
1114                 // Invoked if a yield statement is found in the body
1115                 //
1116                 void SetYields ();
1117
1118                 //
1119                 // Invoked if an anonymous method is found in the body
1120                 //
1121                 void AddAnonymousMethod (AnonymousMethodExpression anonymous);
1122         }
1123
1124         public class AnonymousMethodExpression : Expression, IAnonymousContainer, IAnonymousHost
1125         {
1126                 public readonly AnonymousMethodExpression Parent;
1127                 public readonly TypeContainer Host;
1128                 public readonly Parameters Parameters;
1129
1130                 public ToplevelBlock Block;
1131
1132                 protected Block container;
1133                 protected readonly GenericMethod generic;
1134
1135                 public Block Container {
1136                         get { return container; }
1137                 }
1138
1139                 public GenericMethod GenericMethod {
1140                         get { return generic; }
1141                 }
1142
1143                 public RootScopeInfo RootScope {
1144                         get { return root_scope; }
1145                 }
1146
1147                 public AnonymousMethodExpression (AnonymousMethodExpression parent,
1148                                                   GenericMethod generic, TypeContainer host,
1149                                                   Parameters parameters, Block container,
1150                                                   Location loc)
1151                 {
1152                         this.Parent = parent;
1153                         this.generic = parent != null ? null : generic;
1154                         this.Host = host;
1155                         this.Parameters = parameters;
1156                         this.container = container;
1157                         this.loc = loc;
1158
1159                         Report.Debug (64, "NEW ANONYMOUS METHOD EXPRESSION", this, parent, host,
1160                                       container, loc);
1161
1162                         if (parent != null)
1163                                 parent.AddAnonymousMethod (this);
1164                 }
1165
1166                 ArrayList children;
1167                 RootScopeInfo root_scope;
1168
1169                 static int next_index;
1170
1171                 void IAnonymousHost.SetYields ()
1172                 {
1173                         throw new InvalidOperationException ();
1174                 }
1175
1176                 public void AddAnonymousMethod (AnonymousMethodExpression anonymous)
1177                 {
1178                         if (children == null)
1179                                 children = new ArrayList ();
1180                         children.Add (anonymous);
1181                 }
1182
1183                 public bool CreateAnonymousHelpers ()
1184                 {
1185                         // FIXME: this polutes expression trees implementation
1186
1187                         Report.Debug (64, "ANONYMOUS METHOD EXPRESSION CREATE ROOT SCOPE",
1188                                       this, Host, container, loc);
1189
1190                         if (container != null)
1191                                 root_scope = container.Toplevel.CreateRootScope (Host);
1192
1193                         if (children != null) {
1194                                 foreach (AnonymousMethodExpression child in children) {
1195                                         if (!child.CreateAnonymousHelpers ())
1196                                                 return false;
1197                                 }
1198                         }
1199
1200                         return true;
1201                 }
1202
1203                 public override string ExprClassName {
1204                         get {
1205                                 return "anonymous method";
1206                         }
1207                 }
1208
1209                 public virtual bool HasExplicitParameters {
1210                         get {
1211                                 return true;
1212                         }
1213                 }
1214
1215                 //
1216                 // Returns true if the body of lambda expression can be implicitly
1217                 // converted to the delegate of type `delegate_type'
1218                 //
1219                 public bool ImplicitStandardConversionExists (Type delegate_type)
1220                 {
1221                         EmitContext ec = EmitContext.TempEc;
1222                         using (ec.Set (EmitContext.Flags.ProbingMode)) {
1223                                 return Compatible (ec, delegate_type) != null;
1224                         }
1225                 }
1226
1227                 protected Type CompatibleChecks (EmitContext ec, Type delegate_type)
1228                 {
1229                         if (!ec.IsAnonymousMethodAllowed) {
1230                                 Report.Error (1706, loc, "Anonymous methods and lambda expressions cannot be used in the current context");
1231                                 return null;
1232                         }
1233                         
1234                         if (TypeManager.IsDelegateType (delegate_type))
1235                                 return delegate_type;
1236
1237 #if GMCS_SOURCE
1238                         if (TypeManager.DropGenericTypeArguments (delegate_type) == TypeManager.expression_type) {
1239                                 delegate_type = TypeManager.GetTypeArguments (delegate_type) [0];
1240                                 if (TypeManager.IsDelegateType (delegate_type))
1241                                         return delegate_type;
1242
1243                                 Report.Error (835, loc, "Cannot convert `{0}' to an expression tree of non-delegate type `{1}'",
1244                                         GetSignatureForError (), TypeManager.CSharpName (delegate_type));
1245                                 return null;
1246                         }
1247 #endif
1248
1249                         Report.Error (1660, loc, "Cannot convert `{0}' to non-delegate type `{1}'",
1250                                       GetSignatureForError (), TypeManager.CSharpName (delegate_type));
1251                         return null;
1252                 }
1253
1254                 protected bool VerifyExplicitParameters (Type delegate_type, ParameterData parameters, bool ignore_error)
1255                 {
1256                         if (VerifyParameterCompatibility (delegate_type, parameters, ignore_error))
1257                                 return true;
1258
1259                         if (!ignore_error)
1260                                 Report.Error (1661, loc,
1261                                         "Cannot convert `{0}' to delegate type `{1}' since there is a parameter mismatch",
1262                                         GetSignatureForError (), TypeManager.CSharpName (delegate_type));
1263
1264                         return false;
1265                 }
1266
1267                 protected bool VerifyParameterCompatibility (Type delegate_type, ParameterData invoke_pd, bool ignore_errors)
1268                 {
1269                         if (Parameters.Count != invoke_pd.Count) {
1270                                 if (ignore_errors)
1271                                         return false;
1272                                 
1273                                 Report.Error (1593, loc, "Delegate `{0}' does not take `{1}' arguments",
1274                                               TypeManager.CSharpName (delegate_type), Parameters.Count.ToString ());
1275                                 return false;
1276                         }
1277                         
1278                         if (!HasExplicitParameters)
1279                                 return true;                    
1280
1281                         bool error = false;
1282                         for (int i = 0; i < Parameters.Count; ++i) {
1283                                 Parameter.Modifier p_mod = invoke_pd.ParameterModifier (i);
1284                                 if (Parameters.ParameterModifier (i) != p_mod && p_mod != Parameter.Modifier.PARAMS) {
1285                                         if (ignore_errors)
1286                                                 return false;
1287                                         
1288                                         if (p_mod == Parameter.Modifier.NONE)
1289                                                 Report.Error (1677, loc, "Parameter `{0}' should not be declared with the `{1}' keyword",
1290                                                               (i + 1).ToString (), Parameter.GetModifierSignature (Parameters.ParameterModifier (i)));
1291                                         else
1292                                                 Report.Error (1676, loc, "Parameter `{0}' must be declared with the `{1}' keyword",
1293                                                               (i+1).ToString (), Parameter.GetModifierSignature (p_mod));
1294                                         error = true;
1295                                         continue;
1296                                 }
1297
1298                                 Type type = invoke_pd.Types [i];
1299                                 
1300                                 // We assume that generic parameters are always inflated
1301                                 if (TypeManager.IsGenericParameter (type))
1302                                         continue;
1303                                 
1304                                 if (TypeManager.HasElementType (type) && TypeManager.IsGenericParameter (TypeManager.GetElementType (type)))
1305                                         continue;
1306                                 
1307                                 if (invoke_pd.ParameterType (i) != Parameters.ParameterType (i)) {
1308                                         if (ignore_errors)
1309                                                 return false;
1310                                         
1311                                         Report.Error (1678, loc, "Parameter `{0}' is declared as type `{1}' but should be `{2}'",
1312                                                       (i+1).ToString (),
1313                                                       TypeManager.CSharpName (Parameters.ParameterType (i)),
1314                                                       TypeManager.CSharpName (invoke_pd.ParameterType (i)));
1315                                         error = true;
1316                                 }
1317                         }
1318
1319                         return !error;
1320                 }
1321
1322                 //
1323                 // Infers type arguments based on explicit arguments
1324                 //
1325                 public bool ExplicitTypeInference (TypeInferenceContext type_inference, Type delegate_type)
1326                 {
1327                         if (!HasExplicitParameters)
1328                                 return false;
1329
1330                         if (!TypeManager.IsDelegateType (delegate_type)) {
1331 #if GMCS_SOURCE
1332                                 if (TypeManager.DropGenericTypeArguments (delegate_type) != TypeManager.expression_type)
1333                                         return false;
1334
1335                                 delegate_type = delegate_type.GetGenericArguments () [0];
1336                                 if (!TypeManager.IsDelegateType (delegate_type))
1337                                         return false;
1338 #else
1339                                 return false;
1340 #endif
1341                         }
1342                         
1343                         ParameterData d_params = TypeManager.GetDelegateParameters (delegate_type);
1344                         if (d_params.Count != Parameters.Count)
1345                                 return false;
1346
1347                         for (int i = 0; i < Parameters.Count; ++i) {
1348                                 Type itype = d_params.Types [i];
1349                                 if (!TypeManager.IsGenericParameter (itype)) {
1350                                         if (!TypeManager.HasElementType (itype))
1351                                                 continue;
1352                                         
1353                                         if (!TypeManager.IsGenericParameter (itype.GetElementType ()))
1354                                             continue;
1355                                 }
1356                                 type_inference.ExactInference (Parameters.FixedParameters[i].ParameterType, itype);
1357                         }
1358                         return true;
1359                 }
1360
1361                 public Type InferReturnType (EmitContext ec, TypeInferenceContext tic, Type delegate_type)
1362                 {
1363                         AnonymousMethod am;
1364                         using (ec.Set (EmitContext.Flags.ProbingMode | EmitContext.Flags.InferReturnType)) {
1365                                 am = CompatibleMethod (ec, tic, GetType (), delegate_type);
1366                         }
1367                         
1368                         if (am == null)
1369                                 return null;
1370
1371                         if (am.ReturnType == TypeManager.null_type)
1372                                 am.ReturnType = null;
1373
1374                         return am.ReturnType;
1375                 }
1376
1377                 //
1378                 // Returns AnonymousMethod container if this anonymous method
1379                 // expression can be implicitly converted to the delegate type `delegate_type'
1380                 //
1381                 public Expression Compatible (EmitContext ec, Type type)
1382                 {
1383                         Type delegate_type = CompatibleChecks (ec, type);
1384                         if (delegate_type == null)
1385                                 return null;
1386
1387                         //
1388                         // At this point its the first time we know the return type that is 
1389                         // needed for the anonymous method.  We create the method here.
1390                         //
1391
1392                         MethodInfo invoke_mb = Delegate.GetInvokeMethod (
1393                                 ec.ContainerType, delegate_type);
1394                         Type return_type = TypeManager.TypeToCoreType (invoke_mb.ReturnType);
1395
1396 #if MS_COMPATIBLE
1397                         Type[] g_args = delegate_type.GetGenericArguments ();
1398                         if (return_type.IsGenericParameter)
1399                                 return_type = g_args [return_type.GenericParameterPosition];
1400 #endif
1401
1402                         //
1403                         // Second: the return type of the delegate must be compatible with 
1404                         // the anonymous type.   Instead of doing a pass to examine the block
1405                         // we satisfy the rule by setting the return type on the EmitContext
1406                         // to be the delegate type return type.
1407                         //
1408
1409                         Report.Debug (64, "COMPATIBLE", this, Parent, GenericMethod, Host,
1410                                       Container, Block, return_type, delegate_type,
1411                                       TypeManager.IsGenericType (delegate_type), loc);
1412
1413                         try {
1414                                 int errors = Report.Errors;
1415                                 AnonymousMethod am = CompatibleMethod (ec, null, return_type, delegate_type);
1416                                 if (am != null && delegate_type != type && errors == Report.Errors)
1417                                         return CreateExpressionTree (ec, delegate_type);
1418
1419                                 return am;
1420                         } catch (Exception e) {
1421                                 throw new InternalErrorException (e, loc);
1422                         }
1423                 }
1424
1425                 protected virtual Expression CreateExpressionTree (EmitContext ec, Type delegate_type)
1426                 {
1427                         Report.Error (1946, loc, "An anonymous method cannot be converted to an expression tree");
1428                         return null;
1429                 }
1430
1431                 protected virtual Parameters ResolveParameters (EmitContext ec, TypeInferenceContext tic, Type delegate_type)
1432                 {
1433                         ParameterData delegate_parameters = TypeManager.GetDelegateParameters (delegate_type);
1434
1435                         if (Parameters == null) {
1436                                 //
1437                                 // We provide a set of inaccessible parameters
1438                                 //
1439                                 Parameter[] fixedpars = new Parameter[delegate_parameters.Count];
1440
1441                                 for (int i = 0; i < delegate_parameters.Count; i++) {
1442                                         Parameter.Modifier i_mod = delegate_parameters.ParameterModifier (i);
1443                                         if ((i_mod & Parameter.Modifier.OUTMASK) != 0) {
1444                                                 Report.Error (1688, loc, "Cannot convert anonymous " +
1445                                                                   "method block without a parameter list " +
1446                                                                   "to delegate type `{0}' because it has " +
1447                                                                   "one or more `out' parameters.",
1448                                                                   TypeManager.CSharpName (delegate_type));
1449                                                 return null;
1450                                         }
1451                                         fixedpars[i] = new Parameter (
1452                                                 delegate_parameters.ParameterType (i), "+" + (++next_index),
1453                                                 delegate_parameters.ParameterModifier (i), null, loc);
1454                                 }
1455
1456                                 return Parameters.CreateFullyResolved (fixedpars, delegate_parameters.Types);
1457                         }
1458
1459                         if (!VerifyExplicitParameters (delegate_type, delegate_parameters, ec.IsInProbingMode)) {
1460                                 return null;
1461                         }
1462
1463                         return Parameters;
1464                 }
1465
1466                 public override Expression DoResolve (EmitContext ec)
1467                 {
1468                         //
1469                         // Set class type, set type
1470                         //
1471
1472                         eclass = ExprClass.Value;
1473
1474                         //
1475                         // This hack means `The type is not accessible
1476                         // anywhere', we depend on special conversion
1477                         // rules.
1478                         // 
1479                         type = TypeManager.anonymous_method_type;
1480
1481                         if ((Parameters != null) && !Parameters.Resolve (ec))
1482                                 return null;
1483
1484                         return this;
1485                 }
1486
1487                 public override void Emit (EmitContext ec)
1488                 {
1489                         // nothing, as we only exist to not do anything.
1490                 }
1491
1492                 public override string GetSignatureForError ()
1493                 {
1494                         return ExprClassName;
1495                 }
1496
1497                 public bool IsIterator {
1498                         get { return false; }
1499                 }
1500
1501                 protected AnonymousMethod CompatibleMethod (EmitContext ec, TypeInferenceContext tic, Type return_type, Type delegate_type)
1502                 {
1503                         Parameters p = ResolveParameters (ec, tic, delegate_type);
1504                         if (p == null)
1505                                 return null;
1506
1507                         ToplevelBlock b = ec.IsInProbingMode ? (ToplevelBlock) Block.PerformClone () : Block;
1508
1509                         AnonymousMethod anonymous = CompatibleMethodFactory (return_type, delegate_type, p, b);
1510                         if (!anonymous.Compatible (ec))
1511                                 return null;
1512
1513                         return anonymous;
1514                 }
1515
1516                 protected virtual AnonymousMethod CompatibleMethodFactory (Type return_type, Type delegate_type, Parameters p, ToplevelBlock b)
1517                 {
1518                         return new AnonymousMethod (RootScope, Host,
1519                                 GenericMethod, p, Container, b, return_type,
1520                                 delegate_type, loc);
1521                 }
1522
1523                 protected override void CloneTo (CloneContext clonectx, Expression t)
1524                 {
1525                         AnonymousMethodExpression target = (AnonymousMethodExpression) t;
1526
1527                         target.Block = (ToplevelBlock) clonectx.LookupBlock (Block);
1528                         target.container = clonectx.LookupBlock (Block);
1529                 }
1530         }
1531
1532         public abstract class AnonymousContainer : Expression, IAnonymousContainer
1533         {
1534                 public Parameters Parameters;
1535
1536                 //
1537                 // The block that makes up the body for the anonymous mehtod
1538                 //
1539                 public readonly ToplevelBlock Block;
1540
1541                 public readonly int ModFlags;
1542                 public Type ReturnType;
1543                 public readonly DeclSpace Host;
1544
1545                 //
1546                 // The implicit method we create
1547                 //
1548                 protected Method method;
1549                 protected EmitContext aec;
1550
1551                 // The emit context for the anonymous method
1552                 protected bool unreachable;
1553                 protected readonly Block container;
1554                 protected readonly GenericMethod generic;
1555
1556                 protected AnonymousContainer (DeclSpace host,
1557                                               GenericMethod generic, Parameters parameters,
1558                                               Block container, ToplevelBlock block,
1559                                               Type return_type, int mod, Location loc)
1560                 {
1561                         this.ReturnType = return_type;
1562                         this.ModFlags = mod | Modifiers.COMPILER_GENERATED;
1563                         this.Host = host;
1564
1565                         this.container = container;
1566                         this.generic = generic;
1567                         this.Parameters = parameters;
1568                         this.Block = block;
1569                         this.loc = loc;
1570
1571                         block.AnonymousContainer = this;
1572                 }
1573
1574                 public Method Method {
1575                         get { return method; }
1576                 }
1577
1578                 public abstract string ContainerType {
1579                         get; 
1580                 }
1581
1582                 public abstract RootScopeInfo RootScope {
1583                         get;
1584                 }
1585
1586                 public abstract ScopeInfo Scope {
1587                         get;
1588                 }
1589
1590                 public bool Compatible (EmitContext ec)
1591                 {
1592                         // REFACTOR: The method should be refactor, many of the
1593                         // hacks can be handled in better way
1594
1595                         Report.Debug (64, "RESOLVE ANONYMOUS METHOD", this, Location, ec,
1596                                       RootScope, Parameters, ec.IsStatic);
1597
1598                         if (ReturnType != null) {
1599                                 TypeExpr return_type_expr;
1600                                 if (RootScope != null)
1601                                         return_type_expr = RootScope.InflateType (ReturnType);
1602                                 else
1603                                         return_type_expr = new TypeExpression (ReturnType, Location);
1604                                 return_type_expr = return_type_expr.ResolveAsTypeTerminal (ec, false);
1605                                 if ((return_type_expr == null) || (return_type_expr.Type == null))
1606                                         return false;
1607                                 ReturnType = return_type_expr.Type;
1608                         }
1609
1610                         // Linq type inference is done differently
1611                         if (RootScope != null && RootContext.Version != LanguageVersion.LINQ)
1612                                 Parameters = RootScope.InflateParameters (Parameters);
1613
1614                         aec = new EmitContext (
1615                                 ec.ResolveContext, ec.TypeContainer,
1616                                 RootScope != null ? RootScope : Host, Location, null, ReturnType,
1617                                 /* REVIEW */ (ec.InIterator ? Modifiers.METHOD_YIELDS : 0) |
1618                                 (ec.InUnsafe ? Modifiers.UNSAFE : 0), /* No constructor */ false);
1619
1620                         aec.CurrentAnonymousMethod = this;
1621                         aec.IsStatic = ec.IsStatic;
1622                         
1623                         //
1624                         // HACK: Overwrite parent declaration container to currently resolved.
1625                         // It's required for an anonymous container inside partial class.
1626                         //
1627                         if (RootScope != null)
1628                                 aec.DeclContainer.Parent = ec.TypeContainer;
1629
1630                         IDisposable aec_dispose = null;
1631                         EmitContext.Flags flags = 0;
1632                         if (ec.InferReturnType)
1633                                 flags |= EmitContext.Flags.InferReturnType;
1634                         
1635                         if (ec.IsInProbingMode)
1636                                 flags |= EmitContext.Flags.ProbingMode;
1637                         
1638                         if (ec.IsInFieldInitializer)
1639                                 flags |= EmitContext.Flags.InFieldInitializer;
1640                         
1641                         // HACK: Flag with 0 cannot be set 
1642                         if (flags != 0)
1643                                 aec_dispose = aec.Set (flags);
1644
1645                         Report.Debug (64, "RESOLVE ANONYMOUS METHOD #1", this, Location, ec, aec,
1646                                       RootScope, Parameters, Block);
1647
1648                         bool unreachable;
1649                         bool res = aec.ResolveTopBlock (ec, Block, Parameters, null, out unreachable);
1650
1651                         if (ec.InferReturnType)
1652                                 ReturnType = aec.ReturnType;
1653
1654                         if (aec_dispose != null) {
1655                                 aec_dispose.Dispose ();
1656                         }
1657
1658                         return res;
1659                 }
1660
1661                 public virtual bool Define (EmitContext ec)
1662                 {
1663                         Report.Debug (64, "DEFINE ANONYMOUS METHOD #3", this, ec, aec, Block);
1664
1665                         if (aec == null && !Compatible (ec))
1666                                 return false;
1667
1668                         // Don't define anything when we are in probing scope (nested anonymous methods)
1669                         if (ec.IsInProbingMode)
1670                                 return true;
1671
1672                         method = DoCreateMethodHost (ec);
1673
1674                         if (Scope != null)
1675                                 return true;
1676
1677                         if (!method.ResolveMembers ())
1678                                 return false;
1679                         return method.Define ();
1680                 }
1681
1682                 protected abstract Method DoCreateMethodHost (EmitContext ec);
1683
1684                 public override void Emit (EmitContext ec)
1685                 {
1686                         throw new NotSupportedException ();
1687                 }
1688
1689                 public Block Container {
1690                         get { return container; }
1691                 }
1692
1693                 public GenericMethod GenericMethod {
1694                         get { return generic; }
1695                 }
1696
1697                 public abstract bool IsIterator {
1698                         get;
1699                 }
1700
1701                 protected class AnonymousMethodMethod : Method
1702                 {
1703                         public readonly AnonymousContainer AnonymousMethod;
1704                         public readonly ScopeInfo Scope;
1705                         public readonly string RealName;
1706
1707                         public AnonymousMethodMethod (AnonymousContainer am, ScopeInfo scope,
1708                                                       GenericMethod generic, TypeExpr return_type,
1709                                                       int mod, string real_name, MemberName name,
1710                                                       Parameters parameters)
1711                                 : base (scope != null ? scope : am.Host,
1712                                         generic, return_type, mod | Modifiers.COMPILER_GENERATED, false, name, parameters, null)
1713                         {
1714                                 this.AnonymousMethod = am;
1715                                 this.Scope = scope;
1716                                 this.RealName = real_name;
1717
1718                                 if (scope != null) {
1719                                         scope.CheckMembersDefined ();
1720                                         scope.AddMethod (this);
1721                                 } else {
1722                                         ModFlags |= Modifiers.STATIC;
1723                                         am.Host.PartialContainer.AddMethod (this);
1724                                 }
1725                                 Block = am.Block;
1726                         }
1727
1728                         public override EmitContext CreateEmitContext (DeclSpace tc, ILGenerator ig)
1729                         {
1730                                 EmitContext aec = AnonymousMethod.aec;
1731                                 aec.ig = ig;
1732                                 aec.MethodIsStatic = Scope == null;
1733                                 return aec;
1734                         }
1735
1736                         public override void EmitExtraSymbolInfo ()
1737                         {
1738                                 SymbolWriter.SetRealMethodName (RealName);
1739                         }
1740                 }
1741         }
1742
1743         public class AnonymousMethod : AnonymousContainer
1744         {
1745                 Type DelegateType;
1746
1747                 //
1748                 // The value return by the Compatible call, this ensure that
1749                 // the code works even if invoked more than once (Resolve called
1750                 // more than once, due to the way Convert.ImplicitConversion works
1751                 //
1752                 RootScopeInfo root_scope;
1753                 ScopeInfo scope;
1754
1755                 public AnonymousMethod (RootScopeInfo root_scope,
1756                                         DeclSpace host, GenericMethod generic,
1757                                         Parameters parameters, Block container,
1758                                         ToplevelBlock block, Type return_type, Type delegate_type,
1759                                         Location loc)
1760                         : base (host, generic, parameters, container, block,
1761                                 return_type, 0, loc)
1762                 {
1763                         this.DelegateType = delegate_type;
1764                         this.root_scope = root_scope;
1765                 }
1766
1767                 public override string ContainerType {
1768                         get { return "anonymous method"; }
1769                 }
1770
1771                 public override RootScopeInfo RootScope {
1772                         get { return root_scope; }
1773                 }
1774
1775                 public override ScopeInfo Scope {
1776                         get { return scope; }
1777                 }
1778
1779                 public override bool IsIterator {
1780                         get { return false; }
1781                 }
1782
1783                 public override string GetSignatureForError ()
1784                 {
1785                         return TypeManager.CSharpName (DelegateType);
1786                 }
1787
1788                 //
1789                 // Creates the host for the anonymous method
1790                 //
1791                 protected override Method DoCreateMethodHost (EmitContext ec)
1792                 {
1793                         MemberCore mc = ec.ResolveContext as MemberCore;
1794                         string name = CompilerGeneratedClass.MakeName (mc.Name, null);
1795                         MemberName member_name;
1796
1797                         Report.Debug (128, "CREATE METHOD HOST #0", RootScope);
1798
1799                         Block b;
1800                         scope = RootScope;
1801
1802                         Report.Debug (128, "CREATE METHOD HOST #1", this, Block, Block.ScopeInfo,
1803                                       RootScope, Location);
1804
1805                         for (b = Block.Parent; b != null; b = b.Parent) {
1806                                 Report.Debug (128, "CREATE METHOD HOST #2", this, Block,
1807                                               b, b.ScopeInfo);
1808                                 if (b.ScopeInfo != null) {
1809                                         scope = b.ScopeInfo;
1810                                         break;
1811                                 }
1812                         }
1813
1814                         if (scope != null)
1815                                 scope.CheckMembersDefined ();
1816
1817                         ArrayList scopes = new ArrayList ();
1818                         if (b != null) {
1819                                 for (b = b.Parent; b != null; b = b.Parent) {
1820                                         if (b.ScopeInfo != null)
1821                                                 scopes.Add (b.ScopeInfo);
1822                                 }
1823                         }
1824
1825                         Report.Debug (128, "CREATE METHOD HOST #1", this, scope, scopes);
1826
1827                         foreach (ScopeInfo si in scopes)
1828                                 scope.CaptureScope (si);
1829
1830                         Report.Debug (128, "CREATE METHOD HOST", this, Block, container,
1831                                       RootScope, scope, scopes, Location);
1832
1833                         GenericMethod generic_method = null;
1834 #if GMCS_SOURCE
1835                         if (TypeManager.IsGenericType (DelegateType)) {
1836                                 TypeArguments args = new TypeArguments (Location);
1837
1838                                 Type dt = DelegateType.GetGenericTypeDefinition ();
1839
1840                                 Type[] tparam = TypeManager.GetTypeArguments (dt);
1841                                 for (int i = 0; i < tparam.Length; i++)
1842                                         args.Add (new SimpleName (tparam [i].Name, Location));
1843
1844                                 member_name = new MemberName (name, args, Location);
1845
1846                                 Report.Debug (128, "CREATE METHOD HOST #5", this, DelegateType,
1847                                               TypeManager.GetTypeArguments (DelegateType),
1848                                               dt, tparam, args);
1849
1850                                 generic_method = new GenericMethod (
1851                                         Host.NamespaceEntry, scope, member_name,
1852                                         new TypeExpression (ReturnType, Location), Parameters);
1853
1854                                 generic_method.SetParameterInfo (null);
1855                         } else
1856 #endif
1857                                 member_name = new MemberName (name, Location);
1858
1859                         string real_name = String.Format (
1860                                 "{0}~{1}{2}", mc.GetSignatureForError (), GetSignatureForError (),
1861                                 Parameters.GetSignatureForError ());
1862
1863                         return new AnonymousMethodMethod (
1864                                 this, scope, generic_method, new TypeExpression (ReturnType, Location),
1865                                 scope == null ? Modifiers.PRIVATE : Modifiers.INTERNAL,
1866                                 real_name, member_name, Parameters);
1867                 }
1868
1869                 public override Expression DoResolve (EmitContext ec)
1870                 {
1871                         if (!Define (ec))
1872                                 return null;
1873
1874                         return new AnonymousDelegate (this, DelegateType, Location).Resolve (ec);
1875                 }
1876
1877                 public MethodInfo GetMethodBuilder (EmitContext ec)
1878                 {
1879                         MethodInfo builder = method.MethodBuilder;
1880                         if ((Scope != null) && Scope.IsGeneric) {
1881                                 Type scope_type = Scope.GetScopeType (ec);
1882                                 if (scope_type == null)
1883                                         throw new InternalErrorException ();
1884
1885                                 MethodGroupExpr mg = (MethodGroupExpr) Expression.MemberLookup (
1886                                         ec.ContainerType, scope_type, builder.Name,
1887                                         MemberTypes.Method, Expression.AllBindingFlags | BindingFlags.NonPublic, Location);
1888                                 
1889                                 if (mg == null)
1890                                         throw new InternalErrorException ();
1891                                 builder = (MethodInfo) mg.Methods [0];
1892                         }
1893
1894 #if GMCS_SOURCE
1895                         if (!DelegateType.IsGenericType)
1896                                 return builder;
1897
1898                         Type[] targs = TypeManager.GetTypeArguments (DelegateType);
1899                         return builder.MakeGenericMethod (targs);
1900 #else
1901                         return builder;
1902 #endif
1903                 }
1904
1905                 public static void Error_AddressOfCapturedVar (string name, Location loc)
1906                 {
1907                         Report.Error (1686, loc,
1908                                       "Local variable `{0}' or its members cannot have their " +
1909                                       "address taken and be used inside an anonymous method block",
1910                                       name);
1911                 }
1912         }
1913
1914         //
1915         // This will emit the code for the delegate, as well delegate creation on the host
1916         //
1917         public class AnonymousDelegate : DelegateCreation {
1918                 readonly AnonymousMethod am;
1919
1920                 //
1921                 // if target_type is null, this means that we do not know the type
1922                 // for this delegate, and we want to infer it from the various 
1923                 // returns (implicit and explicit) from the body of this anonymous
1924                 // method.
1925                 //
1926                 // for example, the lambda: x => 1
1927                 //
1928                 public AnonymousDelegate (AnonymousMethod am, Type target_type, Location l)
1929                 {
1930                         type = target_type;
1931                         loc = l;
1932                         this.am = am;
1933                 }
1934
1935                 public override Expression DoResolve (EmitContext ec)
1936                 {
1937                         eclass = ExprClass.Value;
1938                         return this;
1939                 }
1940                 
1941                 public override void Emit (EmitContext ec)
1942                 {
1943                         //ec.ig.Emit (OpCodes.Ldstr, "EMIT ANONYMOUS DELEGATE");
1944                         //ec.ig.Emit (OpCodes.Pop);
1945
1946                         //
1947                         // Now emit the delegate creation.
1948                         //
1949                         if ((am.Method.ModFlags & Modifiers.STATIC) == 0) {
1950                                 Report.Debug (128, "EMIT ANONYMOUS DELEGATE", this, am, am.Scope, loc);
1951                                 delegate_instance_expression = am.Scope.GetScopeInitializer (ec);
1952
1953                                 if (delegate_instance_expression == null)
1954                                         throw new InternalErrorException ();
1955                         }
1956
1957                         constructor_method = Delegate.GetConstructor (ec.ContainerType, type);
1958 #if MS_COMPATIBLE
1959                         if (type.IsGenericType && type is TypeBuilder)
1960                                 constructor_method = TypeBuilder.GetConstructor (type, (ConstructorInfo)constructor_method);
1961 #endif
1962                         
1963                         delegate_method = am.GetMethodBuilder (ec);
1964                         base.Emit (ec);
1965
1966                         //ec.ig.Emit (OpCodes.Ldstr, "EMIT ANONYMOUS DELEGATE DONE");
1967                         //ec.ig.Emit (OpCodes.Pop);
1968
1969                         Report.Debug (128, "EMIT ANONYMOUS DELEGATE DONE", this, am, am.Scope, loc);
1970                 }
1971         }
1972
1973         //
1974         // Anonymous type container
1975         //
1976         public class AnonymousTypeClass : CompilerGeneratedClass
1977         {
1978                 static int types_counter;
1979                 public const string ClassNamePrefix = "<>__AnonType";
1980                 public const string SignatureForError = "anonymous type";
1981                 
1982                 readonly ArrayList parameters;
1983
1984                 private AnonymousTypeClass (DeclSpace parent, MemberName name, ArrayList parameters, Location loc)
1985                         : base (parent, name, Modifiers.SEALED, loc)
1986                 {
1987                         this.parameters = parameters;
1988                 }
1989
1990                 public static AnonymousTypeClass Create (TypeContainer parent, ArrayList parameters, Location loc)
1991                 {
1992                         if (RootContext.Version <= LanguageVersion.ISO_2)
1993                                 Report.FeatureIsNotAvailable (loc, "anonymous types");
1994                         
1995                         string name = ClassNamePrefix + types_counter++;
1996
1997                         SimpleName [] t_args = new SimpleName [parameters.Count];
1998                         Parameter [] ctor_params = new Parameter [parameters.Count];
1999                         for (int i = 0; i < parameters.Count; ++i) {
2000                                 AnonymousTypeParameter p = (AnonymousTypeParameter) parameters [i];
2001
2002                                 t_args [i] = new SimpleName ("<" + p.Name + ">__T", p.Location);
2003                                 ctor_params [i] = new Parameter (t_args [i], p.Name, 0, null, p.Location);
2004                         }
2005
2006                         //
2007                         // Create generic anonymous type host with generic arguments
2008                         // named upon properties names
2009                         //
2010                         AnonymousTypeClass a_type = new AnonymousTypeClass (parent.NamespaceEntry.SlaveDeclSpace,
2011                                 new MemberName (name, new TypeArguments (loc, t_args), loc), parameters, loc);
2012
2013                         if (parameters.Count > 0)
2014                                 a_type.SetParameterInfo (null);
2015
2016                         Constructor c = new Constructor (a_type, name, Modifiers.PUBLIC,
2017                                 new Parameters (ctor_params), null, loc);
2018                         c.OptAttributes = a_type.GetDebuggerHiddenAttribute ();
2019                         c.Block = new ToplevelBlock (c.Parameters, loc);
2020
2021                         // 
2022                         // Create fields and contructor body with field initialization
2023                         //
2024                         bool error = false;
2025                         for (int i = 0; i < parameters.Count; ++i) {
2026                                 AnonymousTypeParameter p = (AnonymousTypeParameter) parameters [i];
2027
2028                                 Field f = new Field (a_type, t_args [i], Modifiers.PRIVATE | Modifiers.READONLY,
2029                                         "<" + p.Name + ">", null, p.Location);
2030
2031                                 if (!a_type.AddField (f)) {
2032                                         error = true;
2033                                         Report.Error (833, p.Location, "`{0}': An anonymous type cannot have multiple properties with the same name",
2034                                                 p.Name);
2035                                         continue;
2036                                 }
2037
2038                                 c.Block.AddStatement (new StatementExpression (
2039                                         new Assign (new MemberAccess (new This (p.Location), f.Name),
2040                                                 c.Block.GetParameterReference (p.Name, p.Location))));
2041
2042                                 ToplevelBlock get_block = new ToplevelBlock (p.Location);
2043                                 get_block.AddStatement (new Return (
2044                                         new MemberAccess (new This (p.Location), f.Name), p.Location));
2045                                 Accessor get_accessor = new Accessor (get_block, 0, null, p.Location);
2046                                 Property prop = new Property (a_type, t_args [i], Modifiers.PUBLIC, false,
2047                                         new MemberName (p.Name, p.Location), null, get_accessor, null, false);
2048                                 a_type.AddProperty (prop);
2049                         }
2050
2051                         if (error)
2052                                 return null;
2053
2054                         a_type.AddConstructor (c);
2055                         return a_type;
2056                 }
2057                 
2058                 public new static void Reset ()
2059                 {
2060                         types_counter = 0;
2061                 }
2062
2063                 protected override bool AddToContainer (MemberCore symbol, string name)
2064                 {
2065                         MemberCore mc = (MemberCore) defined_names [name];
2066
2067                         if (mc == null) {
2068                                 defined_names.Add (name, symbol);
2069                                 return true;
2070                         }
2071
2072                         Report.SymbolRelatedToPreviousError (mc);
2073                         return false;
2074                 }
2075
2076                 void DefineOverrides ()
2077                 {
2078                         Location loc = Location;
2079
2080                         Method equals = new Method (this, null, TypeManager.system_boolean_expr,
2081                                 Modifiers.PUBLIC | Modifiers.OVERRIDE, false, new MemberName ("Equals", loc),
2082                                 new Parameters (new Parameter (TypeManager.system_object_expr, "obj", 0, null, loc)),
2083                                 GetDebuggerHiddenAttribute ());
2084
2085                         Method tostring = new Method (this, null, TypeManager.system_string_expr,
2086                                 Modifiers.PUBLIC | Modifiers.OVERRIDE, false, new MemberName ("ToString", loc),
2087                                 Mono.CSharp.Parameters.EmptyReadOnlyParameters, GetDebuggerHiddenAttribute ());
2088
2089                         ToplevelBlock equals_block = new ToplevelBlock (equals.Parameters, loc);
2090                         TypeExpr current_type;
2091                         if (IsGeneric)
2092                                 current_type = new ConstructedType (TypeBuilder, TypeParameters, loc);
2093                         else
2094                                 current_type = new TypeExpression (TypeBuilder, loc);
2095
2096                         equals_block.AddVariable (current_type, "other", loc);
2097                         LocalVariableReference other_variable = new LocalVariableReference (equals_block, "other", loc);
2098
2099                         MemberAccess system_collections_generic = new MemberAccess (new MemberAccess (
2100                                 new SimpleName ("System", loc), "Collections", loc), "Generic", loc);
2101
2102                         Expression rs_equals = null;
2103                         Expression string_concat = new StringConstant ("<empty type>", loc);
2104                         Expression rs_hashcode = new IntConstant (-2128831035, loc);
2105                         for (int i = 0; i < parameters.Count; ++i) {
2106                                 AnonymousTypeParameter p = (AnonymousTypeParameter) parameters [i];
2107                                 Field f = (Field) Fields [i];
2108
2109                                 MemberAccess equality_comparer = new MemberAccess (new MemberAccess (
2110                                         system_collections_generic, "EqualityComparer",
2111                                                 new TypeArguments (loc, new SimpleName (TypeParameters [i].Name, loc)), loc),
2112                                                 "Default", loc);
2113
2114                                 ArrayList arguments_equal = new ArrayList (2);
2115                                 arguments_equal.Add (new Argument (new MemberAccess (new This (f.Location), f.Name)));
2116                                 arguments_equal.Add (new Argument (new MemberAccess (other_variable, f.Name)));
2117
2118                                 Expression field_equal = new Invocation (new MemberAccess (equality_comparer,
2119                                         "Equals", loc), arguments_equal);
2120
2121                                 ArrayList arguments_hashcode = new ArrayList (1);
2122                                 arguments_hashcode.Add (new Argument (new MemberAccess (new This (f.Location), f.Name)));
2123                                 Expression field_hashcode = new Invocation (new MemberAccess (equality_comparer,
2124                                         "GetHashCode", loc), arguments_hashcode);
2125
2126                                 IntConstant FNV_prime = new IntConstant (16777619, loc);                                
2127                                 rs_hashcode = new Binary (Binary.Operator.Multiply,
2128                                         new Binary (Binary.Operator.ExclusiveOr, rs_hashcode, field_hashcode),
2129                                         FNV_prime);
2130
2131                                 Expression field_to_string = new Conditional (new Binary (Binary.Operator.Inequality,
2132                                         new MemberAccess (new This (f.Location), f.Name), new NullLiteral (loc)),
2133                                         new Invocation (new MemberAccess (
2134                                                 new MemberAccess (new This (f.Location), f.Name), "ToString"), null),
2135                                         new StringConstant ("<null>", loc));
2136
2137                                 if (rs_equals == null) {
2138                                         rs_equals = field_equal;
2139                                         string_concat = new Binary (Binary.Operator.Addition,
2140                                                 new StringConstant (p.Name + " = ", loc),
2141                                                 field_to_string);
2142                                         continue;
2143                                 }
2144
2145                                 //
2146                                 // Implementation of ToString () body using string concatenation
2147                                 //                              
2148                                 string_concat = new Binary (Binary.Operator.Addition,
2149                                         new Binary (Binary.Operator.Addition,
2150                                                 string_concat,
2151                                                 new StringConstant (", " + p.Name + " = ", loc)),
2152                                         field_to_string);
2153
2154                                 rs_equals = new Binary (Binary.Operator.LogicalAnd, rs_equals, field_equal);
2155                         }
2156
2157                         //
2158                         // Equals (object obj) override
2159                         //
2160                         equals_block.AddStatement (new StatementExpression (
2161                                 new Assign (other_variable,
2162                                         new As (equals_block.GetParameterReference ("obj", loc),
2163                                                 current_type, loc), loc)));
2164
2165                         Expression equals_test = new Binary (Binary.Operator.Inequality, other_variable, new NullLiteral (loc));
2166                         if (rs_equals != null)
2167                                 equals_test = new Binary (Binary.Operator.LogicalAnd, equals_test, rs_equals);
2168                         equals_block.AddStatement (new Return (equals_test, loc));
2169
2170                         equals.Block = equals_block;
2171                         equals.ResolveMembers ();
2172                         AddMethod (equals);
2173
2174                         //
2175                         // GetHashCode () override
2176                         //
2177                         Method hashcode = new Method (this, null, TypeManager.system_int32_expr,
2178                                 Modifiers.PUBLIC | Modifiers.OVERRIDE, false, new MemberName ("GetHashCode", loc),
2179                                 Mono.CSharp.Parameters.EmptyReadOnlyParameters, GetDebuggerHiddenAttribute ());
2180
2181                         //
2182                         // Modified FNV with good avalanche behavior and uniform
2183                         // distribution with larger hash sizes.
2184                         //
2185                         // const int FNV_prime = 16777619;
2186                         // int hash = (int) 2166136261;
2187                         // foreach (int d in data)
2188                         //     hash = (hash ^ d) * FNV_prime;
2189                         // hash += hash << 13;
2190                         // hash ^= hash >> 7;
2191                         // hash += hash << 3;
2192                         // hash ^= hash >> 17;
2193                         // hash += hash << 5;
2194
2195                         ToplevelBlock hashcode_block = new ToplevelBlock (loc);
2196                         hashcode_block.AddVariable (TypeManager.system_int32_expr, "hash", loc);
2197                         LocalVariableReference hash_variable = new LocalVariableReference (hashcode_block, "hash", loc);
2198                         hashcode_block.AddStatement (new StatementExpression (
2199                                 new Assign (hash_variable, rs_hashcode)));
2200
2201                         hashcode_block.AddStatement (new StatementExpression (
2202                                 new CompoundAssign (Binary.Operator.Addition, hash_variable,
2203                                         new Binary (Binary.Operator.LeftShift, hash_variable, new IntConstant (13, loc)))));
2204                         hashcode_block.AddStatement (new StatementExpression (
2205                                 new CompoundAssign (Binary.Operator.ExclusiveOr, hash_variable,
2206                                         new Binary (Binary.Operator.RightShift, hash_variable, new IntConstant (7, loc)))));
2207                         hashcode_block.AddStatement (new StatementExpression (
2208                                 new CompoundAssign (Binary.Operator.Addition, hash_variable,
2209                                         new Binary (Binary.Operator.LeftShift, hash_variable, new IntConstant (3, loc)))));
2210                         hashcode_block.AddStatement (new StatementExpression (
2211                                 new CompoundAssign (Binary.Operator.ExclusiveOr, hash_variable,
2212                                         new Binary (Binary.Operator.RightShift, hash_variable, new IntConstant (17, loc)))));
2213                         hashcode_block.AddStatement (new StatementExpression (
2214                                 new CompoundAssign (Binary.Operator.Addition, hash_variable,
2215                                         new Binary (Binary.Operator.LeftShift, hash_variable, new IntConstant (5, loc)))));
2216
2217                         hashcode_block.AddStatement (new Return (hash_variable, loc));
2218                         hashcode.Block = hashcode_block;
2219                         hashcode.ResolveMembers ();
2220                         AddMethod (hashcode);
2221
2222                         //
2223                         // ToString () override
2224                         //
2225
2226                         ToplevelBlock tostring_block = new ToplevelBlock (loc);
2227                         tostring_block.AddStatement (new Return (string_concat, loc));
2228                         tostring.Block = tostring_block;
2229                         tostring.ResolveMembers ();
2230                         AddMethod (tostring);
2231                 }
2232
2233                 public override bool DefineMembers ()
2234                 {
2235                         DefineOverrides ();
2236
2237                         return base.DefineMembers ();
2238                 }
2239
2240                 Attributes GetDebuggerHiddenAttribute ()
2241                 {
2242                         return new Attributes (new Attribute (null, null,
2243                                 "System.Diagnostics.DebuggerHiddenAttribute", null, Location, false));
2244                 }
2245
2246                 public override string GetSignatureForError ()
2247                 {
2248                         return SignatureForError;
2249                 }
2250
2251                 public ArrayList Parameters {
2252                         get {
2253                                 return parameters;
2254                         }
2255                 }
2256         }
2257 }