**** Merged r47522-r47526 from MCS ****
[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);
352                         } else
353                                 return new MemberName (proxy_name);
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, m_container.Location)
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 ();
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);
754                                 type = iterator_type_expr;
755                         } else {
756                                 left = new MemberName ("System.Collections.IEnumerator");
757                                 type = TypeManager.system_object_expr;
758                         }
759
760                         MemberName name = new MemberName (left, "Current", null);
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), Location),
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, Location);
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);
801                                 type = generic_enumerator_type;
802                         } else {
803                                 left = new MemberName ("System.Collections.IEnumerable");
804                                 type = enumerator_type;
805                         }
806
807                         MemberName name = new MemberName (left, "GetEnumerator", null);
808
809                         Method get_enumerator = new Method (
810                                 this, null, type, 0, false, name,
811                                 Parameters.EmptyReadOnlyParameters, null,
812                                 Location.Null);
813                         AddMethod (get_enumerator);
814
815                         get_enumerator.Block = new ToplevelBlock (
816                                 block, parameters.Parameters, Location);
817
818                         get_enumerator.Block.SetHaveAnonymousMethods (Location, move_next_method);
819
820                         Expression ce = new MemberAccess (
821                                 new SimpleName ("System.Threading.Interlocked", Location),
822                                 "CompareExchange", Location);
823
824                         Expression pc = new FieldExpression (this, pc_field);
825                         Expression before = new IntLiteral ((int) State.Running);
826                         Expression uninitialized = new IntLiteral ((int) State.Uninitialized);
827
828                         ArrayList args = new ArrayList ();
829                         args.Add (new Argument (pc, Argument.AType.Ref));
830                         args.Add (new Argument (before, Argument.AType.Expression));
831                         args.Add (new Argument (uninitialized, Argument.AType.Expression));
832
833                         get_enumerator.Block.AddStatement (new If (
834                                 new Binary (
835                                         Binary.Operator.Equality,
836                                         new Invocation (ce, args, Location),
837                                         uninitialized, Location),
838                                 new Return (new ThisParameterReference (type.Type, Location),
839                                             Location),
840                                 Location));
841
842                         args = new ArrayList ();
843                         if (!IsStatic) {
844                                 args.Add (new Argument (new CapturedThisReference (this, Location)));
845                         }
846
847                         args.Add (new Argument (new BoolLiteral (true)));
848
849                         for (int i = 0; i < parameters.Count; i++) {
850                                 Expression cp = new CapturedParameterReference (
851                                         this, parameters.ParameterType (i),
852                                         parameters.ParameterName (i), Location);
853                                 args.Add (new Argument (cp));
854                         }
855
856                         Expression new_expr = new New (current_type, args, Location);
857                         get_enumerator.Block.AddStatement (new Return (new_expr, Location));
858                 }
859
860                 protected class SimpleParameterReference : Expression
861                 {
862                         int idx;
863
864                         public SimpleParameterReference (Type type, int idx, Location loc)
865                         {
866                                 this.idx = idx;
867                                 this.loc = loc;
868                                 this.type = type;
869                                 eclass = ExprClass.Variable;
870                         }
871
872                         public override Expression DoResolve (EmitContext ec)
873                         {
874                                 return this;
875                         }
876
877                         public override void Emit (EmitContext ec)
878                         {
879                                 DoEmit (ec);
880                         }
881
882                         protected virtual void DoEmit (EmitContext ec)
883                         {
884                                 ParameterReference.EmitLdArg (ec.ig, idx);
885                         }
886                 }
887
888                 protected class ThisParameterReference : SimpleParameterReference, IMemoryLocation
889                 {
890                         public ThisParameterReference (Type type, Location loc)
891                                 : base (type, 0, loc)
892                         { }
893
894                         protected override void DoEmit (EmitContext ec)
895                         {
896                                 base.DoEmit (ec);
897                                 if (ec.TypeContainer is Struct)
898                                         ec.ig.Emit (OpCodes.Ldobj, type);
899                         }
900
901                         public void AddressOf (EmitContext ec, AddressOp mode)
902                         {
903                                 if (ec.TypeContainer is Struct)
904                                         ec.ig.Emit (OpCodes.Ldarga, 0);
905                                 else
906                                         ec.ig.Emit (OpCodes.Ldarg, 0);
907                         }
908                 }
909
910                 protected class CapturedParameterReference : Expression
911                 {
912                         Iterator iterator;
913                         string name;
914
915                         public CapturedParameterReference (Iterator iterator, Type type,
916                                                            string name, Location loc)
917                         {
918                                 this.iterator = iterator;
919                                 this.loc = loc;
920                                 this.type = type;
921                                 this.name = name;
922                                 eclass = ExprClass.Variable;
923                         }
924
925                         public override Expression DoResolve (EmitContext ec)
926                         {
927                                 return this;
928                         }
929
930                         public override void Emit (EmitContext ec)
931                         {
932                                 ec.CurrentAnonymousMethod = iterator.move_next_method;
933
934                                 iterator.cc.EmitParameter (ec, name);
935                         }
936                 }
937
938                 protected class CapturedThisReference : Expression
939                 {
940                         public CapturedThisReference (Iterator iterator, Location loc)
941                         {
942                                 this.loc = loc;
943                                 this.type = iterator.this_type;
944                                 eclass = ExprClass.Variable;
945                         }
946
947                         public override Expression DoResolve (EmitContext ec)
948                         {
949                                 return this;
950                         }
951
952                         public override void Emit (EmitContext ec)
953                         {
954                                 ec.EmitThis ();
955                         }
956                 }
957
958                 protected class FieldExpression : Expression
959                 {
960                         Iterator iterator;
961                         Field field;
962
963                         public FieldExpression (Iterator iterator, Field field)
964                         {
965                                 this.iterator = iterator;
966                                 this.field = field;
967                                 this.loc = iterator.Location;
968                         }
969
970                         public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
971                         {
972                                 FieldExpr fexpr = new FieldExpr (field.FieldBuilder, loc);
973                                 fexpr.InstanceExpression = new ThisParameterReference (
974                                         iterator.this_type, loc);
975                                 return fexpr.ResolveLValue (ec, right_side, loc);
976                         }
977
978                         public override Expression DoResolve (EmitContext ec)
979                         {
980                                 FieldExpr fexpr = new FieldExpr (field.FieldBuilder, loc);
981                                 fexpr.InstanceExpression = new ThisParameterReference (
982                                         iterator.this_type, loc);
983                                 return fexpr.Resolve (ec);
984                         }
985
986                         public override void Emit (EmitContext ec)
987                         {
988                                 throw new InvalidOperationException ();
989                         }
990                 }
991
992                 protected class MoveNextMethod : AnonymousContainer
993                 {
994                         Iterator iterator;
995
996                         public MoveNextMethod (Iterator iterator, Location loc)
997                                 : base (iterator.parameters.Parameters, iterator.original_block, loc)
998                         {
999                                 this.iterator = iterator;
1000                         }
1001
1002                         protected override bool CreateMethodHost (EmitContext ec)
1003                         {
1004                                 method = new Method (
1005                                         iterator, null, TypeManager.system_boolean_expr,
1006                                         Modifiers.PUBLIC, false, new MemberName ("MoveNext"),
1007                                         Parameters.EmptyReadOnlyParameters, null, loc);
1008
1009                                 method.Block = Block;
1010
1011                                 MoveNextStatement inline = new MoveNextStatement (iterator, loc);
1012                                 Block.AddStatement (inline);
1013
1014                                 return true;
1015                         }
1016
1017                         public bool CreateMethod (EmitContext ec)
1018                         {
1019                                 return CreateMethodHost (ec);
1020                         }
1021
1022                         public override Iterator Iterator {
1023                                 get { return iterator; }
1024                         }
1025
1026                         public override bool IsIterator {
1027                                 get { return true; }
1028                         }
1029
1030                         public override void CreateScopeType (EmitContext ec, ScopeInfo scope)
1031                         {
1032                                 scope.ScopeTypeBuilder = iterator.TypeBuilder;
1033                                 scope.ScopeConstructor = iterator.ctor.ConstructorBuilder;
1034                         }
1035
1036                         public override void Emit (EmitContext ec)
1037                         {
1038                                 throw new InternalErrorException ();
1039                         }
1040                 }
1041
1042                 protected class MoveNextStatement : Statement {
1043                         Iterator iterator;
1044
1045                         public MoveNextStatement (Iterator iterator, Location loc)
1046                         {
1047                                 this.loc = loc;
1048                                 this.iterator = iterator;
1049                         }
1050
1051                         public override bool Resolve (EmitContext ec)
1052                         {
1053                                 return true;
1054                         }
1055
1056                         protected override void DoEmit (EmitContext ec)
1057                         {
1058                                 ec.CurrentAnonymousMethod = iterator.move_next_method;
1059                                 ec.InIterator = true;
1060
1061                                 iterator.EmitMoveNext (ec);
1062                         }
1063                 }
1064
1065                 protected class DisposeMethod : Statement {
1066                         Iterator iterator;
1067
1068                         public DisposeMethod (Iterator iterator, Location loc)
1069                         {
1070                                 this.loc = loc;
1071                                 this.iterator = iterator;
1072                         }
1073
1074                         public override bool Resolve (EmitContext ec)
1075                         {
1076                                 return true;
1077                         }
1078
1079                         protected override void DoEmit (EmitContext ec)
1080                         {
1081                                 iterator.EmitDispose (ec);
1082                         }
1083                 }
1084
1085                 protected class StatementList : Statement {
1086                         ArrayList statements;
1087
1088                         public StatementList (Location loc)
1089                         {
1090                                 this.loc = loc;
1091                                 statements = new ArrayList ();
1092                         }
1093
1094                         public void Add (Statement statement)
1095                         {
1096                                 statements.Add (statement);
1097                         }
1098
1099                         public override bool Resolve (EmitContext ec)
1100                         {
1101                                 foreach (Statement stmt in statements) {
1102                                         if (!stmt.Resolve (ec))
1103                                                 return false;
1104                                 }
1105
1106                                 return true;
1107                         }
1108
1109                         protected override void DoEmit (EmitContext ec)
1110                         {
1111                                 foreach (Statement stmt in statements)
1112                                         stmt.Emit (ec);
1113                         }
1114                 }
1115
1116                 protected class SetState : Statement
1117                 {
1118                         Iterator iterator;
1119                         State state;
1120
1121                         public SetState (Iterator iterator, State state, Location loc)
1122                         {
1123                                 this.iterator = iterator;
1124                                 this.state = state;
1125                                 this.loc = loc;
1126                         }
1127
1128                         public override bool Resolve (EmitContext ec)
1129                         {
1130                                 return true;
1131                         }
1132
1133                         protected override void DoEmit (EmitContext ec)
1134                         {
1135                                 ec.ig.Emit (OpCodes.Ldarg_0);
1136                                 IntConstant.EmitInt (ec.ig, (int) state);
1137                                 ec.ig.Emit (OpCodes.Stfld, iterator.pc_field.FieldBuilder);
1138                         }
1139                 }
1140
1141                 protected class InitScope : Statement
1142                 {
1143                         Iterator iterator;
1144
1145                         public InitScope (Iterator iterator, Location loc)
1146                         {
1147                                 this.iterator = iterator;
1148                                 this.loc = loc;
1149                         }
1150
1151                         public override bool Resolve (EmitContext ec)
1152                         {
1153                                 return true;
1154                         }
1155
1156                         protected override void DoEmit (EmitContext ec)
1157                         {
1158                                 iterator.cc.EmitInitScope (ec);
1159                         }
1160                 }
1161
1162                 void Define_Reset ()
1163                 {
1164                         Method reset = new Method (
1165                                 this, null, TypeManager.system_void_expr, Modifiers.PUBLIC,
1166                                 false, new MemberName ("Reset"),
1167                                 Parameters.EmptyReadOnlyParameters, null, Location);
1168                         AddMethod (reset);
1169
1170                         reset.Block = new ToplevelBlock (Location);
1171                         reset.Block = new ToplevelBlock (block, parameters.Parameters, Location);
1172                         reset.Block.SetHaveAnonymousMethods (Location, move_next_method);
1173
1174                         reset.Block.AddStatement (Create_ThrowNotSupported ());
1175                 }
1176
1177                 void Define_Dispose ()
1178                 {
1179                         dispose = new Method (
1180                                 this, null, TypeManager.system_void_expr, Modifiers.PUBLIC,
1181                                 false, new MemberName ("Dispose"),
1182                                 Parameters.EmptyReadOnlyParameters, null, Location);
1183                         AddMethod (dispose);
1184
1185                         dispose.Block = new ToplevelBlock (block, parameters.Parameters, Location);
1186                         dispose.Block.SetHaveAnonymousMethods (Location, move_next_method);
1187
1188                         dispose.Block.AddStatement (new DisposeMethod (this, Location));
1189                 }
1190
1191                 public Type IteratorType {
1192                         get { return iterator_type_expr.Type; }
1193                 }
1194
1195                 //
1196                 // This return statement tricks return into not flagging an error for being
1197                 // used in a Yields method
1198                 //
1199                 class NoCheckReturn : Statement {
1200                         public Expression Expr;
1201                 
1202                         public NoCheckReturn (Expression expr, Location l)
1203                         {
1204                                 Expr = expr;
1205                                 loc = l;
1206                         }
1207
1208                         public override bool Resolve (EmitContext ec)
1209                         {
1210                                 Expr = Expr.Resolve (ec);
1211                                 if (Expr == null)
1212                                         return false;
1213
1214                                 ec.CurrentBranching.CurrentUsageVector.Return ();
1215
1216                                 return true;
1217                         }
1218
1219                         protected override void DoEmit (EmitContext ec)
1220                         {
1221                                 Expr.Emit (ec);
1222                                 ec.ig.Emit (OpCodes.Ret);
1223                         }
1224                 }
1225
1226                 bool CheckType ()
1227                 {
1228                         Type ret = orig_method.ReturnType;
1229
1230                         if (ret == TypeManager.ienumerable_type) {
1231                                 original_iterator_type = TypeManager.object_type;
1232                                 is_enumerable = true;
1233                                 return true;
1234                         }
1235                         if (ret == TypeManager.ienumerator_type) {
1236                                 original_iterator_type = TypeManager.object_type;
1237                                 is_enumerable = false;
1238                                 return true;
1239                         }
1240
1241                         if (!ret.IsGenericInstance)
1242                                 return false;
1243
1244                         Type[] args = TypeManager.GetTypeArguments (ret);
1245                         if (args.Length != 1)
1246                                 return false;
1247
1248                         Type gt = ret.GetGenericTypeDefinition ();
1249                         if (gt == TypeManager.generic_ienumerable_type) {
1250                                 original_iterator_type = args [0];
1251                                 is_enumerable = true;
1252                                 return true;
1253                         } else if (gt == TypeManager.generic_ienumerator_type) {
1254                                 original_iterator_type = args [0];
1255                                 is_enumerable = false;
1256                                 return true;
1257                         }
1258
1259                         return false;
1260                 }
1261         }
1262 }
1263