039969833d2fea640d20452f05f0521277c17deb
[mono.git] / mcs / mcs / anonymous.cs
1 //
2 // anonymous.cs: Support for anonymous methods and types
3 //
4 // Author:
5 //   Miguel de Icaza (miguel@ximain.com)
6 //   Marek Safar (marek.safar@gmail.com)
7 //
8 // Dual licensed under the terms of the MIT X11 or GNU GPL
9 // Copyright 2003-2008 Novell, Inc.
10 //
11
12 using System;
13 using System.Text;
14 using System.Collections;
15 using System.Reflection;
16 using System.Reflection.Emit;
17
18 namespace Mono.CSharp {
19
20         public abstract class CompilerGeneratedClass : Class
21         {
22                 public static string MakeName (string host, string typePrefix, string name, int id)
23                 {
24                         return "<" + host + ">" + typePrefix + "__" + name + id.ToString ();
25                 }
26                 
27                 protected CompilerGeneratedClass (DeclSpace parent, MemberName name, int mod, Location loc)
28                         : base (parent.NamespaceEntry, parent, name, mod | Modifiers.COMPILER_GENERATED | Modifiers.SEALED, null)
29                 {
30                         parent.PartialContainer.AddCompilerGeneratedClass (this);
31                 }
32
33                 protected CompilerGeneratedClass (DeclSpace parent, GenericMethod generic, MemberName name, int mod, Location loc)
34                         : this (parent, name, mod, loc)
35                 {
36                         if (generic != null) {
37                                 ArrayList list = new ArrayList ();
38                                 foreach (TypeParameter tparam in generic.TypeParameters) {
39                                         if (tparam.Constraints != null)
40                                                 list.Add (tparam.Constraints.Clone ());
41                                 }
42                                 SetParameterInfo (list);
43                         }
44                 }
45
46                 protected void CheckMembersDefined ()
47                 {
48                         if (members_defined)
49                                 throw new InternalErrorException ("Helper class already defined!");
50                 }
51         }
52
53         //
54         // Anonymous method storey is created when an anonymous method uses
55         // variable or parameter from outer scope. They are then hoisted to
56         // anonymous method storey (captured)
57         //
58         public class AnonymousMethodStorey : CompilerGeneratedClass
59         {
60                 class StoreyFieldPair {
61                         public AnonymousMethodStorey Storey;
62                         public Field Field;
63
64                         public StoreyFieldPair (AnonymousMethodStorey storey)
65                         {
66                                 this.Storey = storey;
67                         }
68
69                         public override int GetHashCode ()
70                         {
71                                 return Storey.ID.GetHashCode ();
72                         }
73
74                         public override bool Equals (object obj)
75                         {
76                                 return (AnonymousMethodStorey)obj == Storey;
77                         }
78                 }
79
80                 class HoistedGenericField : Field
81                 {
82                         public HoistedGenericField (DeclSpace parent, FullNamedExpression type, int mod, string name,
83                                   Attributes attrs, Location loc)
84                                 : base (parent, type, mod, name, attrs, loc)
85                         {
86                         }
87
88                         public override bool Define ()
89                         {
90                                 type_name.Type = ((AnonymousMethodStorey) Parent).MutateType (type_name.Type);
91                                 return base.Define ();
92                         }
93                 }
94
95                 // TODO: Why is it required by debugger ?
96                 public readonly int ID;
97                 static int unique_id;
98
99                 public readonly Block OriginalSourceBlock;
100
101                 // A list of StoreyFieldPair with local field keeping parent storey instance
102                 ArrayList used_parent_storeys;
103
104                 // A list of hoisted parameters
105                 protected ArrayList hoisted_params;
106
107                 // Hoisted this
108                 HoistedThis hoisted_this;
109
110                 // Local variable which holds this storey instance
111                 public LocalTemporary Instance;
112
113                 bool references_defined;
114
115                 public AnonymousMethodStorey (Block block, DeclSpace parent, MemberBase host, GenericMethod generic, string name)
116                         : base (parent, generic, MakeMemberName (host, name, generic, block.StartLocation), Modifiers.PRIVATE, block.StartLocation)
117                 {
118                         Parent = parent;
119                         OriginalSourceBlock = block;
120                         ID = unique_id++;
121                 }
122
123                 static MemberName MakeMemberName (MemberBase host, string name, GenericMethod generic, Location loc)
124                 {
125                         string host_name = host == null ? null : host.Name;
126                         string tname = MakeName (host_name, "c", name, unique_id);
127                         TypeArguments args = null;
128                         if (generic != null) {
129                                 args = new TypeArguments (loc);
130                                 foreach (TypeParameter tparam in generic.CurrentTypeParameters)
131                                         args.Add (new SimpleName (tparam.Name, loc));
132                         }
133
134                         return new MemberName (tname, args, loc);
135                 }
136
137                 public Field AddCapturedVariable (string name, Type type)
138                 {
139                         CheckMembersDefined ();
140
141                         FullNamedExpression field_type = new TypeExpression (type, Location);
142                         if (!IsGeneric)
143                                 return AddCompilerGeneratedField (name, field_type);
144
145                         const int mod = Modifiers.INTERNAL | Modifiers.COMPILER_GENERATED;
146                         Field f = new HoistedGenericField (this, field_type, mod, name, null, Location);
147                         AddField (f);
148                         return f;
149                 }
150
151                 protected Field AddCompilerGeneratedField (string name, FullNamedExpression type)
152                 {
153                         const int mod = Modifiers.INTERNAL | Modifiers.COMPILER_GENERATED;
154                         Field f = new Field (this, type, mod, name, null, Location);
155                         AddField (f);
156                         return f;
157                 }
158
159                 public void AddParentStoreyReference (AnonymousMethodStorey s)
160                 {
161                         CheckMembersDefined ();
162
163                         if (used_parent_storeys == null)
164                                 used_parent_storeys = new ArrayList ();
165                         else if (used_parent_storeys.IndexOf (s) != -1)
166                                 return;
167
168                         used_parent_storeys.Add (new StoreyFieldPair (s));
169                 }
170
171                 public void CaptureLocalVariable (EmitContext ec, LocalInfo local_info)
172                 {
173                         if (local_info.HoistedVariableReference != null)
174                                 return;
175
176                         HoistedVariable var = new HoistedLocalVariable (this, local_info, GetVariableMangledName (local_info));
177                         local_info.HoistedVariableReference = var;
178                 }
179
180                 public void CaptureParameter (EmitContext ec, ParameterReference param_ref)
181                 {
182                         if (param_ref.HoistedVariable != null)
183                                 return;
184
185                         if (hoisted_params == null)
186                                 hoisted_params = new ArrayList ();
187
188                         HoistedVariable expr = new HoistedParameter (this, param_ref);
189                         param_ref.Parameter.HoistedVariableReference = expr;
190                         hoisted_params.Add (expr);
191                 }
192
193                 public HoistedThis CaptureThis (EmitContext ec, This t)
194                 {
195                         hoisted_this = new HoistedThis (this, t);
196                         return hoisted_this;
197                 }
198
199                 void DefineStoreyReferences ()
200                 {
201                         if (used_parent_storeys == null || references_defined)
202                                 return;
203
204                         references_defined = true;
205
206                         //
207                         // For each used variable from parent scope we allocate its local reference point
208                         //
209                         for (int i = 0; i < used_parent_storeys.Count; ++i) {
210                                 StoreyFieldPair sf = (StoreyFieldPair) used_parent_storeys [i];
211                                 AnonymousMethodStorey p_storey = sf.Storey;
212                                 TypeExpr type_expr = new TypeExpression (p_storey.TypeBuilder, Location);
213
214                                 sf.Field = AddCompilerGeneratedField ("<>f__ref$" + p_storey.ID, type_expr);
215                                 sf.Field.Define ();
216                         }
217                 }
218
219                 //
220                 // Initializes all hoisted variables
221                 //
222                 public void EmitHoistedVariables (EmitContext ec)
223                 {
224                         // There can be only one instance variable for each storey type
225                         if (Instance != null)
226                                 throw new InternalErrorException ();
227
228                         //
229                         // A storey with hoisted `this' is an instance method
230                         //
231                         if (!HasHoistedVariables) {
232                                 throw new NotImplementedException ();
233                         }
234
235                         DefineStoreyReferences ();
236
237                         //
238                         // Create an instance of storey type
239                         //
240                         Expression storey_type_expr;
241                         if (IsGeneric) {
242                                 //
243                                 // Use current method type parameter (MVAR) for top level storey only. All
244                                 // nested storeys use class type parameter (VAR)
245                                 //
246                                 TypeParameter[] tparams = ec.CurrentAnonymousMethod != null ?
247                                         ec.CurrentAnonymousMethod.Storey.CurrentTypeParameters :
248                                         ec.GenericDeclContainer.CurrentTypeParameters;
249
250                                 if (tparams.Length != CountTypeParameters) {
251                                         TypeParameter [] full = new TypeParameter [CountTypeParameters];
252                                         DeclSpace parent = ec.DeclContainer.Parent;
253                                         parent.CurrentTypeParameters.CopyTo (full, 0);
254                                         tparams.CopyTo (full, parent.CountTypeParameters);
255                                         tparams = full;
256                                 }
257
258                                 storey_type_expr = new ConstructedType (TypeBuilder, tparams, Location);
259                         } else {
260                                 storey_type_expr = new TypeExpression (TypeBuilder, Location);
261                         }
262
263                         Expression e = new New (storey_type_expr, new ArrayList (0), Location).Resolve (ec);
264                         e.Emit (ec);
265
266                         Instance = new LocalTemporary (storey_type_expr.Type);
267                         Instance.Store (ec);
268
269                         EmitHoistedFieldsInitialization (ec);
270                 }
271
272                 void EmitHoistedFieldsInitialization (EmitContext ec)
273                 {
274                         //
275                         // Initialize all storey reference fields by using local or hoisted variables
276                         //
277                         if (used_parent_storeys != null) {
278                                 foreach (StoreyFieldPair sf in used_parent_storeys) {
279                                         //
280                                         // Setting local field
281                                         //
282                                         FieldExpr f_set_expr = new FieldExpr (sf.Field.FieldBuilder, Location);
283                                         f_set_expr.InstanceExpression = GetStoreyInstanceExpression (ec);
284
285                                         SimpleAssign a = new SimpleAssign (f_set_expr, sf.Storey.GetStoreyInstanceExpression (ec));
286                                         if (a.Resolve (ec) != null)
287                                                 a.EmitStatement (ec);
288                                 }
289                         }
290
291                         //
292                         // Setting currect anonymous method to null blocks any further variable hoisting
293                         //
294                         AnonymousExpression ae = ec.CurrentAnonymousMethod;
295                         ec.CurrentAnonymousMethod = null;
296
297                         if (hoisted_params != null) {
298                                 foreach (HoistedParameter hp in hoisted_params) {
299                                         hp.EmitHoistingAssignment (ec);
300                                 }
301                         }
302
303                         if (hoisted_this != null) {
304                                 hoisted_this.EmitHoistingAssignment (ec);
305                         }
306
307                         ec.CurrentAnonymousMethod = ae;
308                 }
309
310                 public override void EmitType ()
311                 {
312                         DefineStoreyReferences ();
313                         base.EmitType ();
314                 }
315
316                 //
317                 // Returns a field which holds referenced storey instance
318                 //
319                 Field GetReferencedStoreyField (AnonymousMethodStorey storey)
320                 {
321                         if (used_parent_storeys == null)
322                                 return null;
323
324                         foreach (StoreyFieldPair sf in used_parent_storeys) {
325                                 if (sf.Storey == storey)
326                                         return sf.Field;
327                         }
328
329                         return null;
330                 }
331
332                 //
333                 // Creates storey instance expression regardless of currect IP
334                 //
335                 public Expression GetStoreyInstanceExpression (EmitContext ec)
336                 {
337                         AnonymousExpression am = ec.CurrentAnonymousMethod;
338
339                         //
340                         // Access from original block -> storey
341                         //
342                         if (am == null)
343                                 return Instance;
344
345                         //
346                         // Access from anonymous method implemented as a static -> storey
347                         //
348                         if (am.Storey == null)
349                                 return Instance;
350
351                         Field f = am.Storey.GetReferencedStoreyField (this);
352                         if (f == null) {
353                                 if (am.Storey == this) {
354                                         //
355                                         // Access inside of same storey (S -> S)
356                                         //
357                                         return new CompilerGeneratedThis (TypeBuilder, Location);
358                                 }
359                                 //
360                                 // External field access
361                                 //
362                                 return Instance;
363                         }
364
365                         //
366                         // Storey was cached to local field
367                         //
368                         FieldExpr f_ind = new FieldExpr (f.FieldBuilder, Location);
369                         f_ind.InstanceExpression = new CompilerGeneratedThis (TypeBuilder, Location);
370                         return f_ind;
371                 }
372
373                 protected virtual string GetVariableMangledName (LocalInfo local_info)
374                 {
375                         //
376                         // No need to mangle anonymous method hoisted variables cause they
377                         // are hoisted in their own scopes
378                         //
379                         return local_info.Name;
380                 }
381
382                 public bool HasHoistedVariables {
383                         get {
384                                 return true; // TODO: Finish this optimization
385                         }
386                 }
387
388                 //
389                 // Mutate type dispatcher
390                 //
391                 public Type MutateType (Type type)
392                 {
393 #if GMCS_SOURCE
394                         if (TypeManager.IsGenericType (type))
395                                 return MutateGenericType (type);
396
397                         if (TypeManager.IsGenericParameter (type))
398                                 return MutateGenericArgument (type);
399
400                         if (type.IsArray)
401                                 return MutateArrayType (type);
402 #endif
403                         return type;
404                 }
405
406                 //
407                 // Changes method type arguments (MVAR) to storey (VAR) type arguments
408                 //
409                 public MethodInfo MutateGenericMethod (MethodInfo method)
410                 {
411 #if GMCS_SOURCE
412                         if (TypeManager.IsGenericType (method.DeclaringType)) {
413                                 Type t = MutateGenericType (method.DeclaringType);
414                                 if (t != method.DeclaringType)
415                                         method = TypeBuilder.GetMethod (t, method);
416                         }
417
418                         Type [] t_args = TypeManager.GetGenericArguments (method);
419                         if (t_args == null || t_args.Length == 0)
420                                 return method;
421
422                         for (int i = 0; i < t_args.Length; ++i)
423                                 t_args [i] = MutateType (t_args [i]);
424
425                         return method.GetGenericMethodDefinition ().MakeGenericMethod (t_args);
426 #else
427                         throw new NotSupportedException ();
428 #endif
429                 }
430
431                 public ConstructorInfo MutateConstructor (ConstructorInfo ctor)
432                 {
433 #if GMCS_SOURCE         
434                         if (TypeManager.IsGenericType (ctor.DeclaringType)) {
435                                 Type t = MutateGenericType (ctor.DeclaringType);
436                                 if (t != ctor.DeclaringType) {
437                                         // TODO: It should throw on imported types
438                                         return TypeBuilder.GetConstructor (t, ctor);
439                                 }
440                         }
441 #endif
442                         return ctor;
443                 }
444
445 #if GMCS_SOURCE
446                 protected Type MutateArrayType (Type array)
447                 {
448                         int rank = array.GetArrayRank ();
449                         Type element = TypeManager.GetElementType (array);
450                         if (element.IsArray)
451                                 throw new NotImplementedException ();
452
453                         if (TypeManager.IsGenericParameter (element)) {
454                                 element = MutateGenericArgument (element);
455                         } else if (TypeManager.IsGenericType (element)) {
456                                 element = MutateGenericType (element);
457                         } else {
458                                 return array;
459                         }
460
461                         return element.MakeArrayType (rank);
462                 }
463
464                 protected Type MutateGenericType (Type type)
465                 {
466                         Type [] t_args = TypeManager.GetTypeArguments (type);
467                         if (t_args == null || t_args.Length == 0)
468                                 return type;
469
470                         for (int i = 0; i < t_args.Length; ++i)
471                                 t_args [i] = MutateType (t_args [i]);
472
473                         return type.GetGenericTypeDefinition ().MakeGenericType (t_args);
474                 }
475 #endif
476
477                 //
478                 // Changes method generic argument (MVAR) to type generic argument (VAR)
479                 //
480                 public Type MutateGenericArgument (Type type)
481                 {
482                         foreach (TypeParameter tp in CurrentTypeParameters) {
483                                 if (tp.Name == type.Name) {
484                                         return tp.Type;
485                                 }
486                         }
487
488                         return type;
489                 }
490
491                 public static void Reset ()
492                 {
493                         unique_id = 0;
494                 }
495         }
496
497         public abstract class HoistedVariable
498         {
499                 protected readonly AnonymousMethodStorey storey;
500                 protected Field field;
501                 Hashtable cached_inner_access; // TODO: Hashtable is too heavyweight
502
503                 protected HoistedVariable (AnonymousMethodStorey storey, string name, Type type)
504                 {
505                         this.storey = storey;
506
507                         this.field = storey.AddCapturedVariable (name, type);
508                 }
509
510                 public void AddressOf (EmitContext ec, AddressOp mode)
511                 {
512                         GetFieldExpression (ec).AddressOf (ec, mode);
513                 }
514
515                 public void Emit (EmitContext ec)
516                 {
517                         GetFieldExpression (ec).Emit (ec);
518                 }
519
520                 //
521                 // Creates field access expression for hoisted variable
522                 //
523                 protected FieldExpr GetFieldExpression (EmitContext ec)
524                 {
525                         if (ec.CurrentAnonymousMethod == null) {
526                                 //
527                                 // When setting top-level hoisted variable in generic storey
528                                 // change storey generic types to method generic types (VAR -> MVAR)
529                                 //
530                                 FieldExpr outer_access = storey.MemberName.IsGeneric ?
531                                         new FieldExpr (field.FieldBuilder, storey.Instance.Type, field.Location) :
532                                         new FieldExpr (field.FieldBuilder, field.Location);
533
534                                 outer_access.InstanceExpression = storey.GetStoreyInstanceExpression (ec);
535                                 outer_access.Resolve (ec);
536                                 return outer_access;
537                         }
538
539                         FieldExpr inner_access;
540                         if (cached_inner_access != null) {
541                                 inner_access = (FieldExpr) cached_inner_access [ec.CurrentAnonymousMethod];
542                         } else {
543                                 inner_access = null;
544                                 cached_inner_access = new Hashtable (4);
545                         }
546
547                         if (inner_access == null) {
548                                 inner_access = new FieldExpr (field.FieldBuilder, field.Location);
549                                 inner_access.InstanceExpression = storey.GetStoreyInstanceExpression (ec);
550                                 inner_access.Resolve (ec);
551                                 cached_inner_access.Add (ec.CurrentAnonymousMethod, inner_access);
552                         }
553
554                         return inner_access;
555                 }
556
557                 public abstract void EmitSymbolInfo ();
558
559                 public void Emit (EmitContext ec, bool leave_copy)
560                 {
561                         GetFieldExpression (ec).Emit (ec, leave_copy);
562                 }
563
564                 public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool prepare_for_load)
565                 {
566                         GetFieldExpression (ec).EmitAssign (ec, source, leave_copy, false);
567                 }
568         }
569
570         class HoistedParameter : HoistedVariable
571         {
572                 class HoistedFieldAssign : Assign
573                 {
574                         public HoistedFieldAssign (Expression target, Expression source)
575                                 : base (target, source, source.Location)
576                         {
577                         }
578
579                         protected override Expression ResolveConversions (EmitContext ec)
580                         {
581                                 //
582                                 // Implicit conversion check fails for hoisted type arguments
583                                 // as they are of different types (!!0 x !0)
584                                 //
585                                 return this;
586                         }
587                 }
588
589                 readonly ParameterReference parameter;
590
591                 public HoistedParameter (AnonymousMethodStorey scope, ParameterReference par)
592                         : base (scope, par.Name, par.Type)
593                 {
594                         this.parameter = par;
595                 }
596
597                 public void EmitHoistingAssignment (EmitContext ec)
598                 {
599                         //
600                         // Remove hoisted redirection to emit assignment from original parameter
601                         //
602                         HoistedVariable temp = parameter.Parameter.HoistedVariableReference;
603                         parameter.Parameter.HoistedVariableReference = null;
604
605                         Assign a = new HoistedFieldAssign (GetFieldExpression (ec), parameter);
606                         if (a.Resolve (ec) != null)
607                                 a.EmitStatement (ec);
608
609                         parameter.Parameter.HoistedVariableReference = temp;
610                 }
611
612                 public override void EmitSymbolInfo ()
613                 {
614                         SymbolWriter.DefineCapturedParameter (storey.ID, field.Name, field.Name);
615                 }
616
617                 public Field Field {
618                         get { return field; }
619                 }
620         }
621
622         class HoistedLocalVariable : HoistedVariable
623         {
624                 public HoistedLocalVariable (AnonymousMethodStorey scope, LocalInfo local, string name)
625                         : base (scope, name, local.VariableType)
626                 {
627                 }
628
629                 public override void EmitSymbolInfo ()
630                 {
631                         SymbolWriter.DefineCapturedLocal (storey.ID, field.Name, field.Name);
632                 }
633         }
634
635         public class HoistedThis : HoistedVariable
636         {
637                 readonly This this_reference;
638
639                 public HoistedThis (AnonymousMethodStorey storey, This this_reference)
640                         : base (storey, "<>f__this", this_reference.Type)
641                 {
642                         this.this_reference = this_reference;
643                 }
644
645                 public void EmitHoistingAssignment (EmitContext ec)
646                 {
647                         SimpleAssign a = new SimpleAssign (GetFieldExpression (ec), this_reference);
648                         if (a.Resolve (ec) != null)
649                                 a.EmitStatement (ec);
650                 }
651
652                 public override void EmitSymbolInfo ()
653                 {
654                         SymbolWriter.DefineCapturedThis (storey.ID, field.Name);
655                 }
656         }
657
658         // TODO: Remove, it should be done in block
659         public interface IAnonymousHost
660         {
661                 //
662                 // Invoked if a yield statement is found in the body
663                 //
664                 void SetYields ();
665         }
666
667         //
668         // Anonymous method expression as created by parser
669         //
670         public class AnonymousMethodExpression : Expression
671         {
672                 protected readonly TypeContainer Host;
673                 public readonly Parameters Parameters;
674
675                 public ToplevelBlock Block;
676
677                 public AnonymousMethodExpression (TypeContainer host, Parameters parameters, Location loc)
678                 {
679                         this.Host = host;
680                         this.Parameters = parameters;
681                         this.loc = loc;
682                 }
683
684                 public override string ExprClassName {
685                         get {
686                                 return "anonymous method";
687                         }
688                 }
689
690                 public virtual bool HasExplicitParameters {
691                         get {
692                                 return Parameters != null;
693                         }
694                 }
695
696                 //
697                 // Returns true if the body of lambda expression can be implicitly
698                 // converted to the delegate of type `delegate_type'
699                 //
700                 public bool ImplicitStandardConversionExists (EmitContext ec, Type delegate_type)
701                 {
702                         using (ec.Set (EmitContext.Flags.ProbingMode)) {
703                                 return Compatible (ec, delegate_type) != null;
704                         }
705                 }
706
707                 protected Type CompatibleChecks (EmitContext ec, Type delegate_type)
708                 {
709                         if (TypeManager.IsDelegateType (delegate_type))
710                                 return delegate_type;
711
712 #if GMCS_SOURCE
713                         if (TypeManager.DropGenericTypeArguments (delegate_type) == TypeManager.expression_type) {
714                                 delegate_type = TypeManager.GetTypeArguments (delegate_type) [0];
715                                 if (TypeManager.IsDelegateType (delegate_type))
716                                         return delegate_type;
717
718                                 Report.Error (835, loc, "Cannot convert `{0}' to an expression tree of non-delegate type `{1}'",
719                                         GetSignatureForError (), TypeManager.CSharpName (delegate_type));
720                                 return null;
721                         }
722 #endif
723
724                         Report.Error (1660, loc, "Cannot convert `{0}' to non-delegate type `{1}'",
725                                       GetSignatureForError (), TypeManager.CSharpName (delegate_type));
726                         return null;
727                 }
728
729                 protected bool VerifyExplicitParameters (Type delegate_type, ParameterData parameters, bool ignore_error)
730                 {
731                         if (VerifyParameterCompatibility (delegate_type, parameters, ignore_error))
732                                 return true;
733
734                         if (!ignore_error)
735                                 Report.Error (1661, loc,
736                                         "Cannot convert `{0}' to delegate type `{1}' since there is a parameter mismatch",
737                                         GetSignatureForError (), TypeManager.CSharpName (delegate_type));
738
739                         return false;
740                 }
741
742                 protected bool VerifyParameterCompatibility (Type delegate_type, ParameterData invoke_pd, bool ignore_errors)
743                 {
744                         if (Parameters.Count != invoke_pd.Count) {
745                                 if (ignore_errors)
746                                         return false;
747                                 
748                                 Report.Error (1593, loc, "Delegate `{0}' does not take `{1}' arguments",
749                                               TypeManager.CSharpName (delegate_type), Parameters.Count.ToString ());
750                                 return false;
751                         }
752                         
753                         if (!HasExplicitParameters)
754                                 return true;                    
755
756                         bool error = false;
757                         for (int i = 0; i < Parameters.Count; ++i) {
758                                 Parameter.Modifier p_mod = invoke_pd.ParameterModifier (i);
759                                 if (Parameters.ParameterModifier (i) != p_mod && p_mod != Parameter.Modifier.PARAMS) {
760                                         if (ignore_errors)
761                                                 return false;
762                                         
763                                         if (p_mod == Parameter.Modifier.NONE)
764                                                 Report.Error (1677, loc, "Parameter `{0}' should not be declared with the `{1}' keyword",
765                                                               (i + 1).ToString (), Parameter.GetModifierSignature (Parameters.ParameterModifier (i)));
766                                         else
767                                                 Report.Error (1676, loc, "Parameter `{0}' must be declared with the `{1}' keyword",
768                                                               (i+1).ToString (), Parameter.GetModifierSignature (p_mod));
769                                         error = true;
770                                         continue;
771                                 }
772
773                                 Type type = invoke_pd.Types [i];
774                                 
775                                 // We assume that generic parameters are always inflated
776                                 if (TypeManager.IsGenericParameter (type))
777                                         continue;
778                                 
779                                 if (TypeManager.HasElementType (type) && TypeManager.IsGenericParameter (TypeManager.GetElementType (type)))
780                                         continue;
781                                 
782                                 if (invoke_pd.ParameterType (i) != Parameters.ParameterType (i)) {
783                                         if (ignore_errors)
784                                                 return false;
785                                         
786                                         Report.Error (1678, loc, "Parameter `{0}' is declared as type `{1}' but should be `{2}'",
787                                                       (i+1).ToString (),
788                                                       TypeManager.CSharpName (Parameters.ParameterType (i)),
789                                                       TypeManager.CSharpName (invoke_pd.ParameterType (i)));
790                                         error = true;
791                                 }
792                         }
793
794                         return !error;
795                 }
796
797                 //
798                 // Infers type arguments based on explicit arguments
799                 //
800                 public bool ExplicitTypeInference (TypeInferenceContext type_inference, Type delegate_type)
801                 {
802                         if (!HasExplicitParameters)
803                                 return false;
804
805                         if (!TypeManager.IsDelegateType (delegate_type)) {
806 #if GMCS_SOURCE
807                                 if (TypeManager.DropGenericTypeArguments (delegate_type) != TypeManager.expression_type)
808                                         return false;
809
810                                 delegate_type = delegate_type.GetGenericArguments () [0];
811                                 if (!TypeManager.IsDelegateType (delegate_type))
812                                         return false;
813 #else
814                                 return false;
815 #endif
816                         }
817                         
818                         ParameterData d_params = TypeManager.GetDelegateParameters (delegate_type);
819                         if (d_params.Count != Parameters.Count)
820                                 return false;
821
822                         for (int i = 0; i < Parameters.Count; ++i) {
823                                 Type itype = d_params.Types [i];
824                                 if (!TypeManager.IsGenericParameter (itype)) {
825                                         if (!TypeManager.HasElementType (itype))
826                                                 continue;
827                                         
828                                         if (!TypeManager.IsGenericParameter (itype.GetElementType ()))
829                                             continue;
830                                 }
831                                 type_inference.ExactInference (Parameters.FixedParameters[i].ParameterType, itype);
832                         }
833                         return true;
834                 }
835
836                 public Type InferReturnType (EmitContext ec, TypeInferenceContext tic, Type delegate_type)
837                 {
838                         AnonymousMethodBody am;
839                         using (ec.Set (EmitContext.Flags.ProbingMode | EmitContext.Flags.InferReturnType)) {
840                                 am = CompatibleMethod (ec, tic, GetType (), delegate_type);
841                         }
842                         
843                         if (am == null)
844                                 return null;
845
846                         if (am.ReturnType == TypeManager.null_type)
847                                 am.ReturnType = null;
848
849                         return am.ReturnType;
850                 }
851
852                 //
853                 // Returns AnonymousMethod container if this anonymous method
854                 // expression can be implicitly converted to the delegate type `delegate_type'
855                 //
856                 public Expression Compatible (EmitContext ec, Type type)
857                 {
858                         Type delegate_type = CompatibleChecks (ec, type);
859                         if (delegate_type == null)
860                                 return null;
861
862                         //
863                         // At this point its the first time we know the return type that is 
864                         // needed for the anonymous method.  We create the method here.
865                         //
866
867                         MethodInfo invoke_mb = Delegate.GetInvokeMethod (
868                                 ec.ContainerType, delegate_type);
869                         Type return_type = TypeManager.TypeToCoreType (invoke_mb.ReturnType);
870
871 #if MS_COMPATIBLE
872                         Type[] g_args = delegate_type.GetGenericArguments ();
873                         if (return_type.IsGenericParameter)
874                                 return_type = g_args [return_type.GenericParameterPosition];
875 #endif
876
877                         //
878                         // Second: the return type of the delegate must be compatible with 
879                         // the anonymous type.   Instead of doing a pass to examine the block
880                         // we satisfy the rule by setting the return type on the EmitContext
881                         // to be the delegate type return type.
882                         //
883
884                         try {
885                                 int errors = Report.Errors;
886                                 AnonymousMethodBody am = CompatibleMethod (ec, null, return_type, delegate_type);
887                                 if (am != null && delegate_type != type && errors == Report.Errors)
888                                         return CreateExpressionTree (ec, delegate_type);
889
890                                 return am;
891                         } catch (Exception e) {
892                                 throw new InternalErrorException (e, loc);
893                         }
894                 }
895
896                 protected virtual Expression CreateExpressionTree (EmitContext ec, Type delegate_type)
897                 {
898                         return CreateExpressionTree (ec);
899                 }
900
901                 public override Expression CreateExpressionTree (EmitContext ec)
902                 {
903                         Report.Error (1946, loc, "An anonymous method cannot be converted to an expression tree");
904                         return null;
905                 }
906
907                 protected virtual Parameters ResolveParameters (EmitContext ec, TypeInferenceContext tic, Type delegate_type)
908                 {
909                         ParameterData delegate_parameters = TypeManager.GetDelegateParameters (delegate_type);
910
911                         if (Parameters == null) {
912                                 //
913                                 // We provide a set of inaccessible parameters
914                                 //
915                                 Parameter[] fixedpars = new Parameter[delegate_parameters.Count];
916
917                                 for (int i = 0; i < delegate_parameters.Count; i++) {
918                                         Parameter.Modifier i_mod = delegate_parameters.ParameterModifier (i);
919                                         if ((i_mod & Parameter.Modifier.OUTMASK) != 0) {
920                                                 Report.Error (1688, loc, "Cannot convert anonymous " +
921                                                                   "method block without a parameter list " +
922                                                                   "to delegate type `{0}' because it has " +
923                                                                   "one or more `out' parameters.",
924                                                                   TypeManager.CSharpName (delegate_type));
925                                                 return null;
926                                         }
927                                         fixedpars[i] = new Parameter (
928                                                 delegate_parameters.ParameterType (i), null,
929                                                 delegate_parameters.ParameterModifier (i), null, loc);
930                                 }
931
932                                 return Parameters.CreateFullyResolved (fixedpars, delegate_parameters.Types);
933                         }
934
935                         if (!VerifyExplicitParameters (delegate_type, delegate_parameters, ec.IsInProbingMode)) {
936                                 return null;
937                         }
938
939                         return Parameters;
940                 }
941
942                 public override Expression DoResolve (EmitContext ec)
943                 {
944                         if (!ec.IsAnonymousMethodAllowed) {
945                                 Report.Error (1706, loc, "Anonymous methods and lambda expressions cannot be used in the current context");
946                                 return null;
947                         }
948
949                         //
950                         // Set class type, set type
951                         //
952
953                         eclass = ExprClass.Value;
954
955                         //
956                         // This hack means `The type is not accessible
957                         // anywhere', we depend on special conversion
958                         // rules.
959                         // 
960                         type = TypeManager.anonymous_method_type;
961
962                         if ((Parameters != null) && !Parameters.Resolve (ec))
963                                 return null;
964
965                         // FIXME: The emitted code isn't very careful about reachability
966                         // so, ensure we have a 'ret' at the end
967                         if (ec.CurrentBranching != null &&
968                             ec.CurrentBranching.CurrentUsageVector.IsUnreachable)
969                                 ec.NeedReturnLabel ();
970
971                         return this;
972                 }
973
974                 public override void Emit (EmitContext ec)
975                 {
976                         // nothing, as we only exist to not do anything.
977                 }
978
979                 public override string GetSignatureForError ()
980                 {
981                         return ExprClassName;
982                 }
983
984                 protected AnonymousMethodBody CompatibleMethod (EmitContext ec, TypeInferenceContext tic, Type return_type, Type delegate_type)
985                 {
986                         Parameters p = ResolveParameters (ec, tic, delegate_type);
987                         if (p == null)
988                                 return null;
989
990                         ToplevelBlock b = ec.IsInProbingMode ? (ToplevelBlock) Block.PerformClone () : Block;
991
992                         AnonymousMethodBody anonymous = CompatibleMethodFactory (return_type, delegate_type, p, b);
993                         if (!anonymous.Compatible (ec))
994                                 return null;
995
996                         return anonymous;
997                 }
998
999                 protected virtual AnonymousMethodBody CompatibleMethodFactory (Type return_type, Type delegate_type, Parameters p, ToplevelBlock b)
1000                 {
1001                         return new AnonymousMethodBody (Host,
1002                                 p, b, return_type,
1003                                 delegate_type, loc);
1004                 }
1005
1006                 protected override void CloneTo (CloneContext clonectx, Expression t)
1007                 {
1008                         AnonymousMethodExpression target = (AnonymousMethodExpression) t;
1009
1010                         target.Block = (ToplevelBlock) clonectx.LookupBlock (Block);
1011                 }
1012         }
1013
1014         //
1015         // Abstract expression for any block which requires variables hoisting
1016         //
1017         public abstract class AnonymousExpression : Expression
1018         {
1019                 protected class AnonymousMethodMethod : Method
1020                 {
1021                         public readonly AnonymousExpression AnonymousMethod;
1022                         public readonly AnonymousMethodStorey Storey;
1023                         readonly string RealName;
1024
1025                         public AnonymousMethodMethod (DeclSpace parent, AnonymousExpression am, AnonymousMethodStorey storey,
1026                                                           GenericMethod generic, TypeExpr return_type,
1027                                                           int mod, string real_name, MemberName name,
1028                                                           Parameters parameters)
1029                                 : base (parent, generic, return_type, mod | Modifiers.COMPILER_GENERATED,
1030                                                 false, name, parameters, null)
1031                         {
1032                                 this.AnonymousMethod = am;
1033                                 this.Storey = storey;
1034                                 this.RealName = real_name;
1035
1036                                 Parent.PartialContainer.AddMethod (this);
1037                                 Block = am.Block;
1038                         }
1039
1040                         public override EmitContext CreateEmitContext (DeclSpace tc, ILGenerator ig)
1041                         {
1042                                 EmitContext aec = AnonymousMethod.aec;
1043                                 aec.ig = ig;
1044                                 aec.IsStatic = (ModFlags & Modifiers.STATIC) != 0;
1045                                 return aec;
1046                         }
1047
1048                         public override bool Define ()
1049                         {
1050                                 if (Storey != null && Storey.IsGeneric) {
1051                                         if (!Parameters.Empty) {
1052                                                 Type [] ptypes = Parameters.Types;
1053                                                 for (int i = 0; i < ptypes.Length; ++i) {
1054                                                         if (TypeManager.IsGenericParameter (ptypes [i]))
1055                                                                 ptypes [i] = Storey.MutateType (ptypes [i]);
1056                                                 }
1057                                         }
1058
1059                                         member_type = Storey.MutateType (ReturnType);
1060                                 }
1061
1062                                 return base.Define ();
1063                         }
1064
1065                         public override void Emit ()
1066                         {
1067                                 //
1068                                 // Before emitting any code we have to change all MVAR references to VAR
1069                                 // when the method is of generic type and has hoisted variables
1070                                 //
1071                                 if (Storey == Parent && Storey.IsGeneric) {
1072                                         AnonymousMethod.aec.ReturnType = Storey.MutateType (ReturnType);
1073                                         block.MutateHoistedGenericType (Storey);
1074                                 }
1075
1076                                 base.Emit ();
1077                         }
1078
1079                         public override void EmitExtraSymbolInfo (SourceMethod source)
1080                         {
1081                                 source.SetRealMethodName (RealName);
1082                         }
1083                 }
1084
1085                 //
1086                 // The block that makes up the body for the anonymous method
1087                 //
1088                 protected readonly ToplevelBlock Block;
1089
1090                 public Type ReturnType;
1091                 public readonly DeclSpace Host;
1092
1093                 //
1094                 // The implicit method we create
1095                 //
1096                 protected AnonymousMethodMethod method;
1097                 protected EmitContext aec;
1098
1099                 protected AnonymousExpression (DeclSpace host, ToplevelBlock block, Type return_type, Location loc)
1100                 {
1101                         this.ReturnType = return_type;
1102                         this.Host = host;
1103
1104                         this.Block = block;
1105                         this.loc = loc;
1106                 }
1107
1108                 public abstract void AddStoreyReference (AnonymousMethodStorey storey);
1109                 public abstract string ContainerType { get; }
1110                 public abstract bool IsIterator { get; }
1111                 public abstract AnonymousMethodStorey Storey { get; }
1112
1113                 public bool Compatible (EmitContext ec)
1114                 {
1115                         // TODO: Implement clone
1116                         aec = new EmitContext (
1117                                 ec.ResolveContext, ec.TypeContainer, ec.DeclContainer,
1118                                 Location, null, ReturnType,
1119                                 /* REVIEW */ (ec.InIterator ? Modifiers.METHOD_YIELDS : 0) |
1120                                 (ec.InUnsafe ? Modifiers.UNSAFE : 0), /* No constructor */ false);
1121
1122                         aec.CurrentAnonymousMethod = this;
1123                         aec.IsStatic = ec.IsStatic;
1124
1125                         IDisposable aec_dispose = null;
1126                         EmitContext.Flags flags = 0;
1127                         if (ec.InferReturnType)
1128                                 flags |= EmitContext.Flags.InferReturnType;
1129
1130                         if (ec.IsInProbingMode)
1131                                 flags |= EmitContext.Flags.ProbingMode;
1132
1133                         if (ec.IsInFieldInitializer)
1134                                 flags |= EmitContext.Flags.InFieldInitializer;
1135
1136                         if (ec.IsInUnsafeScope)
1137                                 flags |= EmitContext.Flags.InUnsafe;
1138
1139                         // HACK: Flag with 0 cannot be set 
1140                         if (flags != 0)
1141                                 aec_dispose = aec.Set (flags);
1142
1143                         bool unreachable;
1144                         bool res = aec.ResolveTopBlock (ec, Block, Block.Parameters, null, out unreachable);
1145
1146                         if (ec.InferReturnType)
1147                                 ReturnType = aec.ReturnType;
1148
1149                         if (aec_dispose != null) {
1150                                 aec_dispose.Dispose ();
1151                         }
1152
1153                         return res;
1154                 }
1155         }
1156
1157         public class AnonymousMethodBody : AnonymousExpression
1158         {
1159                 ArrayList referenced_storeys;
1160                 readonly Parameters parameters;
1161                 static int unique_id;
1162
1163                 public AnonymousMethodBody (
1164                                         DeclSpace host,
1165                                         Parameters parameters,
1166                                         ToplevelBlock block, Type return_type, Type delegate_type,
1167                                         Location loc)
1168                         : base (host, block, return_type, loc)
1169                 {
1170                         this.type = delegate_type;
1171                         this.parameters = parameters;
1172                 }
1173
1174                 public override string ContainerType {
1175                         get { return "anonymous method"; }
1176                 }
1177
1178                 public override AnonymousMethodStorey Storey {
1179                         get { return method.Storey; }
1180                 }
1181
1182                 public override bool IsIterator {
1183                         get { return false; }
1184                 }
1185
1186                 //
1187                 // Adds new storey reference to track out of scope variables
1188                 //
1189                 public override void AddStoreyReference (AnonymousMethodStorey storey)
1190                 {
1191                         if (referenced_storeys == null) {
1192                                 referenced_storeys = new ArrayList ();
1193                         } else {
1194                                 foreach (AnonymousMethodStorey ams in referenced_storeys) {
1195                                         if (ams == storey)
1196                                                 return;
1197                                 }
1198                         }
1199
1200                         referenced_storeys.Add (storey);
1201                 }
1202
1203                 public override Expression CreateExpressionTree (EmitContext ec)
1204                 {
1205                         Report.Error (1945, loc, "An expression tree cannot contain an anonymous method expression");
1206                         return null;
1207                 }
1208
1209                 bool Define (EmitContext ec)
1210                 {
1211                         if (aec == null && !Compatible (ec))
1212                                 return false;
1213
1214                         // Don't define anything when we are in probing scope (nested anonymous methods)
1215                         if (ec.IsInProbingMode)
1216                                 return true;
1217
1218                         method = DoCreateMethodHost (ec);
1219
1220                         //
1221                         // Define method only when is not inside AnonymousMethodStorey because a container passed its Define
1222                         //
1223                         if (method.Storey != null && method.Storey.HasHoistedVariables)
1224                                 return true;
1225
1226                         method.ResolveMembers ();
1227                         return method.Define ();
1228                 }
1229
1230                 //
1231                 // Creates a host for the anonymous method
1232                 //
1233                 AnonymousMethodMethod DoCreateMethodHost (EmitContext ec)
1234                 {
1235                         AnonymousMethodStorey storey = FindBestMethodStorey ();
1236                         if (referenced_storeys != null && referenced_storeys.Count > 1) {
1237                                 foreach (AnonymousMethodStorey s in referenced_storeys) {
1238                                         if (s == storey)
1239                                                 continue;
1240
1241                                         storey.AddParentStoreyReference (s);
1242                                         Block.Parent.Explicit.PropagateStoreyReference (s);
1243                                 }
1244                         }
1245
1246                         //
1247                         // Anonymous method body can be converted to
1248                         //
1249                         // 1, an instance method in current scope when only `this' is hoisted
1250                         // 2, a static method in current scope when neither `this' nor any variable is hoisted
1251                         // 3, an instance method in compiler generated storey when any hoisted variable exists
1252                         //
1253
1254                         int modifiers;
1255                         if (storey != null) {
1256                                 modifiers = storey.HasHoistedVariables ? Modifiers.INTERNAL : Modifiers.PRIVATE;
1257                         } else {
1258                                 modifiers = Modifiers.STATIC | Modifiers.PRIVATE;
1259                         }
1260
1261                         DeclSpace parent = (modifiers & Modifiers.PRIVATE) != 0 ? Host : storey;
1262
1263                         MemberCore mc = ec.ResolveContext as MemberCore;
1264                         string name = CompilerGeneratedClass.MakeName (parent != storey ? mc.Name : null,
1265                                 "m", null, unique_id++);
1266
1267                         MemberName member_name;
1268                         GenericMethod generic_method;
1269                         if ((modifiers & Modifiers.PRIVATE) != 0 && mc.MemberName.IsGeneric) {
1270                                 member_name = new MemberName (name, mc.MemberName.TypeArguments.Clone (), Location);
1271
1272                                 generic_method = new GenericMethod (
1273                                         Host.NamespaceEntry, storey, member_name,
1274                                         new TypeExpression (ReturnType, Location), parameters);
1275                                 generic_method.SetParameterInfo (null);
1276                         } else {
1277                                 member_name = new MemberName (name, Location);
1278                                 generic_method = null;
1279                         }
1280
1281                         string real_name = String.Format (
1282                                 "{0}~{1}{2}", mc.GetSignatureForError (), GetSignatureForError (),
1283                                 parameters.GetSignatureForError ());
1284
1285                         return new AnonymousMethodMethod (parent,
1286                                 this, storey, generic_method, new TypeExpression (ReturnType, Location), modifiers,
1287                                 real_name, member_name, parameters);
1288                 }
1289
1290                 public override Expression DoResolve (EmitContext ec)
1291                 {
1292                         if (!Define (ec))
1293                                 return null;
1294
1295                         eclass = ExprClass.Value;
1296                         return this;
1297                 }
1298
1299                 public override void Emit (EmitContext ec)
1300                 {
1301                         //
1302                         // Load method delegate implementation
1303                         //
1304                         if ((method.ModFlags & Modifiers.STATIC) != 0) {
1305                                 ec.ig.Emit (OpCodes.Ldnull);
1306                         } else {
1307                                 Expression e = Storey.GetStoreyInstanceExpression (ec).Resolve (ec);
1308                                 if (e != null)
1309                                         e.Emit (ec);
1310                         }
1311
1312                         MethodInfo delegate_method = method.MethodBuilder;
1313 #if GMCS_SOURCE
1314                         if (Storey != null && Storey.IsGeneric)
1315                                 delegate_method = TypeBuilder.GetMethod (Storey.Instance.Type, delegate_method);
1316 #endif
1317                         ec.ig.Emit (OpCodes.Ldftn, delegate_method);
1318
1319                         ConstructorInfo constructor_method = Delegate.GetConstructor (ec.ContainerType, type);
1320 #if MS_COMPATIBLE
1321             if (type.IsGenericType && type is TypeBuilder)
1322                 constructor_method = TypeBuilder.GetConstructor (type, constructor_method);
1323 #endif
1324                         ec.ig.Emit (OpCodes.Newobj, constructor_method);
1325                 }
1326
1327                 //
1328                 // Look for the best storey for this anonymous method
1329                 //
1330                 AnonymousMethodStorey FindBestMethodStorey ()
1331                 {
1332                         if (referenced_storeys == null) {
1333                                 for (Block b = Block.Parent; b != null; b = b.Parent) {
1334                                         AnonymousMethodStorey s = b.Explicit.AnonymousMethodStorey;
1335                                         if (s != null)
1336                                                 return s;
1337                                 }
1338                                                 
1339                                 return null;
1340                         }
1341
1342                         if (referenced_storeys.Count == 1)
1343                                 return (AnonymousMethodStorey) referenced_storeys [0];
1344
1345                         for (Block b = Block.Parent; b != null; b = b.Parent) {
1346                                 foreach (AnonymousMethodStorey storey in referenced_storeys) {
1347                                         if (storey.OriginalSourceBlock == b)
1348                                                 return storey;
1349                                 }
1350                         }
1351
1352                         return null;
1353                 }
1354
1355                 public override string GetSignatureForError ()
1356                 {
1357                         return TypeManager.CSharpName (type);
1358                 }
1359
1360                 public static void Error_AddressOfCapturedVar (string name, Location loc)
1361                 {
1362                         Report.Error (1686, loc,
1363                                       "Local variable `{0}' or its members cannot have their " +
1364                                       "address taken and be used inside an anonymous method block",
1365                                       name);
1366                 }
1367
1368                 public static void Reset ()
1369                 {
1370                         unique_id = 0;
1371                 }
1372         }
1373
1374         //
1375         // Anonymous type container
1376         //
1377         public class AnonymousTypeClass : CompilerGeneratedClass
1378         {
1379                 static int types_counter;
1380                 public const string ClassNamePrefix = "<>__AnonType";
1381                 public const string SignatureForError = "anonymous type";
1382                 
1383                 readonly ArrayList parameters;
1384
1385                 private AnonymousTypeClass (DeclSpace parent, MemberName name, ArrayList parameters, Location loc)
1386                         : base (parent, name, Modifiers.SEALED, loc)
1387                 {
1388                         this.parameters = parameters;
1389                 }
1390
1391                 public static AnonymousTypeClass Create (TypeContainer parent, ArrayList parameters, Location loc)
1392                 {
1393                         if (RootContext.Version <= LanguageVersion.ISO_2)
1394                                 Report.FeatureIsNotAvailable (loc, "anonymous types");
1395                         
1396                         string name = ClassNamePrefix + types_counter++;
1397
1398                         SimpleName [] t_args = new SimpleName [parameters.Count];
1399                         Parameter [] ctor_params = new Parameter [parameters.Count];
1400                         for (int i = 0; i < parameters.Count; ++i) {
1401                                 AnonymousTypeParameter p = (AnonymousTypeParameter) parameters [i];
1402
1403                                 t_args [i] = new SimpleName ("<" + p.Name + ">__T", p.Location);
1404                                 ctor_params [i] = new Parameter (t_args [i], p.Name, 0, null, p.Location);
1405                         }
1406
1407                         //
1408                         // Create generic anonymous type host with generic arguments
1409                         // named upon properties names
1410                         //
1411                         AnonymousTypeClass a_type = new AnonymousTypeClass (parent.NamespaceEntry.SlaveDeclSpace,
1412                                 new MemberName (name, new TypeArguments (loc, t_args), loc), parameters, loc);
1413
1414                         if (parameters.Count > 0)
1415                                 a_type.SetParameterInfo (null);
1416
1417                         Constructor c = new Constructor (a_type, name, Modifiers.PUBLIC,
1418                                 new Parameters (ctor_params), null, loc);
1419                         c.OptAttributes = a_type.GetDebuggerHiddenAttribute ();
1420                         c.Block = new ToplevelBlock (c.Parameters, loc);
1421
1422                         // 
1423                         // Create fields and contructor body with field initialization
1424                         //
1425                         bool error = false;
1426                         for (int i = 0; i < parameters.Count; ++i) {
1427                                 AnonymousTypeParameter p = (AnonymousTypeParameter) parameters [i];
1428
1429                                 Field f = new Field (a_type, t_args [i], Modifiers.PRIVATE | Modifiers.READONLY,
1430                                         "<" + p.Name + ">", null, p.Location);
1431
1432                                 if (!a_type.AddField (f)) {
1433                                         error = true;
1434                                         Report.Error (833, p.Location, "`{0}': An anonymous type cannot have multiple properties with the same name",
1435                                                 p.Name);
1436                                         continue;
1437                                 }
1438
1439                                 c.Block.AddStatement (new StatementExpression (
1440                                         new SimpleAssign (new MemberAccess (new This (p.Location), f.Name),
1441                                                 c.Block.GetParameterReference (p.Name, p.Location))));
1442
1443                                 ToplevelBlock get_block = new ToplevelBlock (p.Location);
1444                                 get_block.AddStatement (new Return (
1445                                         new MemberAccess (new This (p.Location), f.Name), p.Location));
1446                                 Accessor get_accessor = new Accessor (get_block, 0, null, p.Location);
1447                                 Property prop = new Property (a_type, t_args [i], Modifiers.PUBLIC, false,
1448                                         new MemberName (p.Name, p.Location), null, get_accessor, null, false);
1449                                 a_type.AddProperty (prop);
1450                         }
1451
1452                         if (error)
1453                                 return null;
1454
1455                         a_type.AddConstructor (c);
1456                         return a_type;
1457                 }
1458                 
1459                 public new static void Reset ()
1460                 {
1461                         types_counter = 0;
1462                 }
1463
1464                 protected override bool AddToContainer (MemberCore symbol, string name)
1465                 {
1466                         MemberCore mc = (MemberCore) defined_names [name];
1467
1468                         if (mc == null) {
1469                                 defined_names.Add (name, symbol);
1470                                 return true;
1471                         }
1472
1473                         Report.SymbolRelatedToPreviousError (mc);
1474                         return false;
1475                 }
1476
1477                 void DefineOverrides ()
1478                 {
1479                         Location loc = Location;
1480
1481                         Method equals = new Method (this, null, TypeManager.system_boolean_expr,
1482                                 Modifiers.PUBLIC | Modifiers.OVERRIDE, false, new MemberName ("Equals", loc),
1483                                 new Parameters (new Parameter (TypeManager.system_object_expr, "obj", 0, null, loc)),
1484                                 GetDebuggerHiddenAttribute ());
1485
1486                         Method tostring = new Method (this, null, TypeManager.system_string_expr,
1487                                 Modifiers.PUBLIC | Modifiers.OVERRIDE, false, new MemberName ("ToString", loc),
1488                                 Mono.CSharp.Parameters.EmptyReadOnlyParameters, GetDebuggerHiddenAttribute ());
1489
1490                         ToplevelBlock equals_block = new ToplevelBlock (equals.Parameters, loc);
1491                         TypeExpr current_type;
1492                         if (IsGeneric)
1493                                 current_type = new ConstructedType (TypeBuilder, TypeParameters, loc);
1494                         else
1495                                 current_type = new TypeExpression (TypeBuilder, loc);
1496
1497                         equals_block.AddVariable (current_type, "other", loc);
1498                         LocalVariableReference other_variable = new LocalVariableReference (equals_block, "other", loc);
1499
1500                         MemberAccess system_collections_generic = new MemberAccess (new MemberAccess (
1501                                 new SimpleName ("System", loc), "Collections", loc), "Generic", loc);
1502
1503                         Expression rs_equals = null;
1504                         Expression string_concat = new StringConstant ("<empty type>", loc);
1505                         Expression rs_hashcode = new IntConstant (-2128831035, loc);
1506                         for (int i = 0; i < parameters.Count; ++i) {
1507                                 AnonymousTypeParameter p = (AnonymousTypeParameter) parameters [i];
1508                                 Field f = (Field) Fields [i];
1509
1510                                 MemberAccess equality_comparer = new MemberAccess (new MemberAccess (
1511                                         system_collections_generic, "EqualityComparer",
1512                                                 new TypeArguments (loc, new SimpleName (TypeParameters [i].Name, loc)), loc),
1513                                                 "Default", loc);
1514
1515                                 ArrayList arguments_equal = new ArrayList (2);
1516                                 arguments_equal.Add (new Argument (new MemberAccess (new This (f.Location), f.Name)));
1517                                 arguments_equal.Add (new Argument (new MemberAccess (other_variable, f.Name)));
1518
1519                                 Expression field_equal = new Invocation (new MemberAccess (equality_comparer,
1520                                         "Equals", loc), arguments_equal);
1521
1522                                 ArrayList arguments_hashcode = new ArrayList (1);
1523                                 arguments_hashcode.Add (new Argument (new MemberAccess (new This (f.Location), f.Name)));
1524                                 Expression field_hashcode = new Invocation (new MemberAccess (equality_comparer,
1525                                         "GetHashCode", loc), arguments_hashcode);
1526
1527                                 IntConstant FNV_prime = new IntConstant (16777619, loc);                                
1528                                 rs_hashcode = new Binary (Binary.Operator.Multiply,
1529                                         new Binary (Binary.Operator.ExclusiveOr, rs_hashcode, field_hashcode),
1530                                         FNV_prime);
1531
1532                                 Expression field_to_string = new Conditional (new Binary (Binary.Operator.Inequality,
1533                                         new MemberAccess (new This (f.Location), f.Name), new NullLiteral (loc)),
1534                                         new Invocation (new MemberAccess (
1535                                                 new MemberAccess (new This (f.Location), f.Name), "ToString"), null),
1536                                         new StringConstant ("<null>", loc));
1537
1538                                 if (rs_equals == null) {
1539                                         rs_equals = field_equal;
1540                                         string_concat = new Binary (Binary.Operator.Addition,
1541                                                 new StringConstant (p.Name + " = ", loc),
1542                                                 field_to_string);
1543                                         continue;
1544                                 }
1545
1546                                 //
1547                                 // Implementation of ToString () body using string concatenation
1548                                 //                              
1549                                 string_concat = new Binary (Binary.Operator.Addition,
1550                                         new Binary (Binary.Operator.Addition,
1551                                                 string_concat,
1552                                                 new StringConstant (", " + p.Name + " = ", loc)),
1553                                         field_to_string);
1554
1555                                 rs_equals = new Binary (Binary.Operator.LogicalAnd, rs_equals, field_equal);
1556                         }
1557
1558                         //
1559                         // Equals (object obj) override
1560                         //
1561                         equals_block.AddStatement (new StatementExpression (
1562                                 new SimpleAssign (other_variable,
1563                                         new As (equals_block.GetParameterReference ("obj", loc),
1564                                                 current_type, loc), loc)));
1565
1566                         Expression equals_test = new Binary (Binary.Operator.Inequality, other_variable, new NullLiteral (loc));
1567                         if (rs_equals != null)
1568                                 equals_test = new Binary (Binary.Operator.LogicalAnd, equals_test, rs_equals);
1569                         equals_block.AddStatement (new Return (equals_test, loc));
1570
1571                         equals.Block = equals_block;
1572                         equals.ResolveMembers ();
1573                         AddMethod (equals);
1574
1575                         //
1576                         // GetHashCode () override
1577                         //
1578                         Method hashcode = new Method (this, null, TypeManager.system_int32_expr,
1579                                 Modifiers.PUBLIC | Modifiers.OVERRIDE, false, new MemberName ("GetHashCode", loc),
1580                                 Mono.CSharp.Parameters.EmptyReadOnlyParameters, GetDebuggerHiddenAttribute ());
1581
1582                         //
1583                         // Modified FNV with good avalanche behavior and uniform
1584                         // distribution with larger hash sizes.
1585                         //
1586                         // const int FNV_prime = 16777619;
1587                         // int hash = (int) 2166136261;
1588                         // foreach (int d in data)
1589                         //     hash = (hash ^ d) * FNV_prime;
1590                         // hash += hash << 13;
1591                         // hash ^= hash >> 7;
1592                         // hash += hash << 3;
1593                         // hash ^= hash >> 17;
1594                         // hash += hash << 5;
1595
1596                         ToplevelBlock hashcode_block = new ToplevelBlock (loc);
1597                         hashcode_block.AddVariable (TypeManager.system_int32_expr, "hash", loc);
1598                         LocalVariableReference hash_variable = new LocalVariableReference (hashcode_block, "hash", loc);
1599                         hashcode_block.AddStatement (new StatementExpression (
1600                                 new SimpleAssign (hash_variable, rs_hashcode)));
1601
1602                         hashcode_block.AddStatement (new StatementExpression (
1603                                 new CompoundAssign (Binary.Operator.Addition, hash_variable,
1604                                         new Binary (Binary.Operator.LeftShift, hash_variable, new IntConstant (13, loc)))));
1605                         hashcode_block.AddStatement (new StatementExpression (
1606                                 new CompoundAssign (Binary.Operator.ExclusiveOr, hash_variable,
1607                                         new Binary (Binary.Operator.RightShift, hash_variable, new IntConstant (7, loc)))));
1608                         hashcode_block.AddStatement (new StatementExpression (
1609                                 new CompoundAssign (Binary.Operator.Addition, hash_variable,
1610                                         new Binary (Binary.Operator.LeftShift, hash_variable, new IntConstant (3, loc)))));
1611                         hashcode_block.AddStatement (new StatementExpression (
1612                                 new CompoundAssign (Binary.Operator.ExclusiveOr, hash_variable,
1613                                         new Binary (Binary.Operator.RightShift, hash_variable, new IntConstant (17, loc)))));
1614                         hashcode_block.AddStatement (new StatementExpression (
1615                                 new CompoundAssign (Binary.Operator.Addition, hash_variable,
1616                                         new Binary (Binary.Operator.LeftShift, hash_variable, new IntConstant (5, loc)))));
1617
1618                         hashcode_block.AddStatement (new Return (hash_variable, loc));
1619                         hashcode.Block = hashcode_block;
1620                         hashcode.ResolveMembers ();
1621                         AddMethod (hashcode);
1622
1623                         //
1624                         // ToString () override
1625                         //
1626
1627                         ToplevelBlock tostring_block = new ToplevelBlock (loc);
1628                         tostring_block.AddStatement (new Return (string_concat, loc));
1629                         tostring.Block = tostring_block;
1630                         tostring.ResolveMembers ();
1631                         AddMethod (tostring);
1632                 }
1633
1634                 public override bool DefineMembers ()
1635                 {
1636                         DefineOverrides ();
1637
1638                         return base.DefineMembers ();
1639                 }
1640
1641                 Attributes GetDebuggerHiddenAttribute ()
1642                 {
1643                         return new Attributes (new Attribute (null, null,
1644                                 "System.Diagnostics.DebuggerHiddenAttribute", null, Location, false));
1645                 }
1646
1647                 public override string GetSignatureForError ()
1648                 {
1649                         return SignatureForError;
1650                 }
1651
1652                 public ArrayList Parameters {
1653                         get {
1654                                 return parameters;
1655                         }
1656                 }
1657         }
1658 }