svn path=/branches/mono-1-1-9/mcs/; revision=51206
[mono.git] / mcs / gmcs / iterators.cs
1 //
2 // iterators.cs: Support for implementing iterators
3 //
4 // Author:
5 //   Miguel de Icaza (miguel@ximian.com)
6 //
7 // (C) 2003 Ximian, Inc.
8 //
9 // TODO:
10 //    Flow analysis for Yield.
11 //    Emit calls to base object constructor.
12 //
13 // Generics note:
14 //    Current should be defined to return T, and IEnumerator.Current returns object
15 //
16
17 using System;
18 using System.Collections;
19 using System.Reflection;
20 using System.Reflection.Emit;
21
22 namespace Mono.CSharp {
23
24         public interface IIteratorContainer {
25
26                 //
27                 // Invoked if a yield statement is found in the body
28                 //
29                 void SetYields ();
30         }
31         
32         public class Yield : Statement {
33                 Expression expr;
34                 ArrayList finally_blocks;
35
36                 public Yield (Expression expr, Location l)
37                 {
38                         this.expr = expr;
39                         loc = l;
40                 }
41
42                 public static bool CheckContext (EmitContext ec, Location loc)
43                 {
44                         if (ec.InFinally) {
45                                 Report.Error (1625, loc, "Cannot yield in the body of a " +
46                                               "finally clause");
47                                 return false;
48                         } 
49                         
50                         if (ec.InUnsafe) {
51                                 Report.Error (1629, loc, "Unsafe code may not appear in iterators");
52                                 return false;
53                         }
54                         if (ec.InCatch){
55                                 Report.Error (1631, loc, "Cannot yield a value in the body of a catch clause");
56                                 return false;
57                         }
58
59                         AnonymousContainer am = ec.CurrentAnonymousMethod;
60                         if ((am != null) && !am.IsIterator){
61                                 Report.Error (1621, loc, "The yield statement cannot be used inside anonymous method blocks");
62                                 return false;
63                         }
64
65                         if (ec.CurrentBranching.InTryWithCatch ()) {
66                                 Report.Error (1626, loc, "Cannot yield a value in the body of a " +
67                                         "try block with a catch clause");
68                                 return false;
69                         }
70                         return true;
71                 }
72                 
73                 public override bool Resolve (EmitContext ec)
74                 {
75                         expr = expr.Resolve (ec);
76                         if (expr == null)
77                                 return false;
78
79                         if (!CheckContext (ec, loc))
80                                 return false;
81
82                         Iterator iterator = ec.CurrentIterator;
83
84                         if (expr.Type != iterator.IteratorType){
85                                 expr = Convert.ImplicitConversionRequired (
86                                         ec, expr, iterator.IteratorType, loc);
87                                 if (expr == null)
88                                         return false;
89                         }
90
91                         ec.CurrentBranching.StealFinallyClauses (ref finally_blocks);
92                         return true;
93                 }
94
95                 protected override void DoEmit (EmitContext ec)
96                 {
97                         ec.CurrentIterator.MarkYield (ec, expr, finally_blocks);
98                 }
99         }
100
101         public class YieldBreak : Statement {
102
103                 public YieldBreak (Location l)
104                 {
105                         loc = l;
106                 }
107
108                 public override bool Resolve (EmitContext ec)
109                 {
110                         if (!Yield.CheckContext (ec, loc))
111                                 return false;
112
113                         ec.CurrentBranching.CurrentUsageVector.Goto ();
114                         return true;
115                 }
116
117                 protected override void DoEmit (EmitContext ec)
118                 {
119                         ec.CurrentIterator.EmitYieldBreak (ec.ig);
120                 }
121         }
122
123         public class Iterator : Class {
124                 protected ToplevelBlock original_block;
125                 protected ToplevelBlock block;
126
127                 Type original_iterator_type;
128                 TypeExpr iterator_type_expr;
129                 bool is_enumerable;
130                 public readonly bool IsStatic;
131
132                 //
133                 // The state as we generate the iterator
134                 //
135                 Label move_next_ok, move_next_error;
136                 ArrayList resume_points = new ArrayList ();
137                 int pc;
138                 
139                 //
140                 // Context from the original method
141                 //
142                 GenericMethod generic_method;
143                 TypeContainer container;
144                 TypeExpr current_type;
145                 Type this_type;
146                 InternalParameters parameters;
147                 InternalParameters original_parameters;
148                 IMethodData orig_method;
149
150                 MethodInfo dispose_method;
151                 MoveNextMethod move_next_method;
152                 Constructor ctor;
153                 CaptureContext cc;
154
155                 Expression enumerator_type;
156                 Expression enumerable_type;
157                 Expression generic_enumerator_type;
158                 Expression generic_enumerable_type;
159                 TypeArguments generic_args;
160
161                 protected enum State {
162                         Uninitialized   = -2,
163                         After,
164                         Running
165                 }
166
167                 static int proxy_count;
168
169                 public void EmitYieldBreak (ILGenerator ig)
170                 {
171                         ig.Emit (OpCodes.Ldarg_0);
172                         IntConstant.EmitInt (ig, (int) State.After);
173                         ig.Emit (OpCodes.Stfld, pc_field.FieldBuilder);
174                         ig.Emit (OpCodes.Br, move_next_error);
175                 }
176
177                 public void EmitMoveNext (EmitContext ec)
178                 {
179                         ILGenerator ig = ec.ig;
180
181                         move_next_ok = ig.DefineLabel ();
182                         move_next_error = ig.DefineLabel ();
183
184                         LocalBuilder retval = ec.GetTemporaryLocal (TypeManager.int32_type);
185
186                         ig.BeginExceptionBlock ();
187
188                         Label dispatcher = ig.DefineLabel ();
189                         ig.Emit (OpCodes.Br, dispatcher);
190
191                         ResumePoint entry_point = new ResumePoint (null);
192                         resume_points.Add (entry_point);
193                         entry_point.Define (ig);
194
195                         ec.EmitTopBlock (orig_method, original_block, parameters);
196
197                         EmitYieldBreak (ig);
198
199                         ig.MarkLabel (dispatcher);
200
201                         Label [] labels = new Label [resume_points.Count];
202                         for (int i = 0; i < labels.Length; i++)
203                                 labels [i] = ((ResumePoint) resume_points [i]).Label;
204
205                         ig.Emit (OpCodes.Ldarg_0);
206                         ig.Emit (OpCodes.Ldfld, pc_field.FieldBuilder);
207                         ig.Emit (OpCodes.Switch, labels);
208
209                         Label end = ig.DefineLabel ();
210
211                         ig.MarkLabel (move_next_error);
212                         ig.Emit (OpCodes.Ldc_I4_0); 
213                         ig.Emit (OpCodes.Stloc, retval);
214                         ig.Emit (OpCodes.Leave, end);
215
216                         ig.MarkLabel (move_next_ok);
217                         ig.Emit (OpCodes.Ldc_I4_1);
218                         ig.Emit (OpCodes.Stloc, retval);
219                         ig.Emit (OpCodes.Leave, end);
220
221                         ig.BeginFaultBlock ();
222
223                         ig.Emit (OpCodes.Ldarg_0);
224                         ig.Emit (OpCodes.Callvirt, dispose_method);
225
226                         ig.EndExceptionBlock ();
227
228                         ig.MarkLabel (end);
229                         ig.Emit (OpCodes.Ldloc, retval);
230                         ig.Emit (OpCodes.Ret);
231                 }
232
233                 public void EmitDispose (EmitContext ec)
234                 {
235                         ILGenerator ig = ec.ig;
236
237                         Label end = ig.DefineLabel ();
238                         Label dispatcher = ig.DefineLabel ();
239                         ig.Emit (OpCodes.Br, dispatcher);
240
241                         Label [] labels = new Label [resume_points.Count];
242                         for (int i = 0; i < labels.Length; i++) {
243                                 ResumePoint point = (ResumePoint) resume_points [i];
244
245                                 if (point.FinallyBlocks == null) {
246                                         labels [i] = end;
247                                         continue;
248                                 }
249
250                                 labels [i] = ig.DefineLabel ();
251                                 ig.MarkLabel (labels [i]);
252
253                                 ig.BeginExceptionBlock ();
254                                 ig.BeginFinallyBlock ();
255
256                                 foreach (ExceptionStatement stmt in point.FinallyBlocks) {
257                                         if (stmt != null)
258                                                 stmt.EmitFinally (ec);
259                                 }
260
261                                 ig.EndExceptionBlock ();
262                                 ig.Emit (OpCodes.Br, end);
263                         }
264
265                         ig.MarkLabel (dispatcher);
266                         ig.Emit (OpCodes.Ldarg_0);
267                         ig.Emit (OpCodes.Ldfld, pc_field.FieldBuilder);
268                         ig.Emit (OpCodes.Switch, labels);
269
270                         ig.Emit (OpCodes.Ldarg_0);
271                         IntConstant.EmitInt (ig, (int) State.After);
272                         ig.Emit (OpCodes.Stfld, pc_field.FieldBuilder);
273
274                         ig.MarkLabel (end);
275                 }
276
277                 protected class ResumePoint
278                 {
279                         public Label Label;
280                         public readonly ExceptionStatement[] FinallyBlocks;
281
282                         public ResumePoint (ArrayList list)
283                         {
284                                 if (list != null) {
285                                         FinallyBlocks = new ExceptionStatement [list.Count];
286                                         list.CopyTo (FinallyBlocks, 0);
287                                 }
288                         }
289
290                         public void Define (ILGenerator ig)
291                         {
292                                 Label = ig.DefineLabel ();
293                                 ig.MarkLabel (Label);
294                         }
295                 }
296
297                 //
298                 // Called back from Yield
299                 //
300                 public void MarkYield (EmitContext ec, Expression expr,
301                                        ArrayList finally_blocks)
302                 {
303                         ILGenerator ig = ec.ig;
304
305                         // Store the new current
306                         ig.Emit (OpCodes.Ldarg_0);
307                         expr.Emit (ec);
308                         ig.Emit (OpCodes.Stfld, current_field.FieldBuilder);
309
310                         // increment pc
311                         pc++;
312                         ig.Emit (OpCodes.Ldarg_0);
313                         IntConstant.EmitInt (ig, pc);
314                         ig.Emit (OpCodes.Stfld, pc_field.FieldBuilder);
315
316                         // Return ok
317                         ig.Emit (OpCodes.Br, move_next_ok);
318
319                         ResumePoint point = new ResumePoint (finally_blocks);
320                         resume_points.Add (point);
321                         point.Define (ig);
322                 }
323
324                 public void MarkFinally (EmitContext ec, ArrayList finally_blocks)
325                 {
326                         ILGenerator ig = ec.ig;
327
328                         // increment pc
329                         pc++;
330                         ig.Emit (OpCodes.Ldarg_0);
331                         IntConstant.EmitInt (ig, pc);
332                         ig.Emit (OpCodes.Stfld, pc_field.FieldBuilder);
333
334                         ResumePoint point = new ResumePoint (finally_blocks);
335                         resume_points.Add (point);
336                         point.Define (ig);
337                 }
338
339                 private static MemberName MakeProxyName (string name, GenericMethod generic, Location loc)
340                 {
341                         int pos = name.LastIndexOf ('.');
342                         if (pos > 0)
343                                 name = name.Substring (pos + 1);
344
345                         string proxy_name = "<" + name + ">__" + (proxy_count++);
346
347                         if (generic != null) {
348                                 TypeArguments args = new TypeArguments (loc);
349                                 foreach (TypeParameter tparam in generic.CurrentTypeParameters)
350                                         args.Add (new SimpleName (tparam.Name, loc));
351                                 return new MemberName (proxy_name, args, loc);
352                         } else
353                                 return new MemberName (proxy_name, loc);
354                 }
355
356                 //
357                 // Our constructor
358                 //
359                 public Iterator (IMethodData m_container, TypeContainer container, GenericMethod generic,
360                                  InternalParameters parameters, int modifiers)
361                         : base (container.NamespaceEntry, container,
362                                 MakeProxyName (m_container.MethodName.Name, generic, m_container.Location),
363                                 (modifiers & Modifiers.UNSAFE) | Modifiers.PRIVATE, null)
364                 {
365                         this.orig_method = m_container;
366
367                         this.generic_method = generic;
368                         this.container = container;
369                         this.original_parameters = parameters;
370                         this.original_block = orig_method.Block;
371                         this.block = new ToplevelBlock (orig_method.Block, parameters.Parameters, orig_method.Location);
372
373                         if (generic != null) {
374                                 ArrayList constraints = new ArrayList ();
375                                 foreach (TypeParameter tparam in generic.TypeParameters)
376                                         constraints.Add (tparam.Constraints);
377
378                                 SetParameterInfo (constraints);
379                         }
380
381                         IsStatic = (modifiers & Modifiers.STATIC) != 0;
382                 }
383
384                 public AnonymousContainer Host {
385                         get { return move_next_method; }
386                 }
387
388                 public bool DefineIterator ()
389                 {
390                         ec = new EmitContext (this, Location, null, null, ModFlags);
391                         ec.CurrentAnonymousMethod = move_next_method;
392                         ec.InIterator = true;
393
394                         if (!CheckType ()) {
395                                 Report.Error (1624, Location,
396                                         "The body of `{0}' cannot be an iterator block because `{1}' is not an iterator interface type",
397                                         orig_method.GetSignatureForError (), TypeManager.CSharpName (orig_method.ReturnType));
398                                 return false;
399                         }
400
401                         for (int i = 0; i < original_parameters.Count; i++){
402                                 Parameter.Modifier mod = original_parameters.ParameterModifier (i);
403                                 if ((mod & (Parameter.Modifier.REF | Parameter.Modifier.OUT)) != 0){
404                                         Report.Error (
405                                                 1623, Location,
406                                                 "Iterators cannot have ref or out parameters");
407                                         return false;
408                                 }
409
410                                 if ((mod & Parameter.Modifier.ARGLIST) != 0) {
411                                         Report.Error (1636, Location, "__arglist is not allowed in parameter list of iterators");
412                                         return false;
413                                 }
414
415                                 if (original_parameters.ParameterType (i).IsPointer) {
416                                         Report.Error (1637, Location, "Iterators cannot have unsafe parameters or yield types");
417                                         return false;
418                                 }
419                         }
420
421                         if (container.CurrentType != null)
422                                 this_type = container.CurrentType;
423                         else
424                                 this_type = container.TypeBuilder;
425
426                         container.AddIterator (this);
427
428                         orig_method.Block = block;
429                         return true;
430                 }
431
432                 MethodInfo FetchMethodDispose ()
433                 {
434                         MemberList dispose_list;
435
436                         dispose_list = FindMembers (
437                                 current_type.Type,
438                                 MemberTypes.Method, BindingFlags.Public | BindingFlags.Instance,
439                                 Type.FilterName, "Dispose");
440
441                         if (dispose_list.Count != 1)
442                                 throw new InternalErrorException ("Cannot find Dipose() method.");
443
444                         return (MethodInfo) dispose_list [0];
445                 }
446
447                 protected override bool DoDefineMembers ()
448                 {
449                         ec.InIterator = true;
450                         ec.CurrentAnonymousMethod = move_next_method;
451                         ec.capture_context = cc;
452
453                         if (!base.DoDefineMembers ())
454                                 return false;
455
456                         dispose_method = FetchMethodDispose ();
457                         if (dispose_method == null)
458                                 return false;
459
460                         return true;
461                 }
462
463                 public override bool Define ()
464                 {
465                         if (!base.Define ())
466                                 return false;
467
468                         ec.InIterator = true;
469                         ec.CurrentAnonymousMethod = move_next_method;
470                         ec.capture_context = cc;
471
472                         ec.TypeContainer = ec.TypeContainer.Parent;
473
474                         if (ec.TypeContainer.CurrentType != null)
475                                 ec.ContainerType = ec.TypeContainer.CurrentType;
476                         else
477                                 ec.ContainerType = ec.TypeContainer.TypeBuilder;
478
479                         ec.ig = move_next_method.method.MethodBuilder.GetILGenerator ();
480
481                         if (!ctor.Define ())
482                                 return false;
483
484                         bool unreachable;
485
486                         if (!ec.ResolveTopBlock (null, original_block, parameters, orig_method, out unreachable))
487                                 return false;
488
489                         if (!ec.ResolveTopBlock (null, block, parameters, orig_method, out unreachable))
490                                 return false;
491
492                         original_block.CompleteContexts ();
493
494                         cc.EmitAnonymousHelperClasses (ec);
495
496                         return true;
497                 }
498
499                 TypeExpr InflateType (Type it)
500                 {
501                         if (generic_method == null)
502                                 return new TypeExpression (it, Location);
503
504                         if (it.IsGenericParameter && (it.DeclaringMethod != null)) {
505                                 int pos = it.GenericParameterPosition;
506                                 it = CurrentTypeParameters [pos].Type;
507                         } else if (it.IsGenericInstance) {
508                                 Type[] args = it.GetGenericArguments ();
509
510                                 TypeArguments inflated = new TypeArguments (Location);
511                                 foreach (Type t in args)
512                                         inflated.Add (InflateType (t));
513
514                                 return new ConstructedType (it, inflated, Location);
515                         } else if (it.IsArray) {
516                                 TypeExpr et_expr = InflateType (it.GetElementType ());
517                                 int rank = it.GetArrayRank ();
518
519                                 Type et = et_expr.ResolveAsTypeTerminal (ec).Type;
520                                 it = et.MakeArrayType (rank);
521                         }
522
523                         return new TypeExpression (it, Location);
524                 }
525
526                 Parameter InflateParameter (Parameter param)
527                 {
528                         TypeExpr te = InflateType (param.ParameterType);
529                         return new Parameter (
530                                 te, param.Name, param.ModFlags, param.OptAttributes, param.Location);
531                 }
532
533                 InternalParameters InflateParameters (Parameters parameters, EmitContext ec)
534                 {
535                         Parameter[] fixed_params = null;
536                         if (parameters.FixedParameters != null) {
537                                 fixed_params = new Parameter [parameters.FixedParameters.Length];
538                                 for (int i = 0; i < fixed_params.Length; i++)
539                                         fixed_params [i] = InflateParameter (parameters.FixedParameters [i]);
540                         }
541
542                         Parameters new_params;
543                         if (parameters.ArrayParameter != null) {
544                                 Parameter array_param = InflateParameter (parameters.ArrayParameter);
545                                 new_params = new Parameters (fixed_params, array_param);
546                         } else
547                                 new_params = new Parameters (fixed_params, parameters.HasArglist);
548
549                         Type [] types = new_params.GetParameterInfo (ec);
550                         return new InternalParameters (types, new_params);
551                 }
552
553                 protected override TypeExpr [] GetClassBases (out TypeExpr base_class)
554                 {
555                         iterator_type_expr = InflateType (original_iterator_type);
556
557                         generic_args = new TypeArguments (Location);
558                         generic_args.Add (iterator_type_expr);
559
560                         ArrayList list = new ArrayList ();
561                         if (is_enumerable) {
562                                 enumerable_type = new TypeExpression (
563                                         TypeManager.ienumerable_type, Location);
564                                 list.Add (enumerable_type);
565
566                                 generic_enumerable_type = new ConstructedType (
567                                         TypeManager.generic_ienumerable_type,
568                                         generic_args, Location);
569                                 list.Add (generic_enumerable_type);
570                         }
571
572                         enumerator_type = new TypeExpression (
573                                 TypeManager.ienumerator_type, Location);
574                         list.Add (enumerator_type);
575
576                         list.Add (new TypeExpression (TypeManager.idisposable_type, Location));
577
578                         generic_enumerator_type = new ConstructedType (
579                                 TypeManager.generic_ienumerator_type,
580                                 generic_args, Location);
581                         list.Add (generic_enumerator_type);
582
583                         Bases = list;
584
585                         return base.GetClassBases (out base_class);
586                 }
587
588                 //
589                 // Returns the new block for the method, or null on failure
590                 //
591                 protected override bool DefineNestedTypes ()
592                 {
593                         if (CurrentType != null)
594                                 current_type = new TypeExpression (CurrentType, Location);
595                         else
596                                 current_type = new TypeExpression (TypeBuilder, Location);
597
598                         parameters = InflateParameters (original_parameters.Parameters, ec);
599
600                         Define_Fields ();
601                         Define_Current (false);
602                         Define_Current (true);
603                         Define_MoveNext ();
604                         Define_Reset ();
605                         Define_Dispose ();
606
607                         Define_Constructor ();
608
609                         Create_Block ();
610
611                         if (is_enumerable) {
612                                 Define_GetEnumerator (false);
613                                 Define_GetEnumerator (true);
614                         }
615
616                         return base.DefineNestedTypes ();
617                 }
618
619                 Field pc_field;
620                 Field current_field;
621                 Method dispose;
622
623                 void Create_Block ()
624                 {
625                         original_block.SetHaveAnonymousMethods (Location, move_next_method);
626                         block.SetHaveAnonymousMethods (Location, move_next_method);
627
628                         cc = original_block.CaptureContext;
629
630                         int first = IsStatic ? 0 : 1;
631
632                         ArrayList args = new ArrayList ();
633                         if (!IsStatic) {
634                                 Type t = this_type;
635                                 args.Add (new Argument (
636                                         new ThisParameterReference (t, Location)));
637                                 cc.CaptureThis (move_next_method);
638                         }
639
640                         args.Add (new Argument (new BoolLiteral (false)));
641
642                         for (int i = 0; i < parameters.Count; i++) {
643                                 Type t = original_parameters.ParameterType (i);
644                                 Type inflated = parameters.ParameterType (i);
645                                 string name = parameters.ParameterName (i);
646
647                                 args.Add (new Argument (
648                                         new SimpleParameterReference (t, first + i, Location)));
649
650                                 cc.AddParameterToContext (move_next_method, name, inflated, first + i);
651                         }
652
653                         TypeExpr proxy_type;
654                         if (generic_method != null) {
655                                 TypeArguments new_args = new TypeArguments (Location);
656                                 if (Parent.IsGeneric) {
657                                         foreach (TypeParameter tparam in Parent.TypeParameters)
658                                                 new_args.Add (new TypeParameterExpr (tparam, Location));
659                                 }
660                                 foreach (TypeParameter tparam in generic_method.TypeParameters)
661                                         new_args.Add (new TypeParameterExpr (tparam, Location));
662                                 ConstructedType ct = new ConstructedType (CurrentType, new_args, Location);
663                                 proxy_type = ct.ResolveAsTypeTerminal (ec);
664                         } else
665                                 proxy_type = current_type;
666
667                         Expression new_expr = new New (proxy_type, args, Location);
668                         block.AddStatement (new NoCheckReturn (new_expr, Location));
669                 }
670
671                 void Define_Fields ()
672                 {
673                         pc_field = new Field (
674                                 this, TypeManager.system_int32_expr, Modifiers.PRIVATE, "$PC",
675                                 null, null, Location);
676                         AddField (pc_field);
677
678                         current_field = new Field (
679                                 this, iterator_type_expr, Modifiers.PRIVATE, "$current",
680                                 null, null, Location);
681                         AddField (current_field);
682                 }
683
684                 void Define_Constructor ()
685                 {
686                         Parameters ctor_params;
687
688                         ArrayList list = new ArrayList ();
689
690                         if (!IsStatic)
691                                 list.Add (new Parameter (
692                                         new TypeExpression (this_type, Location),
693                                         "this", Parameter.Modifier.NONE,
694                                         null, Location));
695                         list.Add (new Parameter (
696                                 TypeManager.system_boolean_expr, "initialized",
697                                 Parameter.Modifier.NONE, null, Location));
698
699                         Parameter[] old_fixed = parameters.Parameters.FixedParameters;
700                         if (old_fixed != null)
701                                 list.AddRange (old_fixed);
702
703                         Parameter[] fixed_params = new Parameter [list.Count];
704                         list.CopyTo (fixed_params);
705
706                         ctor_params = new Parameters (fixed_params, parameters.Parameters.ArrayParameter);
707
708                         ctor = new Constructor (
709                                 this, MemberName.Name, Modifiers.PUBLIC, ctor_params,
710                                 new ConstructorBaseInitializer (null, Location),
711                                 Location);
712                         AddConstructor (ctor);
713
714                         ctor.Block = new ToplevelBlock (block, parameters.Parameters, Location);
715
716                         int first = IsStatic ? 2 : 3;
717
718                         State initial = is_enumerable ? State.Uninitialized : State.Running;
719                         ctor.Block.AddStatement (new SetState (this, initial, Location));
720
721                         ctor.Block.AddStatement (new If (
722                                 new SimpleParameterReference (
723                                         TypeManager.bool_type, first - 1, Location),
724                                 new SetState (this, State.Running, Location),
725                                 Location));
726
727                         ctor.Block.AddStatement (new InitScope (this, Location));
728                 }
729
730                 Statement Create_ThrowInvalidOperation ()
731                 {
732                         TypeExpr ex_type = new TypeExpression (
733                                 TypeManager.invalid_operation_exception_type, Location);
734
735                         return new Throw (new New (ex_type, null, Location), Location);
736                 }
737
738                 Statement Create_ThrowNotSupported ()
739                 {
740                         TypeExpr ex_type = new TypeExpression (
741                                 TypeManager.not_supported_exception_type, Location);
742
743                         return new Throw (new New (ex_type, null, Location), Location);
744                 }
745
746                 void Define_Current (bool is_generic)
747                 {
748                         MemberName left;
749                         Expression type;
750                         if (is_generic) {
751                                 left = new MemberName (
752                                         "System.Collections.Generic.IEnumerator",
753                                         generic_args, Location);
754                                 type = iterator_type_expr;
755                         } else {
756                                 left = new MemberName ("System.Collections.IEnumerator", Location);
757                                 type = TypeManager.system_object_expr;
758                         }
759
760                         MemberName name = new MemberName (left, "Current", null, Location);
761
762                         ToplevelBlock get_block = new ToplevelBlock (
763                                 block, parameters.Parameters, Location);
764
765                         get_block.AddStatement (new If (
766                                 new Binary (
767                                         Binary.Operator.LessThanOrEqual,
768                                         new FieldExpression (this, pc_field),
769                                         new IntLiteral ((int) State.Running)),
770                                 Create_ThrowInvalidOperation (),
771                                 new Return (
772                                         new FieldExpression (this, current_field), Location),
773                                 Location));
774
775                         Accessor getter = new Accessor (get_block, 0, null, Location);
776
777                         Property current = new Property (
778                                 this, type, 0, false, name, null, getter, null);
779                         AddProperty (current);
780                 }
781
782                 void Define_MoveNext ()
783                 {
784                         move_next_method = new MoveNextMethod (this, Location);
785
786                         original_block.ReParent (block, move_next_method);
787
788                         move_next_method.CreateMethod (ec);
789
790                         AddMethod (move_next_method.method);
791                 }
792
793                 void Define_GetEnumerator (bool is_generic)
794                 {
795                         MemberName left;
796                         Expression type;
797                         if (is_generic) {
798                                 left = new MemberName (
799                                         "System.Collections.Generic.IEnumerable",
800                                         generic_args, Location);
801                                 type = generic_enumerator_type;
802                         } else {
803                                 left = new MemberName ("System.Collections.IEnumerable", Location);
804                                 type = enumerator_type;
805                         }
806
807                         MemberName name = new MemberName (left, "GetEnumerator", Location);
808
809                         Method get_enumerator = new Method (
810                                 this, null, type, 0, false, name,
811                                 Parameters.EmptyReadOnlyParameters, null);
812                         AddMethod (get_enumerator);
813
814                         get_enumerator.Block = new ToplevelBlock (
815                                 block, parameters.Parameters, Location);
816
817                         get_enumerator.Block.SetHaveAnonymousMethods (Location, move_next_method);
818
819                         Expression ce = new MemberAccess (
820                                 new SimpleName ("System.Threading.Interlocked", Location),
821                                 "CompareExchange", Location);
822
823                         Expression pc = new FieldExpression (this, pc_field);
824                         Expression before = new IntLiteral ((int) State.Running);
825                         Expression uninitialized = new IntLiteral ((int) State.Uninitialized);
826
827                         ArrayList args = new ArrayList ();
828                         args.Add (new Argument (pc, Argument.AType.Ref));
829                         args.Add (new Argument (before, Argument.AType.Expression));
830                         args.Add (new Argument (uninitialized, Argument.AType.Expression));
831
832                         get_enumerator.Block.AddStatement (new If (
833                                 new Binary (
834                                         Binary.Operator.Equality,
835                                         new Invocation (ce, args),
836                                         uninitialized),
837                                 new Return (new ThisParameterReference (type.Type, Location),
838                                             Location),
839                                 Location));
840
841                         args = new ArrayList ();
842                         if (!IsStatic) {
843                                 args.Add (new Argument (new CapturedThisReference (this, Location)));
844                         }
845
846                         args.Add (new Argument (new BoolLiteral (true)));
847
848                         for (int i = 0; i < parameters.Count; i++) {
849                                 Expression cp = new CapturedParameterReference (
850                                         this, parameters.ParameterType (i),
851                                         parameters.ParameterName (i), Location);
852                                 args.Add (new Argument (cp));
853                         }
854
855                         Expression new_expr = new New (current_type, args, Location);
856                         get_enumerator.Block.AddStatement (new Return (new_expr, Location));
857                 }
858
859                 protected class SimpleParameterReference : Expression
860                 {
861                         int idx;
862
863                         public SimpleParameterReference (Type type, int idx, Location loc)
864                         {
865                                 this.idx = idx;
866                                 this.loc = loc;
867                                 this.type = type;
868                                 eclass = ExprClass.Variable;
869                         }
870
871                         public override Expression DoResolve (EmitContext ec)
872                         {
873                                 return this;
874                         }
875
876                         public override void Emit (EmitContext ec)
877                         {
878                                 DoEmit (ec);
879                         }
880
881                         protected virtual void DoEmit (EmitContext ec)
882                         {
883                                 ParameterReference.EmitLdArg (ec.ig, idx);
884                         }
885                 }
886
887                 protected class ThisParameterReference : SimpleParameterReference, IMemoryLocation
888                 {
889                         public ThisParameterReference (Type type, Location loc)
890                                 : base (type, 0, loc)
891                         { }
892
893                         protected override void DoEmit (EmitContext ec)
894                         {
895                                 base.DoEmit (ec);
896                                 if (ec.TypeContainer is Struct)
897                                         ec.ig.Emit (OpCodes.Ldobj, type);
898                         }
899
900                         public void AddressOf (EmitContext ec, AddressOp mode)
901                         {
902                                 if (ec.TypeContainer is Struct)
903                                         ec.ig.Emit (OpCodes.Ldarga, 0);
904                                 else
905                                         ec.ig.Emit (OpCodes.Ldarg, 0);
906                         }
907                 }
908
909                 protected class CapturedParameterReference : Expression
910                 {
911                         Iterator iterator;
912                         string name;
913
914                         public CapturedParameterReference (Iterator iterator, Type type,
915                                                            string name, Location loc)
916                         {
917                                 this.iterator = iterator;
918                                 this.loc = loc;
919                                 this.type = type;
920                                 this.name = name;
921                                 eclass = ExprClass.Variable;
922                         }
923
924                         public override Expression DoResolve (EmitContext ec)
925                         {
926                                 return this;
927                         }
928
929                         public override void Emit (EmitContext ec)
930                         {
931                                 ec.CurrentAnonymousMethod = iterator.move_next_method;
932
933                                 iterator.cc.EmitParameter (ec, name);
934                         }
935                 }
936
937                 protected class CapturedThisReference : Expression
938                 {
939                         public CapturedThisReference (Iterator iterator, Location loc)
940                         {
941                                 this.loc = loc;
942                                 this.type = iterator.this_type;
943                                 eclass = ExprClass.Variable;
944                         }
945
946                         public override Expression DoResolve (EmitContext ec)
947                         {
948                                 return this;
949                         }
950
951                         public override void Emit (EmitContext ec)
952                         {
953                                 ec.EmitThis ();
954                         }
955                 }
956
957                 protected class FieldExpression : Expression
958                 {
959                         Iterator iterator;
960                         Field field;
961
962                         public FieldExpression (Iterator iterator, Field field)
963                         {
964                                 this.iterator = iterator;
965                                 this.field = field;
966                                 this.loc = iterator.Location;
967                         }
968
969                         public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
970                         {
971                                 FieldExpr fexpr = new FieldExpr (field.FieldBuilder, loc);
972                                 fexpr.InstanceExpression = new ThisParameterReference (
973                                         iterator.this_type, loc);
974                                 return fexpr.ResolveLValue (ec, right_side, loc);
975                         }
976
977                         public override Expression DoResolve (EmitContext ec)
978                         {
979                                 FieldExpr fexpr = new FieldExpr (field.FieldBuilder, loc);
980                                 fexpr.InstanceExpression = new ThisParameterReference (
981                                         iterator.this_type, loc);
982                                 return fexpr.Resolve (ec);
983                         }
984
985                         public override void Emit (EmitContext ec)
986                         {
987                                 throw new InvalidOperationException ();
988                         }
989                 }
990
991                 protected class MoveNextMethod : AnonymousContainer
992                 {
993                         Iterator iterator;
994
995                         public MoveNextMethod (Iterator iterator, Location loc)
996                                 : base (iterator.parameters.Parameters, iterator.original_block, loc)
997                         {
998                                 this.iterator = iterator;
999                         }
1000
1001                         protected override bool CreateMethodHost (EmitContext ec)
1002                         {
1003                                 method = new Method (
1004                                         iterator, null, TypeManager.system_boolean_expr,
1005                                         Modifiers.PUBLIC, false, new MemberName ("MoveNext", loc),
1006                                         Parameters.EmptyReadOnlyParameters, null);
1007
1008                                 method.Block = Block;
1009
1010                                 MoveNextStatement inline = new MoveNextStatement (iterator, loc);
1011                                 Block.AddStatement (inline);
1012
1013                                 return true;
1014                         }
1015
1016                         public bool CreateMethod (EmitContext ec)
1017                         {
1018                                 return CreateMethodHost (ec);
1019                         }
1020
1021                         public override Iterator Iterator {
1022                                 get { return iterator; }
1023                         }
1024
1025                         public override bool IsIterator {
1026                                 get { return true; }
1027                         }
1028
1029                         public override void CreateScopeType (EmitContext ec, ScopeInfo scope)
1030                         {
1031                                 scope.ScopeTypeBuilder = iterator.TypeBuilder;
1032                                 scope.ScopeConstructor = iterator.ctor.ConstructorBuilder;
1033                         }
1034
1035                         public override void Emit (EmitContext ec)
1036                         {
1037                                 throw new InternalErrorException ();
1038                         }
1039                 }
1040
1041                 protected class MoveNextStatement : Statement {
1042                         Iterator iterator;
1043
1044                         public MoveNextStatement (Iterator iterator, Location loc)
1045                         {
1046                                 this.loc = loc;
1047                                 this.iterator = iterator;
1048                         }
1049
1050                         public override bool Resolve (EmitContext ec)
1051                         {
1052                                 return true;
1053                         }
1054
1055                         protected override void DoEmit (EmitContext ec)
1056                         {
1057                                 ec.CurrentAnonymousMethod = iterator.move_next_method;
1058                                 ec.InIterator = true;
1059
1060                                 iterator.EmitMoveNext (ec);
1061                         }
1062                 }
1063
1064                 protected class DisposeMethod : Statement {
1065                         Iterator iterator;
1066
1067                         public DisposeMethod (Iterator iterator, Location loc)
1068                         {
1069                                 this.loc = loc;
1070                                 this.iterator = iterator;
1071                         }
1072
1073                         public override bool Resolve (EmitContext ec)
1074                         {
1075                                 return true;
1076                         }
1077
1078                         protected override void DoEmit (EmitContext ec)
1079                         {
1080                                 iterator.EmitDispose (ec);
1081                         }
1082                 }
1083
1084                 protected class StatementList : Statement {
1085                         ArrayList statements;
1086
1087                         public StatementList (Location loc)
1088                         {
1089                                 this.loc = loc;
1090                                 statements = new ArrayList ();
1091                         }
1092
1093                         public void Add (Statement statement)
1094                         {
1095                                 statements.Add (statement);
1096                         }
1097
1098                         public override bool Resolve (EmitContext ec)
1099                         {
1100                                 foreach (Statement stmt in statements) {
1101                                         if (!stmt.Resolve (ec))
1102                                                 return false;
1103                                 }
1104
1105                                 return true;
1106                         }
1107
1108                         protected override void DoEmit (EmitContext ec)
1109                         {
1110                                 foreach (Statement stmt in statements)
1111                                         stmt.Emit (ec);
1112                         }
1113                 }
1114
1115                 protected class SetState : Statement
1116                 {
1117                         Iterator iterator;
1118                         State state;
1119
1120                         public SetState (Iterator iterator, State state, Location loc)
1121                         {
1122                                 this.iterator = iterator;
1123                                 this.state = state;
1124                                 this.loc = loc;
1125                         }
1126
1127                         public override bool Resolve (EmitContext ec)
1128                         {
1129                                 return true;
1130                         }
1131
1132                         protected override void DoEmit (EmitContext ec)
1133                         {
1134                                 ec.ig.Emit (OpCodes.Ldarg_0);
1135                                 IntConstant.EmitInt (ec.ig, (int) state);
1136                                 ec.ig.Emit (OpCodes.Stfld, iterator.pc_field.FieldBuilder);
1137                         }
1138                 }
1139
1140                 protected class InitScope : Statement
1141                 {
1142                         Iterator iterator;
1143
1144                         public InitScope (Iterator iterator, Location loc)
1145                         {
1146                                 this.iterator = iterator;
1147                                 this.loc = loc;
1148                         }
1149
1150                         public override bool Resolve (EmitContext ec)
1151                         {
1152                                 return true;
1153                         }
1154
1155                         protected override void DoEmit (EmitContext ec)
1156                         {
1157                                 iterator.cc.EmitInitScope (ec);
1158                         }
1159                 }
1160
1161                 void Define_Reset ()
1162                 {
1163                         Method reset = new Method (
1164                                 this, null, TypeManager.system_void_expr, Modifiers.PUBLIC,
1165                                 false, new MemberName ("Reset", Location),
1166                                 Parameters.EmptyReadOnlyParameters, null);
1167                         AddMethod (reset);
1168
1169                         reset.Block = new ToplevelBlock (Location);
1170                         reset.Block = new ToplevelBlock (block, parameters.Parameters, Location);
1171                         reset.Block.SetHaveAnonymousMethods (Location, move_next_method);
1172
1173                         reset.Block.AddStatement (Create_ThrowNotSupported ());
1174                 }
1175
1176                 void Define_Dispose ()
1177                 {
1178                         dispose = new Method (
1179                                 this, null, TypeManager.system_void_expr, Modifiers.PUBLIC,
1180                                 false, new MemberName ("Dispose", Location),
1181                                 Parameters.EmptyReadOnlyParameters, null);
1182                         AddMethod (dispose);
1183
1184                         dispose.Block = new ToplevelBlock (block, parameters.Parameters, Location);
1185                         dispose.Block.SetHaveAnonymousMethods (Location, move_next_method);
1186
1187                         dispose.Block.AddStatement (new DisposeMethod (this, Location));
1188                 }
1189
1190                 public Type IteratorType {
1191                         get { return iterator_type_expr.Type; }
1192                 }
1193
1194                 //
1195                 // This return statement tricks return into not flagging an error for being
1196                 // used in a Yields method
1197                 //
1198                 class NoCheckReturn : Statement {
1199                         public Expression Expr;
1200                 
1201                         public NoCheckReturn (Expression expr, Location l)
1202                         {
1203                                 Expr = expr;
1204                                 loc = l;
1205                         }
1206
1207                         public override bool Resolve (EmitContext ec)
1208                         {
1209                                 Expr = Expr.Resolve (ec);
1210                                 if (Expr == null)
1211                                         return false;
1212
1213                                 ec.CurrentBranching.CurrentUsageVector.Return ();
1214
1215                                 return true;
1216                         }
1217
1218                         protected override void DoEmit (EmitContext ec)
1219                         {
1220                                 Expr.Emit (ec);
1221                                 ec.ig.Emit (OpCodes.Ret);
1222                         }
1223                 }
1224
1225                 bool CheckType ()
1226                 {
1227                         Type ret = orig_method.ReturnType;
1228
1229                         if (ret == TypeManager.ienumerable_type) {
1230                                 original_iterator_type = TypeManager.object_type;
1231                                 is_enumerable = true;
1232                                 return true;
1233                         }
1234                         if (ret == TypeManager.ienumerator_type) {
1235                                 original_iterator_type = TypeManager.object_type;
1236                                 is_enumerable = false;
1237                                 return true;
1238                         }
1239
1240                         if (!ret.IsGenericInstance)
1241                                 return false;
1242
1243                         Type[] args = TypeManager.GetTypeArguments (ret);
1244                         if (args.Length != 1)
1245                                 return false;
1246
1247                         Type gt = ret.GetGenericTypeDefinition ();
1248                         if (gt == TypeManager.generic_ienumerable_type) {
1249                                 original_iterator_type = args [0];
1250                                 is_enumerable = true;
1251                                 return true;
1252                         } else if (gt == TypeManager.generic_ienumerator_type) {
1253                                 original_iterator_type = args [0];
1254                                 is_enumerable = false;
1255                                 return true;
1256                         }
1257
1258                         return false;
1259                 }
1260         }
1261 }
1262