**** Merged r40732-r40872 from MCS ****
[mono.git] / mcs / mbas / statement.cs
1 //
2 // statement.cs: Statement representation for the IL tree.
3 //
4 // Author:
5 //   Miguel de Icaza (miguel@ximian.com)
6 //   Martin Baulig (martin@gnome.org)
7 //       Anirban Bhattacharjee (banirban@novell.com)
8 //   Manjula GHM (mmanjula@novell.com)
9 //
10 // (C) 2001, 2002 Ximian, Inc.
11 //
12
13 using System;
14 using System.Text;
15 using System.Reflection;
16 using System.Reflection.Emit;
17 using System.Diagnostics;
18
19 namespace Mono.MonoBASIC {
20
21         using System.Collections;
22         
23         public abstract class Statement {
24                 public Location loc;
25                 
26                 ///
27                 /// Resolves the statement, true means that all sub-statements
28                 /// did resolve ok.
29                 //
30                 public virtual bool Resolve (EmitContext ec)
31                 {
32                         return true;
33                 }
34                 
35                 /// <summary>
36                 ///   Return value indicates whether all code paths emitted return.
37                 /// </summary>
38                 protected abstract bool DoEmit (EmitContext ec);
39
40                 /// <summary>
41                 ///   Return value indicates whether all code paths emitted return.
42                 /// </summary>
43                 public virtual bool Emit (EmitContext ec)
44                 {
45                         ec.Mark (loc);
46                         Report.Debug (8, "MARK", this, loc);
47                         return DoEmit (ec);
48                 }
49                 
50                 public static Expression ResolveBoolean (EmitContext ec, Expression e, Location loc)
51                 {
52                         e = e.Resolve (ec);
53                         if (e == null)
54                                 return null;
55                         
56                         if (e.Type != TypeManager.bool_type){
57                                 e = Expression.ConvertImplicit (ec, e, TypeManager.bool_type, Location.Null);
58                         }
59
60                         if (e == null){
61                                 Report.Error (
62                                         30311, loc, "Can not convert the expression to a boolean");
63                         }
64
65                         ec.Mark (loc);
66
67                         return e;
68                 }
69                 
70                 /// <remarks>
71                 ///    Encapsulates the emission of a boolean test and jumping to a
72                 ///    destination.
73                 ///
74                 ///    This will emit the bool expression in `bool_expr' and if
75                 ///    `target_is_for_true' is true, then the code will generate a 
76                 ///    brtrue to the target.   Otherwise a brfalse. 
77                 /// </remarks>
78                 public static void EmitBoolExpression (EmitContext ec, Expression bool_expr,
79                                                        Label target, bool target_is_for_true)
80                 {
81                         ILGenerator ig = ec.ig;
82                         
83                         bool invert = false;
84                         if (bool_expr is Unary){
85                                 Unary u = (Unary) bool_expr;
86                                 
87                                 if (u.Oper == Unary.Operator.LogicalNot){
88                                         invert = true;
89
90                                         u.EmitLogicalNot (ec);
91                                 }
92                         } else if (bool_expr is Binary){
93                                 Binary b = (Binary) bool_expr;
94
95                                 if (b.EmitBranchable (ec, target, target_is_for_true))
96                                         return;
97                         }
98
99                         if (!invert)
100                                 bool_expr.Emit (ec);
101
102                         if (target_is_for_true){
103                                 if (invert)
104                                         ig.Emit (OpCodes.Brfalse, target);
105                                 else
106                                         ig.Emit (OpCodes.Brtrue, target);
107                         } else {
108                                 if (invert)
109                                         ig.Emit (OpCodes.Brtrue, target);
110                                 else
111                                         ig.Emit (OpCodes.Brfalse, target);
112                         }
113                 }
114
115                 public static void Warning_DeadCodeFound (Location loc)
116                 {
117                         Report.Warning (162, loc, "Unreachable code detected");
118                 }
119         }
120
121         public class EmptyStatement : Statement {
122                 public override bool Resolve (EmitContext ec)
123                 {
124                         return true;
125                 }
126                 
127                 protected override bool DoEmit (EmitContext ec)
128                 {
129                         return false;
130                 }
131         }
132         
133         public class If : Statement {
134                 Expression expr;
135                 public Statement TrueStatement;
136                 public Statement FalseStatement;
137                 
138                 public If (Expression expr, Statement trueStatement, Location l)
139                 {
140                         this.expr = expr;
141                         TrueStatement = trueStatement;
142                         loc = l;
143                 }
144
145                 public If (Expression expr,
146                            Statement trueStatement,
147                            Statement falseStatement,
148                            Location l)
149                 {
150                         this.expr = expr;
151                         TrueStatement = trueStatement;
152                         FalseStatement = falseStatement;
153                         loc = l;
154                 }
155
156                 public override bool Resolve (EmitContext ec)
157                 {
158                         Report.Debug (1, "START IF BLOCK", loc);
159
160                         expr = ResolveBoolean (ec, expr, loc);
161                         if (expr == null){
162                                 return false;
163                         }
164                         
165                         ec.StartFlowBranching (FlowBranchingType.BLOCK, loc);
166                         
167                         if (!TrueStatement.Resolve (ec)) {
168                                 ec.KillFlowBranching ();
169                                 return false;
170                         }
171
172                         ec.CurrentBranching.CreateSibling ();
173
174                         if ((FalseStatement != null) && !FalseStatement.Resolve (ec)) {
175                                 ec.KillFlowBranching ();
176                                 return false;
177                         }
178                                         
179                         ec.EndFlowBranching ();
180
181                         Report.Debug (1, "END IF BLOCK", loc);
182
183                         return true;
184                 }
185                 
186                 protected override bool DoEmit (EmitContext ec)
187                 {
188                         ILGenerator ig = ec.ig;
189                         Label false_target = ig.DefineLabel ();
190                         Label end;
191                         bool is_true_ret, is_false_ret;
192
193                         //
194                         // Dead code elimination
195                         //
196                         if (expr is BoolConstant){
197                                 bool take = ((BoolConstant) expr).Value;
198
199                                 if (take){
200                                         if (FalseStatement != null){
201                                                 Warning_DeadCodeFound (FalseStatement.loc);
202                                         }
203                                         return TrueStatement.Emit (ec);
204                                 } else {
205                                         Warning_DeadCodeFound (TrueStatement.loc);
206                                         if (FalseStatement != null)
207                                                 return FalseStatement.Emit (ec);
208                                 }
209                         }
210                         
211                         EmitBoolExpression (ec, expr, false_target, false);
212
213                         is_true_ret = TrueStatement.Emit (ec);
214                         is_false_ret = is_true_ret;
215
216                         if (FalseStatement != null){
217                                 bool branch_emitted = false;
218                                 
219                                 end = ig.DefineLabel ();
220                                 if (!is_true_ret){
221                                         ig.Emit (OpCodes.Br, end);
222                                         branch_emitted = true;
223                                 }
224
225                                 ig.MarkLabel (false_target);
226                                 is_false_ret = FalseStatement.Emit (ec);
227
228                                 if (branch_emitted)
229                                         ig.MarkLabel (end);
230                         } else {
231                                 ig.MarkLabel (false_target);
232                                 is_false_ret = false;
233                         }
234
235                         return is_true_ret && is_false_ret;
236                 }
237         }
238
239         public enum DoOptions {
240                 WHILE,
241                 UNTIL,
242                 TEST_BEFORE,
243                 TEST_AFTER
244         };
245
246         public class Do : Statement {
247                 public Expression expr;
248                 public readonly Statement  EmbeddedStatement;
249                 //public DoOptions type;
250                 public DoOptions test;
251                 bool infinite, may_return;
252
253                 
254                 public Do (Statement statement, Expression boolExpr, DoOptions do_test, Location l)
255                 {
256                         expr = boolExpr;
257                         EmbeddedStatement = statement;
258 //                      type = do_type;
259                         test = do_test;
260                         loc = l;
261                 }
262
263                 public override bool Resolve (EmitContext ec)
264                 {
265                         bool ok = true;
266
267                         ec.StartFlowBranching (FlowBranchingType.LOOP_BLOCK, loc);
268
269                         if (!EmbeddedStatement.Resolve (ec))
270                                 ok = false;
271
272                         expr = ResolveBoolean (ec, expr, loc);
273                         if (expr == null)
274                                 ok = false;
275                         else if (expr is BoolConstant){
276                                 bool res = ((BoolConstant) expr).Value;
277
278                                 if (res)
279                                         infinite = true;
280                         }
281
282                         ec.CurrentBranching.Infinite = infinite;
283                         FlowReturns returns = ec.EndFlowBranching ();
284                         may_return = returns != FlowReturns.NEVER;
285
286                         return ok;
287                 }
288                 
289                 protected override bool DoEmit (EmitContext ec)
290                 {
291                         ILGenerator ig = ec.ig;
292                         Label loop = ig.DefineLabel ();
293                         Label old_begin = ec.LoopBegin;
294                         Label old_end = ec.LoopEnd;
295                         bool  old_inloop = ec.InLoop;
296                         int old_loop_begin_try_catch_level = ec.LoopBeginTryCatchLevel;
297                         
298                         ec.LoopBegin = ig.DefineLabel ();
299                         ec.LoopEnd = ig.DefineLabel ();
300                         ec.InLoop = true;
301                         ec.LoopBeginTryCatchLevel = ec.TryCatchLevel;
302
303                         if (test == DoOptions.TEST_AFTER) {
304                                 ig.MarkLabel (loop);
305                                 EmbeddedStatement.Emit (ec);
306                                 ig.MarkLabel (ec.LoopBegin);
307
308                                 //
309                                 // Dead code elimination
310                                 //
311                                 if (expr is BoolConstant){
312                                         bool res = ((BoolConstant) expr).Value;
313
314                                         if (res)
315                                                 ec.ig.Emit (OpCodes.Br, loop);
316                                 } else
317                                         EmitBoolExpression (ec, expr, loop, true);
318
319                                 ig.MarkLabel (ec.LoopEnd);
320                         }
321                         else
322                         {
323                                 ig.MarkLabel (loop);
324                                 ig.MarkLabel (ec.LoopBegin);
325
326                                 //
327                                 // Dead code elimination
328                                 //
329                                 if (expr is BoolConstant){
330                                         bool res = ((BoolConstant) expr).Value;
331
332                                         if (res)
333                                                 ec.ig.Emit (OpCodes.Br, ec.LoopEnd);
334                                 } else
335                                         EmitBoolExpression (ec, expr, ec.LoopEnd, true);
336
337                                 EmbeddedStatement.Emit (ec);
338                                 ec.ig.Emit (OpCodes.Br, loop);
339                                 ig.MarkLabel (ec.LoopEnd);
340                         }
341                         ec.LoopBeginTryCatchLevel = old_loop_begin_try_catch_level;
342                         ec.LoopBegin = old_begin;
343                         ec.LoopEnd = old_end;
344                         ec.InLoop = old_inloop;
345
346                         if (infinite)
347                                 return may_return == false;
348                         else
349                                 return false;
350                 }
351         }
352
353         public class While : Statement {
354                 public Expression expr;
355                 public readonly Statement Statement;
356                 bool may_return, empty, infinite;
357                 
358                 public While (Expression boolExpr, Statement statement, Location l)
359                 {
360                         this.expr = boolExpr;
361                         Statement = statement;
362                         loc = l;
363                 }
364
365                 public override bool Resolve (EmitContext ec)
366                 {
367                         bool ok = true;
368
369                         expr = ResolveBoolean (ec, expr, loc);
370                         if (expr == null)
371                                 return false;
372
373                         ec.StartFlowBranching (FlowBranchingType.LOOP_BLOCK, loc);
374
375                         //
376                         // Inform whether we are infinite or not
377                         //
378                         if (expr is BoolConstant){
379                                 BoolConstant bc = (BoolConstant) expr;
380
381                                 if (bc.Value == false){
382                                         Warning_DeadCodeFound (Statement.loc);
383                                         empty = true;
384                                 } else
385                                         infinite = true;
386                         } else {
387                                 //
388                                 // We are not infinite, so the loop may or may not be executed.
389                                 //
390                                 ec.CurrentBranching.CreateSibling ();
391                         }
392
393                         if (!Statement.Resolve (ec))
394                                 ok = false;
395
396                         if (empty)
397                                 ec.KillFlowBranching ();
398                         else {
399                                 ec.CurrentBranching.Infinite = infinite;
400                                 FlowReturns returns = ec.EndFlowBranching ();
401                                 may_return = returns != FlowReturns.NEVER;
402                         }
403
404                         return ok;
405                 }
406                 
407                 protected override bool DoEmit (EmitContext ec)
408                 {
409                         if (empty)
410                                 return false;
411
412                         ILGenerator ig = ec.ig;
413                         Label old_begin = ec.LoopBegin;
414                         Label old_end = ec.LoopEnd;
415                         bool old_inloop = ec.InLoop;
416                         int old_loop_begin_try_catch_level = ec.LoopBeginTryCatchLevel;
417                         bool ret;
418                         
419                         ec.LoopBegin = ig.DefineLabel ();
420                         ec.LoopEnd = ig.DefineLabel ();
421                         ec.InLoop = true;
422                         ec.LoopBeginTryCatchLevel = ec.TryCatchLevel;
423
424                         //
425                         // Inform whether we are infinite or not
426                         //
427                         if (expr is BoolConstant){
428                                 ig.MarkLabel (ec.LoopBegin);
429                                 Statement.Emit (ec);
430                                 ig.Emit (OpCodes.Br, ec.LoopBegin);
431                                         
432                                 //
433                                 // Inform that we are infinite (ie, `we return'), only
434                                 // if we do not `break' inside the code.
435                                 //
436                                 ret = may_return == false;
437                                 ig.MarkLabel (ec.LoopEnd);
438                         } else {
439                                 Label while_loop = ig.DefineLabel ();
440
441                                 ig.Emit (OpCodes.Br, ec.LoopBegin);
442                                 ig.MarkLabel (while_loop);
443
444                                 Statement.Emit (ec);
445                         
446                                 ig.MarkLabel (ec.LoopBegin);
447
448                                 EmitBoolExpression (ec, expr, while_loop, true);
449                                 ig.MarkLabel (ec.LoopEnd);
450
451                                 ret = false;
452                         }       
453
454                         ec.LoopBegin = old_begin;
455                         ec.LoopEnd = old_end;
456                         ec.InLoop = old_inloop;
457                         ec.LoopBeginTryCatchLevel = old_loop_begin_try_catch_level;
458
459                         return ret;
460                 }
461         }
462
463         public class For : Statement {
464                 Expression Test;
465                 readonly Statement InitStatement;
466                 readonly Statement Increment;
467                 readonly Statement Statement;
468                 bool may_return, infinite, empty;
469                 
470                 public For (Statement initStatement,
471                             Expression test,
472                             Statement increment,
473                             Statement statement,
474                             Location l)
475                 {
476                         InitStatement = initStatement;
477                         Test = test;
478                         Increment = increment;
479                         Statement = statement;
480                         loc = l;
481                 }
482                 
483
484                 public override bool Resolve (EmitContext ec)
485                 {
486                         bool ok = true;
487
488                         if (InitStatement != null){
489                                 if (!InitStatement.Resolve (ec))
490                                         ok = false;
491                         }
492
493                         if (Test != null){
494                                 Test = ResolveBoolean (ec, Test, loc);
495                                 if (Test == null)
496                                         ok = false;
497                                 else if (Test is BoolConstant){
498                                         BoolConstant bc = (BoolConstant) Test;
499
500                                         if (bc.Value == false){
501                                                 Warning_DeadCodeFound (Statement.loc);
502                                                 empty = true;
503                                         } else
504                                                 infinite = true;
505                                 }
506                         } else
507                                 infinite = true;
508
509                         if (Increment != null){
510                                 if (!Increment.Resolve (ec))
511                                         ok = false;
512                         }
513
514                         ec.StartFlowBranching (FlowBranchingType.LOOP_BLOCK, loc);
515                         if (!infinite)
516                                 ec.CurrentBranching.CreateSibling ();
517
518                         if (!Statement.Resolve (ec))
519                                 ok = false;
520
521                         if (empty)
522                                 ec.KillFlowBranching ();
523                         else {
524                                 ec.CurrentBranching.Infinite = infinite;
525                                 FlowReturns returns = ec.EndFlowBranching ();
526                                 may_return = returns != FlowReturns.NEVER;
527                         }
528
529                         return ok;
530                 }
531                 
532                 protected override bool DoEmit (EmitContext ec)
533                 {
534                         if (empty)
535                                 return false;
536
537                         ILGenerator ig = ec.ig;
538                         Label old_begin = ec.LoopBegin;
539                         Label old_end = ec.LoopEnd;
540                         bool old_inloop = ec.InLoop;
541                         int old_loop_begin_try_catch_level = ec.LoopBeginTryCatchLevel;
542                         Label loop = ig.DefineLabel ();
543                         Label test = ig.DefineLabel ();
544                         
545                         if (InitStatement != null)
546                                 if (! (InitStatement is EmptyStatement))
547                                         InitStatement.Emit (ec);
548
549                         ec.LoopBegin = ig.DefineLabel ();
550                         ec.LoopEnd = ig.DefineLabel ();
551                         ec.InLoop = true;
552                         ec.LoopBeginTryCatchLevel = ec.TryCatchLevel;
553
554                         ig.Emit (OpCodes.Br, test);
555                         ig.MarkLabel (loop);
556                         Statement.Emit (ec);
557
558                         ig.MarkLabel (ec.LoopBegin);
559                         if (!(Increment is EmptyStatement))
560                                 Increment.Emit (ec);
561
562                         ig.MarkLabel (test);
563                         //
564                         // If test is null, there is no test, and we are just
565                         // an infinite loop
566                         //
567                         if (Test != null)
568                                 EmitBoolExpression (ec, Test, loop, true);
569                         else
570                                 ig.Emit (OpCodes.Br, loop);
571                         ig.MarkLabel (ec.LoopEnd);
572
573                         ec.LoopBegin = old_begin;
574                         ec.LoopEnd = old_end;
575                         ec.InLoop = old_inloop;
576                         ec.LoopBeginTryCatchLevel = old_loop_begin_try_catch_level;
577                         
578                         //
579                         // Inform whether we are infinite or not
580                         //
581                         if (Test != null){
582                                 if (Test is BoolConstant){
583                                         BoolConstant bc = (BoolConstant) Test;
584
585                                         if (bc.Value)
586                                                 return may_return == false;
587                                 }
588                                 return false;
589                         } else
590                                 return may_return == false;
591                 }
592         }
593         
594         public class StatementExpression : Statement {
595                 public Expression expr;
596                 
597                 public StatementExpression (ExpressionStatement expr, Location l)
598                 {
599                         this.expr = expr;
600                         loc = l;
601                 }
602
603                 public override bool Resolve (EmitContext ec)
604                 {
605                         expr = (Expression) expr.Resolve (ec);
606                         return expr != null;
607                 }
608                 
609                 protected override bool DoEmit (EmitContext ec)
610                 {
611                         ILGenerator ig = ec.ig;
612                         
613                         if (expr is ExpressionStatement)
614                                 ((ExpressionStatement) expr).EmitStatement (ec);
615                         else {
616                                 expr.Emit (ec);
617                                 ig.Emit (OpCodes.Pop);
618                         }
619
620                         return false;
621                 }
622
623                 public override string ToString ()
624                 {
625                         return "StatementExpression (" + expr + ")";
626                 }
627         }
628
629         /// <summary>
630         ///   Implements the return statement
631         /// </summary>
632         public class Return : Statement {
633                 public Expression Expr;
634                 
635                 public Return (Expression expr, Location l)
636                 {
637                         Expr = expr;
638                         loc = l;
639                 }
640
641                 public override bool Resolve (EmitContext ec)
642                 {
643                         if (Expr != null){
644                                 Expr = Expr.Resolve (ec);
645                                 if (Expr == null)
646                                         return false;
647                         }
648
649                         FlowBranching.UsageVector vector = ec.CurrentBranching.CurrentUsageVector;
650
651                         if (ec.CurrentBranching.InTryBlock ())
652                                 ec.CurrentBranching.AddFinallyVector (vector);
653                         else
654                                 vector.CheckOutParameters (ec.CurrentBranching);
655
656                         vector.Returns = FlowReturns.ALWAYS;
657                         vector.Breaks = FlowReturns.ALWAYS;
658                         return true;
659                 }
660                 
661                 protected override bool DoEmit (EmitContext ec)
662                 {
663                         if (ec.InFinally){
664                                 Report.Error (157,loc,"Control can not leave the body of the finally block");
665                                 return false;
666                         }
667                         
668                         if (ec.ReturnType == null){
669                                 if (Expr != null){
670                                         Report.Error (127, loc, "Return with a value not allowed here");
671                                         return true;
672                                 }
673                         } else {
674                                 if (Expr == null){
675                                         Report.Error (126, loc, "An object of type `" +
676                                                       TypeManager.MonoBASIC_Name (ec.ReturnType) + "' is " +
677                                                       "expected for the return statement");
678                                         return true;
679                                 }
680
681                                 if (Expr.Type != ec.ReturnType)
682                                         Expr = Expression.ConvertImplicitRequired (
683                                                 ec, Expr, ec.ReturnType, loc);
684
685                                 if (Expr == null)
686                                         return true;
687
688                                 Expr.Emit (ec);
689
690                                 if (ec.InTry || ec.InCatch)
691                                         ec.ig.Emit (OpCodes.Stloc, ec.TemporaryReturn ());
692                         }
693
694                         if (ec.InTry || ec.InCatch) {
695                                 if (!ec.HasReturnLabel) {
696                                         ec.ReturnLabel = ec.ig.DefineLabel ();
697                                         ec.HasReturnLabel = true;
698                                 }
699                                 ec.ig.Emit (OpCodes.Leave, ec.ReturnLabel);
700                         } else
701                                 ec.ig.Emit (OpCodes.Ret);
702
703                         return true; 
704                 }
705         }
706
707         public class Goto : Statement {
708                 string target;
709                 Block block;
710                 LabeledStatement label;
711                 
712                 public override bool Resolve (EmitContext ec)
713                 {
714                         label = block.LookupLabel (target);
715                         if (label == null){
716                                 Report.Error (
717                                         30132, loc,
718                                         "No such label `" + target + "' in this scope");
719                                 return false;
720                         }
721
722                         // If this is a forward goto.
723                         if (!label.IsDefined)
724                                 label.AddUsageVector (ec.CurrentBranching.CurrentUsageVector);
725
726                         ec.CurrentBranching.CurrentUsageVector.Breaks = FlowReturns.ALWAYS;
727
728                         return true;
729                 }
730                 
731                 public Goto (Block parent_block, string label, Location l)
732                 {
733                         block = parent_block;
734                         loc = l;
735                         target = label;
736                 }
737
738                 public string Target {
739                         get {
740                                 return target;
741                         }
742                 }
743
744                 protected override bool DoEmit (EmitContext ec)
745                 {
746                         Label l = label.LabelTarget (ec);
747                         ec.ig.Emit (OpCodes.Br, l);
748                         
749                         return false;
750                 }
751         }
752
753         public class LabeledStatement : Statement {
754                 public readonly Location Location;
755                 string label_name;
756                 bool defined;
757                 bool referenced;
758                 Label label;
759
760                 ArrayList vectors;
761                 
762                 public LabeledStatement (string label_name, Location l)
763                 {
764                         this.label_name = label_name;
765                         this.Location = l;
766                 }
767
768                 public Label LabelTarget (EmitContext ec)
769                 {
770                         if (defined)
771                                 return label;
772                         label = ec.ig.DefineLabel ();
773                         defined = true;
774
775                         return label;
776                 }
777
778                 public bool IsDefined {
779                         get {
780                                 return defined;
781                         }
782                 }
783
784                 public bool HasBeenReferenced {
785                         get {
786                                 return referenced;
787                         }
788                 }
789
790                 public void AddUsageVector (FlowBranching.UsageVector vector)
791                 {
792                         if (vectors == null)
793                                 vectors = new ArrayList ();
794
795                         vectors.Add (vector.Clone ());
796                 }
797
798                 public override bool Resolve (EmitContext ec)
799                 {
800                         if (vectors != null)
801                                 ec.CurrentBranching.CurrentUsageVector.MergeJumpOrigins (vectors);
802                         else {
803                                 ec.CurrentBranching.CurrentUsageVector.Breaks = FlowReturns.NEVER;
804                                 ec.CurrentBranching.CurrentUsageVector.Returns = FlowReturns.NEVER;
805                         }
806
807                         referenced = true;
808
809                         return true;
810                 }
811
812                 protected override bool DoEmit (EmitContext ec)
813                 {
814                         LabelTarget (ec);
815                         ec.ig.MarkLabel (label);
816
817                         return false;
818                 }
819         }
820         
821
822         /// <summary>
823         ///   `goto default' statement
824         /// </summary>
825         public class GotoDefault : Statement {
826                 
827                 public GotoDefault (Location l)
828                 {
829                         loc = l;
830                 }
831
832                 public override bool Resolve (EmitContext ec)
833                 {
834                         ec.CurrentBranching.CurrentUsageVector.Breaks = FlowReturns.UNREACHABLE;
835                         return true;
836                 }
837
838                 protected override bool DoEmit (EmitContext ec)
839                 {
840                         if (ec.Switch == null){
841                                 Report.Error (153, loc, "goto default is only valid in a switch statement");
842                                 return false;
843                         }
844
845                         if (!ec.Switch.GotDefault){
846                                 Report.Error (30132, loc, "No default target on switch statement");
847                                 return false;
848                         }
849                         ec.ig.Emit (OpCodes.Br, ec.Switch.DefaultTarget);
850                         return false;
851                 }
852         }
853
854         /// <summary>
855         ///   `goto case' statement
856         /// </summary>
857         public class GotoCase : Statement {
858                 Expression expr;
859                 Label label;
860                 
861                 public GotoCase (Expression e, Location l)
862                 {
863                         expr = e;
864                         loc = l;
865                 }
866
867                 public override bool Resolve (EmitContext ec)
868                 {
869                         if (ec.Switch == null){
870                                 Report.Error (153, loc, "goto case is only valid in a switch statement");
871                                 return false;
872                         }
873
874                         expr = expr.Resolve (ec);
875                         if (expr == null)
876                                 return false;
877
878                         if (!(expr is Constant)){
879                                 Report.Error (30132, loc, "Target expression for goto case is not constant");
880                                 return false;
881                         }
882
883                         object val = Expression.ConvertIntLiteral (
884                                 (Constant) expr, ec.Switch.SwitchType, loc);
885
886                         if (val == null)
887                                 return false;
888                                         
889                         SwitchLabel sl = (SwitchLabel) ec.Switch.Elements [val];
890
891                         if (sl == null){
892                                 Report.Error (
893                                         30132, loc,
894                                         "No such label 'case " + val + "': for the goto case");
895                         }
896
897                         label = sl.ILLabelCode;
898
899                         ec.CurrentBranching.CurrentUsageVector.Breaks = FlowReturns.UNREACHABLE;
900                         return true;
901                 }
902
903                 protected override bool DoEmit (EmitContext ec)
904                 {
905                         ec.ig.Emit (OpCodes.Br, label);
906                         return true;
907                 }
908         }
909         
910         public class Throw : Statement {
911                 Expression expr;
912                 
913                 public Throw (Expression expr, Location l)
914                 {
915                         this.expr = expr;
916                         loc = l;
917                 }
918
919                 public override bool Resolve (EmitContext ec)
920                 {
921                         if (expr != null){
922                                 expr = expr.Resolve (ec);
923                                 if (expr == null)
924                                         return false;
925
926                                 ExprClass eclass = expr.eclass;
927
928                                 if (!(eclass == ExprClass.Variable || eclass == ExprClass.PropertyAccess ||
929                                       eclass == ExprClass.Value || eclass == ExprClass.IndexerAccess)) {
930                                         expr.Error118 ("value, variable, property or indexer access ");
931                                         return false;
932                                 }
933
934                                 Type t = expr.Type;
935                                 
936                                 if ((t != TypeManager.exception_type) &&
937                                     !t.IsSubclassOf (TypeManager.exception_type) &&
938                                     !(expr is NullLiteral)) {
939                                         Report.Error (30665, loc,
940                                                       "The type caught or thrown must be derived " +
941                                                       "from System.Exception");
942                                         return false;
943                                 }
944                         }
945
946                         ec.CurrentBranching.CurrentUsageVector.Returns = FlowReturns.EXCEPTION;
947                         ec.CurrentBranching.CurrentUsageVector.Breaks = FlowReturns.EXCEPTION;
948                         return true;
949                 }
950                         
951                 protected override bool DoEmit (EmitContext ec)
952                 {
953                         if (expr == null){
954                                 if (ec.InCatch)
955                                         ec.ig.Emit (OpCodes.Rethrow);
956                                 else {
957                                         Report.Error (
958                                                 156, loc,
959                                                 "A throw statement with no argument is only " +
960                                                 "allowed in a catch clause");
961                                 }
962                                 return false;
963                         }
964
965                         expr.Emit (ec);
966
967                         ec.ig.Emit (OpCodes.Throw);
968
969                         return true;
970                 }
971         }
972
973         // Support 'End' Statement which terminates execution immediately
974
975           public class End : Statement {
976
977                 public End (Location l)
978                 {
979                         loc = l;
980                 }
981
982                 public override bool Resolve (EmitContext ec)
983                 {
984                         return true;
985                 }
986
987                 protected override bool DoEmit (EmitContext ec)
988                 {
989                         Expression e = null;
990                         Expression tmp = Mono.MonoBASIC.Parser.DecomposeQI (
991                                                 "Microsoft.VisualBasic.CompilerServices.ProjectData.EndApp",
992                                                         Location.Null);
993
994                        e = new Invocation (tmp, null, loc);
995                        e.Resolve (ec);
996
997                         if (e == null)
998                                 return false;
999                         e.Emit (ec);
1000
1001                         return true;
1002                 }
1003         }
1004
1005
1006         public class Break : Statement {
1007                 
1008                 public Break (Location l)
1009                 {
1010                         loc = l;
1011                 }
1012
1013                 public override bool Resolve (EmitContext ec)
1014                 {
1015                         ec.CurrentBranching.MayLeaveLoop = true;
1016                         ec.CurrentBranching.CurrentUsageVector.Breaks = FlowReturns.ALWAYS;
1017                         return true;
1018                 }
1019
1020                 protected override bool DoEmit (EmitContext ec)
1021                 {
1022                         ILGenerator ig = ec.ig;
1023
1024                         if (ec.InLoop == false && ec.Switch == null){
1025                                 Report.Error (139, loc, "No enclosing loop or switch to continue to");
1026                                 return false;
1027                         }
1028
1029                         if (ec.InTry || ec.InCatch)
1030                                 ig.Emit (OpCodes.Leave, ec.LoopEnd);
1031                         else
1032                                 ig.Emit (OpCodes.Br, ec.LoopEnd);
1033
1034                         return false;
1035                 }
1036         }
1037         
1038         public enum ExitType {
1039                 DO, 
1040                 FOR, 
1041                 WHILE,
1042                 SELECT,
1043                 SUB,
1044                 FUNCTION,
1045                 PROPERTY,
1046                 TRY                     
1047         };
1048         
1049         public class Exit : Statement {
1050                 public readonly ExitType type;
1051                 public Exit (ExitType t, Location l)
1052                 {
1053                         loc = l;
1054                         type = t;
1055                 }
1056
1057                 public override bool Resolve (EmitContext ec)
1058                 {
1059                         ec.CurrentBranching.MayLeaveLoop = true;
1060                         ec.CurrentBranching.CurrentUsageVector.Breaks = FlowReturns.ALWAYS;
1061                         return true;
1062                 }
1063
1064                 protected override bool DoEmit (EmitContext ec)
1065                 {
1066                         ILGenerator ig = ec.ig;
1067
1068                         if (type != ExitType.SUB && type != ExitType.FUNCTION && 
1069                                 type != ExitType.PROPERTY && type != ExitType.TRY) {
1070                                 if (ec.InLoop == false && ec.Switch == null){
1071                                         if (type == ExitType.FOR)
1072                                                 Report.Error (30096, loc, "No enclosing FOR loop to exit from");
1073                                         if (type == ExitType.WHILE) \r
1074                                                 Report.Error (30097, loc, "No enclosing WHILE loop to exit from");
1075                                         if (type == ExitType.DO)
1076                                                 Report.Error (30089, loc, "No enclosing DO loop to exit from");
1077                                         if (type == ExitType.SELECT)
1078                                                 Report.Error (30099, loc, "No enclosing SELECT to exit from");
1079
1080                                         return false;
1081                                 }
1082
1083                                 if (ec.InTry || ec.InCatch)
1084                                         ig.Emit (OpCodes.Leave, ec.LoopEnd);
1085                                 else
1086                                         ig.Emit (OpCodes.Br, ec.LoopEnd);
1087                         } else {                        
1088                                 if (ec.InFinally){
1089                                         Report.Error (30393, loc, 
1090                                                 "Control can not leave the body of the finally block");
1091                                         return false;
1092                                 }
1093                         
1094                                 if (ec.InTry || ec.InCatch) {
1095                                         if (!ec.HasReturnLabel) {
1096                                                 ec.ReturnLabel = ec.ig.DefineLabel ();
1097                                                 ec.HasReturnLabel = true;
1098                                         }
1099                                         ec.ig.Emit (OpCodes.Leave, ec.ReturnLabel);
1100                                 } else
1101                                         ec.ig.Emit (OpCodes.Ret);
1102
1103                                 return true; 
1104                         }
1105                         
1106                         return false;
1107                 }
1108         }       
1109
1110         public class Continue : Statement {
1111                 
1112                 public Continue (Location l)
1113                 {
1114                         loc = l;
1115                 }
1116
1117                 public override bool Resolve (EmitContext ec)
1118                 {
1119                         ec.CurrentBranching.CurrentUsageVector.Breaks = FlowReturns.ALWAYS;
1120                         return true;
1121                 }
1122
1123                 protected override bool DoEmit (EmitContext ec)
1124                 {
1125                         Label begin = ec.LoopBegin;
1126                         
1127                         if (!ec.InLoop){
1128                                 Report.Error (139, loc, "No enclosing loop to continue to");
1129                                 return false;
1130                         } 
1131
1132                         //
1133                         // UGH: Non trivial.  This Br might cross a try/catch boundary
1134                         // How can we tell?
1135                         //
1136                         // while () {
1137                         //   try { ... } catch { continue; }
1138                         // }
1139                         //
1140                         // From:
1141                         // try {} catch { while () { continue; }}
1142                         //
1143                         if (ec.TryCatchLevel > ec.LoopBeginTryCatchLevel)
1144                                 ec.ig.Emit (OpCodes.Leave, begin);
1145                         else if (ec.TryCatchLevel < ec.LoopBeginTryCatchLevel)
1146                                 throw new Exception ("Should never happen");
1147                         else
1148                                 ec.ig.Emit (OpCodes.Br, begin);
1149                         return false;
1150                 }
1151         }
1152
1153         // <summary>
1154         //   This is used in the control flow analysis code to specify whether the
1155         //   current code block may return to its enclosing block before reaching
1156         //   its end.
1157         // </summary>
1158         public enum FlowReturns {
1159                 // It can never return.
1160                 NEVER,
1161
1162                 // This means that the block contains a conditional return statement
1163                 // somewhere.
1164                 SOMETIMES,
1165
1166                 // The code always returns, ie. there's an unconditional return / break
1167                 // statement in it.
1168                 ALWAYS,
1169
1170                 // The code always throws an exception.
1171                 EXCEPTION,
1172
1173                 // The current code block is unreachable.  This happens if it's immediately
1174                 // following a FlowReturns.ALWAYS block.
1175                 UNREACHABLE
1176         }
1177
1178         // <summary>
1179         //   This is a special bit vector which can inherit from another bit vector doing a
1180         //   copy-on-write strategy.  The inherited vector may have a smaller size than the
1181         //   current one.
1182         // </summary>
1183         public class MyBitVector {
1184                 public readonly int Count;
1185                 public readonly MyBitVector InheritsFrom;
1186
1187                 bool is_dirty;
1188                 BitArray vector;
1189
1190                 public MyBitVector (int Count)
1191                         : this (null, Count)
1192                 { }
1193
1194                 public MyBitVector (MyBitVector InheritsFrom, int Count)
1195                 {
1196                         this.InheritsFrom = InheritsFrom;
1197                         this.Count = Count;
1198                 }
1199
1200                 // <summary>
1201                 //   Checks whether this bit vector has been modified.  After setting this to true,
1202                 //   we won't use the inherited vector anymore, but our own copy of it.
1203                 // </summary>
1204                 public bool IsDirty {
1205                         get {
1206                                 return is_dirty;
1207                         }
1208
1209                         set {
1210                                 if (!is_dirty)
1211                                         initialize_vector ();
1212                         }
1213                 }
1214
1215                 // <summary>
1216                 //   Get/set bit `index' in the bit vector.
1217                 // </summary>
1218                 public bool this [int index]
1219                 {
1220                         get {
1221                                 if (index > Count)
1222                                         throw new ArgumentOutOfRangeException ();
1223
1224                                 // We're doing a "copy-on-write" strategy here; as long
1225                                 // as nobody writes to the array, we can use our parent's
1226                                 // copy instead of duplicating the vector.
1227
1228                                 if (vector != null)
1229                                         return vector [index];
1230                                 else if (InheritsFrom != null) {
1231                                         BitArray inherited = InheritsFrom.Vector;
1232
1233                                         if (index < inherited.Count)
1234                                                 return inherited [index];
1235                                         else
1236                                                 return false;
1237                                 } else
1238                                         return false;
1239                         }
1240
1241                         set {
1242                                 if (index > Count)
1243                                         throw new ArgumentOutOfRangeException ();
1244
1245                                 // Only copy the vector if we're actually modifying it.
1246
1247                                 if (this [index] != value) {
1248                                         initialize_vector ();
1249
1250                                         vector [index] = value;
1251                                 }
1252                         }
1253                 }
1254
1255                 // <summary>
1256                 //   If you explicitly convert the MyBitVector to a BitArray, you will get a deep
1257                 //   copy of the bit vector.
1258                 // </summary>
1259                 public static explicit operator BitArray (MyBitVector vector)
1260                 {
1261                         vector.initialize_vector ();
1262                         return vector.Vector;
1263                 }
1264
1265                 // <summary>
1266                 //   Performs an `or' operation on the bit vector.  The `new_vector' may have a
1267                 //   different size than the current one.
1268                 // </summary>
1269                 public void Or (MyBitVector new_vector)
1270                 {
1271                         BitArray new_array = new_vector.Vector;
1272
1273                         initialize_vector ();
1274
1275                         int upper;
1276                         if (vector.Count < new_array.Count)
1277                                 upper = vector.Count;
1278                         else
1279                                 upper = new_array.Count;
1280
1281                         for (int i = 0; i < upper; i++)
1282                                 vector [i] = vector [i] | new_array [i];
1283                 }
1284
1285                 // <summary>
1286                 //   Perfonrms an `and' operation on the bit vector.  The `new_vector' may have
1287                 //   a different size than the current one.
1288                 // </summary>
1289                 public void And (MyBitVector new_vector)
1290                 {
1291                         BitArray new_array = new_vector.Vector;
1292
1293                         initialize_vector ();
1294
1295                         int lower, upper;
1296                         if (vector.Count < new_array.Count)
1297                                 lower = upper = vector.Count;
1298                         else {
1299                                 lower = new_array.Count;
1300                                 upper = vector.Count;
1301                         }
1302
1303                         for (int i = 0; i < lower; i++)
1304                                 vector [i] = vector [i] & new_array [i];
1305
1306                         for (int i = lower; i < upper; i++)
1307                                 vector [i] = false;
1308                 }
1309
1310                 // <summary>
1311                 //   This does a deep copy of the bit vector.
1312                 // </summary>
1313                 public MyBitVector Clone ()
1314                 {
1315                         MyBitVector retval = new MyBitVector (Count);
1316
1317                         retval.Vector = Vector;
1318
1319                         return retval;
1320                 }
1321
1322                 BitArray Vector {
1323                         get {
1324                                 if (vector != null)
1325                                         return vector;
1326                                 else if (!is_dirty && (InheritsFrom != null))
1327                                         return InheritsFrom.Vector;
1328
1329                                 initialize_vector ();
1330
1331                                 return vector;
1332                         }
1333
1334                         set {
1335                                 initialize_vector ();
1336
1337                                 for (int i = 0; i < System.Math.Min (vector.Count, value.Count); i++)
1338                                         vector [i] = value [i];
1339                         }
1340                 }
1341
1342                 void initialize_vector ()
1343                 {
1344                         if (vector != null)
1345                                 return;
1346
1347                         vector = new BitArray (Count, false);
1348                         if (InheritsFrom != null)
1349                                 Vector = InheritsFrom.Vector;
1350
1351                         is_dirty = true;
1352                 }
1353
1354                 public override string ToString ()
1355                 {
1356                         StringBuilder sb = new StringBuilder ("MyBitVector (");
1357
1358                         BitArray vector = Vector;
1359                         sb.Append (Count);
1360                         sb.Append (",");
1361                         if (!IsDirty)
1362                                 sb.Append ("INHERITED - ");
1363                         for (int i = 0; i < vector.Count; i++) {
1364                                 if (i > 0)
1365                                         sb.Append (",");
1366                                 sb.Append (vector [i]);
1367                         }
1368                         
1369                         sb.Append (")");
1370                         return sb.ToString ();
1371                 }
1372         }
1373
1374         // <summary>
1375         //   The type of a FlowBranching.
1376         // </summary>
1377         public enum FlowBranchingType {
1378                 // Normal (conditional or toplevel) block.
1379                 BLOCK,
1380
1381                 // A loop block.
1382                 LOOP_BLOCK,
1383
1384                 // Try/Catch block.
1385                 EXCEPTION,
1386
1387                 // Switch block.
1388                 SWITCH,
1389
1390                 // Switch section.
1391                 SWITCH_SECTION
1392         }
1393
1394         // <summary>
1395         //   A new instance of this class is created every time a new block is resolved
1396         //   and if there's branching in the block's control flow.
1397         // </summary>
1398         public class FlowBranching {
1399                 // <summary>
1400                 //   The type of this flow branching.
1401                 // </summary>
1402                 public readonly FlowBranchingType Type;
1403
1404                 // <summary>
1405                 //   The block this branching is contained in.  This may be null if it's not
1406                 //   a top-level block and it doesn't declare any local variables.
1407                 // </summary>
1408                 public readonly Block Block;
1409
1410                 // <summary>
1411                 //   The parent of this branching or null if this is the top-block.
1412                 // </summary>
1413                 public readonly FlowBranching Parent;
1414
1415                 // <summary>
1416                 //   Start-Location of this flow branching.
1417                 // </summary>
1418                 public readonly Location Location;
1419
1420                 // <summary>
1421                 //   A list of UsageVectors.  A new vector is added each time control flow may
1422                 //   take a different path.
1423                 // </summary>
1424                 public ArrayList Siblings;
1425
1426                 // <summary>
1427                 //   If this is an infinite loop.
1428                 // </summary>
1429                 public bool Infinite;
1430
1431                 // <summary>
1432                 //   If we may leave the current loop.
1433                 // </summary>
1434                 public bool MayLeaveLoop;
1435
1436                 //
1437                 // Private
1438                 //
1439                 InternalParameters param_info;
1440                 int[] param_map;
1441                 MyStructInfo[] struct_params;
1442                 int num_params;
1443                 ArrayList finally_vectors;
1444
1445                 static int next_id = 0;
1446                 int id;
1447
1448                 // <summary>
1449                 //   Performs an `And' operation on the FlowReturns status
1450                 //   (for instance, a block only returns ALWAYS if all its siblings
1451                 //   always return).
1452                 // </summary>
1453                 public static FlowReturns AndFlowReturns (FlowReturns a, FlowReturns b)
1454                 {
1455                         if (b == FlowReturns.UNREACHABLE)
1456                                 return a;
1457
1458                         switch (a) {
1459                         case FlowReturns.NEVER:
1460                                 if (b == FlowReturns.NEVER)
1461                                         return FlowReturns.NEVER;
1462                                 else
1463                                         return FlowReturns.SOMETIMES;
1464
1465                         case FlowReturns.SOMETIMES:
1466                                 return FlowReturns.SOMETIMES;
1467
1468                         case FlowReturns.ALWAYS:
1469                                 if ((b == FlowReturns.ALWAYS) || (b == FlowReturns.EXCEPTION))
1470                                         return FlowReturns.ALWAYS;
1471                                 else
1472                                         return FlowReturns.SOMETIMES;
1473
1474                         case FlowReturns.EXCEPTION:
1475                                 if (b == FlowReturns.EXCEPTION)
1476                                         return FlowReturns.EXCEPTION;
1477                                 else if (b == FlowReturns.ALWAYS)
1478                                         return FlowReturns.ALWAYS;
1479                                 else
1480                                         return FlowReturns.SOMETIMES;
1481                         }
1482
1483                         return b;
1484                 }
1485
1486                 // <summary>
1487                 //   The vector contains a BitArray with information about which local variables
1488                 //   and parameters are already initialized at the current code position.
1489                 // </summary>
1490                 public class UsageVector {
1491                         // <summary>
1492                         //   If this is true, then the usage vector has been modified and must be
1493                         //   merged when we're done with this branching.
1494                         // </summary>
1495                         public bool IsDirty;
1496
1497                         // <summary>
1498                         //   The number of parameters in this block.
1499                         // </summary>
1500                         public readonly int CountParameters;
1501
1502                         // <summary>
1503                         //   The number of locals in this block.
1504                         // </summary>
1505                         public readonly int CountLocals;
1506
1507                         // <summary>
1508                         //   If not null, then we inherit our state from this vector and do a
1509                         //   copy-on-write.  If null, then we're the first sibling in a top-level
1510                         //   block and inherit from the empty vector.
1511                         // </summary>
1512                         public readonly UsageVector InheritsFrom;
1513
1514                         //
1515                         // Private.
1516                         //
1517                         MyBitVector locals, parameters;
1518                         FlowReturns real_returns, real_breaks;
1519                         bool is_finally;
1520
1521                         static int next_id = 0;
1522                         int id;
1523
1524                         //
1525                         // Normally, you should not use any of these constructors.
1526                         //
1527                         public UsageVector (UsageVector parent, int num_params, int num_locals)
1528                         {
1529                                 this.InheritsFrom = parent;
1530                                 this.CountParameters = num_params;
1531                                 this.CountLocals = num_locals;
1532                                 this.real_returns = FlowReturns.NEVER;
1533                                 this.real_breaks = FlowReturns.NEVER;
1534
1535                                 if (parent != null) {
1536                                         locals = new MyBitVector (parent.locals, CountLocals);
1537                                         if (num_params > 0)
1538                                                 parameters = new MyBitVector (parent.parameters, num_params);
1539                                         real_returns = parent.Returns;
1540                                         real_breaks = parent.Breaks;
1541                                 } else {
1542                                         locals = new MyBitVector (null, CountLocals);
1543                                         if (num_params > 0)
1544                                                 parameters = new MyBitVector (null, num_params);
1545                                 }
1546
1547                                 id = ++next_id;
1548                         }
1549
1550                         public UsageVector (UsageVector parent)
1551                                 : this (parent, parent.CountParameters, parent.CountLocals)
1552                         { }
1553
1554                         // <summary>
1555                         //   This does a deep copy of the usage vector.
1556                         // </summary>
1557                         public UsageVector Clone ()
1558                         {
1559                                 UsageVector retval = new UsageVector (null, CountParameters, CountLocals);
1560
1561                                 retval.locals = locals.Clone ();
1562                                 if (parameters != null)
1563                                         retval.parameters = parameters.Clone ();
1564                                 retval.real_returns = real_returns;
1565                                 retval.real_breaks = real_breaks;
1566
1567                                 return retval;
1568                         }
1569
1570                         // 
1571                         // State of parameter `number'.
1572                         //
1573                         public bool this [int number]
1574                         {
1575                                 get {
1576                                         if (number == -1)
1577                                                 return true;
1578                                         else if (number == 0)
1579                                                 throw new ArgumentException ();
1580
1581                                         return parameters [number - 1];
1582                                 }
1583
1584                                 set {
1585                                         if (number == -1)
1586                                                 return;
1587                                         else if (number == 0)
1588                                                 throw new ArgumentException ();
1589
1590                                         parameters [number - 1] = value;
1591                                 }
1592                         }
1593
1594                         //
1595                         // State of the local variable `vi'.
1596                         // If the local variable is a struct, use a non-zero `field_idx'
1597                         // to check an individual field in it.
1598                         //
1599                         public bool this [VariableInfo vi, int field_idx]
1600                         {
1601                                 get {
1602                                         if (vi.Number == -1)
1603                                                 return true;
1604                                         else if (vi.Number == 0)
1605                                                 throw new ArgumentException ();
1606
1607                                         return locals [vi.Number + field_idx - 1];
1608                                 }
1609
1610                                 set {
1611                                         if (vi.Number == -1)
1612                                                 return;
1613                                         else if (vi.Number == 0)
1614                                                 throw new ArgumentException ();
1615
1616                                         locals [vi.Number + field_idx - 1] = value;
1617                                 }
1618                         }
1619
1620                         // <summary>
1621                         //   Specifies when the current block returns.
1622                         //   If this is FlowReturns.UNREACHABLE, then control can never reach the
1623                         //   end of the method (so that we don't need to emit a return statement).
1624                         //   The same applies for FlowReturns.EXCEPTION, but in this case the return
1625                         //   value will never be used.
1626                         // </summary>
1627                         public FlowReturns Returns {
1628                                 get {
1629                                         return real_returns;
1630                                 }
1631
1632                                 set {
1633                                         real_returns = value;
1634                                 }
1635                         }
1636
1637                         // <summary>
1638                         //   Specifies whether control may return to our containing block
1639                         //   before reaching the end of this block.  This happens if there
1640                         //   is a break/continue/goto/return in it.
1641                         //   This can also be used to find out whether the statement immediately
1642                         //   following the current block may be reached or not.
1643                         // </summary>
1644                         public FlowReturns Breaks {
1645                                 get {
1646                                         return real_breaks;
1647                                 }
1648
1649                                 set {
1650                                         real_breaks = value;
1651                                 }
1652                         }
1653
1654                         public bool AlwaysBreaks {
1655                                 get {
1656                                         return (Breaks == FlowReturns.ALWAYS) ||
1657                                                 (Breaks == FlowReturns.EXCEPTION) ||
1658                                                 (Breaks == FlowReturns.UNREACHABLE);
1659                                 }
1660                         }
1661
1662                         public bool MayBreak {
1663                                 get {
1664                                         return Breaks != FlowReturns.NEVER;
1665                                 }
1666                         }
1667
1668                         public bool AlwaysReturns {
1669                                 get {
1670                                         return (Returns == FlowReturns.ALWAYS) ||
1671                                                 (Returns == FlowReturns.EXCEPTION);
1672                                 }
1673                         }
1674
1675                         public bool MayReturn {
1676                                 get {
1677                                         return (Returns == FlowReturns.SOMETIMES) ||
1678                                                 (Returns == FlowReturns.ALWAYS);
1679                                 }
1680                         }
1681
1682                         // <summary>
1683                         //   Merge a child branching.
1684                         // </summary>
1685                         public FlowReturns MergeChildren (FlowBranching branching, ICollection children)
1686                         {
1687                                 MyBitVector new_locals = null;
1688                                 MyBitVector new_params = null;
1689
1690                                 FlowReturns new_returns = FlowReturns.NEVER;
1691                                 FlowReturns new_breaks = FlowReturns.NEVER;
1692                                 bool new_returns_set = false, new_breaks_set = false;
1693
1694                                 Report.Debug (2, "MERGING CHILDREN", branching, branching.Type,
1695                                               this, children.Count);
1696
1697                                 foreach (UsageVector child in children) {
1698                                         Report.Debug (2, "  MERGING CHILD", child, child.is_finally);
1699                                         
1700                                         if (!child.is_finally) {
1701                                                 if (child.Breaks != FlowReturns.UNREACHABLE) {
1702                                                         // If Returns is already set, perform an
1703                                                         // `And' operation on it, otherwise just set just.
1704                                                         if (!new_returns_set) {
1705                                                                 new_returns = child.Returns;
1706                                                                 new_returns_set = true;
1707                                                         } else
1708                                                                 new_returns = AndFlowReturns (
1709                                                                         new_returns, child.Returns);
1710                                                 }
1711
1712                                                 // If Breaks is already set, perform an
1713                                                 // `And' operation on it, otherwise just set just.
1714                                                 if (!new_breaks_set) {
1715                                                         new_breaks = child.Breaks;
1716                                                         new_breaks_set = true;
1717                                                 } else
1718                                                         new_breaks = AndFlowReturns (
1719                                                                 new_breaks, child.Breaks);
1720                                         }
1721
1722                                         // Ignore unreachable children.
1723                                         if (child.Returns == FlowReturns.UNREACHABLE)
1724                                                 continue;
1725
1726                                         // A local variable is initialized after a flow branching if it
1727                                         // has been initialized in all its branches which do neither
1728                                         // always return or always throw an exception.
1729                                         //
1730                                         // If a branch may return, but does not always return, then we
1731                                         // can treat it like a never-returning branch here: control will
1732                                         // only reach the code position after the branching if we did not
1733                                         // return here.
1734                                         //
1735                                         // It's important to distinguish between always and sometimes
1736                                         // returning branches here:
1737                                         //
1738                                         //    1   int a;
1739                                         //    2   if (something) {
1740                                         //    3      return;
1741                                         //    4      a = 5;
1742                                         //    5   }
1743                                         //    6   Console.WriteLine (a);
1744                                         //
1745                                         // The if block in lines 3-4 always returns, so we must not look
1746                                         // at the initialization of `a' in line 4 - thus it'll still be
1747                                         // uninitialized in line 6.
1748                                         //
1749                                         // On the other hand, the following is allowed:
1750                                         //
1751                                         //    1   int a;
1752                                         //    2   if (something)
1753                                         //    3      a = 5;
1754                                         //    4   else
1755                                         //    5      return;
1756                                         //    6   Console.WriteLine (a);
1757                                         //
1758                                         // Here, `a' is initialized in line 3 and we must not look at
1759                                         // line 5 since it always returns.
1760                                         // 
1761                                         if (child.is_finally) {
1762                                                 if (new_locals == null)
1763                                                         new_locals = locals.Clone ();
1764                                                 new_locals.Or (child.locals);
1765
1766                                                 if (parameters != null) {
1767                                                         if (new_params == null)
1768                                                                 new_params = parameters.Clone ();
1769                                                         new_params.Or (child.parameters);
1770                                                 }
1771
1772                                         } else {
1773                                                 if (!child.AlwaysReturns && !child.AlwaysBreaks) {
1774                                                         if (new_locals != null)
1775                                                                 new_locals.And (child.locals);
1776                                                         else {
1777                                                                 new_locals = locals.Clone ();
1778                                                                 new_locals.Or (child.locals);
1779                                                         }
1780                                                 } else if (children.Count == 1) {
1781                                                         new_locals = locals.Clone ();
1782                                                         new_locals.Or (child.locals);
1783                                                 }
1784
1785                                                 // An `out' parameter must be assigned in all branches which do
1786                                                 // not always throw an exception.
1787                                                 if (parameters != null) {
1788                                                         if (child.Breaks != FlowReturns.EXCEPTION) {
1789                                                                 if (new_params != null)
1790                                                                         new_params.And (child.parameters);
1791                                                                 else {
1792                                                                         new_params = parameters.Clone ();
1793                                                                         new_params.Or (child.parameters);
1794                                                                 }
1795                                                         } else if (children.Count == 1) {
1796                                                                 new_params = parameters.Clone ();
1797                                                                 new_params.Or (child.parameters);
1798                                                         }
1799                                                 }
1800                                         }
1801                                 }
1802
1803                                 Returns = new_returns;
1804                                 if ((branching.Type == FlowBranchingType.BLOCK) ||
1805                                     (branching.Type == FlowBranchingType.EXCEPTION) ||
1806                                     (new_breaks == FlowReturns.UNREACHABLE) ||
1807                                     (new_breaks == FlowReturns.EXCEPTION))
1808                                         Breaks = new_breaks;
1809                                 else if (branching.Type == FlowBranchingType.SWITCH_SECTION)
1810                                         Breaks = new_returns;
1811                                 else if (branching.Type == FlowBranchingType.SWITCH){
1812                                         if (new_breaks == FlowReturns.ALWAYS)
1813                                                 Breaks = FlowReturns.ALWAYS;
1814                                 }
1815
1816                                 //
1817                                 // We've now either reached the point after the branching or we will
1818                                 // never get there since we always return or always throw an exception.
1819                                 //
1820                                 // If we can reach the point after the branching, mark all locals and
1821                                 // parameters as initialized which have been initialized in all branches
1822                                 // we need to look at (see above).
1823                                 //
1824
1825                                 if (((new_breaks != FlowReturns.ALWAYS) &&
1826                                      (new_breaks != FlowReturns.EXCEPTION) &&
1827                                      (new_breaks != FlowReturns.UNREACHABLE)) ||
1828                                     (children.Count == 1)) {
1829                                         if (new_locals != null)
1830                                                 locals.Or (new_locals);
1831
1832                                         if (new_params != null)
1833                                                 parameters.Or (new_params);
1834                                 }
1835
1836                                 Report.Debug (2, "MERGING CHILDREN DONE", branching.Type,
1837                                               new_params, new_locals, new_returns, new_breaks,
1838                                               branching.Infinite, branching.MayLeaveLoop, this);
1839
1840                                 if (branching.Type == FlowBranchingType.SWITCH_SECTION) {
1841                                         if ((new_breaks != FlowReturns.ALWAYS) &&
1842                                             (new_breaks != FlowReturns.EXCEPTION) &&
1843                                             (new_breaks != FlowReturns.UNREACHABLE))
1844                                                 Report.Error (163, branching.Location,
1845                                                               "Control cannot fall through from one " +
1846                                                               "case label to another");
1847                                 }
1848
1849                                 if (branching.Infinite && !branching.MayLeaveLoop) {
1850                                         Report.Debug (1, "INFINITE", new_returns, new_breaks,
1851                                                       Returns, Breaks, this);
1852
1853                                         // We're actually infinite.
1854                                         if (new_returns == FlowReturns.NEVER) {
1855                                                 Breaks = FlowReturns.UNREACHABLE;
1856                                                 return FlowReturns.UNREACHABLE;
1857                                         }
1858
1859                                         // If we're an infinite loop and do not break, the code after
1860                                         // the loop can never be reached.  However, if we may return
1861                                         // from the loop, then we do always return (or stay in the loop
1862                                         // forever).
1863                                         if ((new_returns == FlowReturns.SOMETIMES) ||
1864                                             (new_returns == FlowReturns.ALWAYS)) {
1865                                                 Returns = FlowReturns.ALWAYS;
1866                                                 return FlowReturns.ALWAYS;
1867                                         }
1868                                 }
1869
1870                                 return new_returns;
1871                         }
1872
1873                         // <summary>
1874                         //   Tells control flow analysis that the current code position may be reached with
1875                         //   a forward jump from any of the origins listed in `origin_vectors' which is a
1876                         //   list of UsageVectors.
1877                         //
1878                         //   This is used when resolving forward gotos - in the following example, the
1879                         //   variable `a' is uninitialized in line 8 becase this line may be reached via
1880                         //   the goto in line 4:
1881                         //
1882                         //      1     int a;
1883                         //
1884                         //      3     if (something)
1885                         //      4        goto World;
1886                         //
1887                         //      6     a = 5;
1888                         //
1889                         //      7  World:
1890                         //      8     Console.WriteLine (a);
1891                         //
1892                         // </summary>
1893                         public void MergeJumpOrigins (ICollection origin_vectors)
1894                         {
1895                                 Report.Debug (1, "MERGING JUMP ORIGIN", this);
1896
1897                                 real_breaks = FlowReturns.NEVER;
1898                                 real_returns = FlowReturns.NEVER;
1899
1900                                 foreach (UsageVector vector in origin_vectors) {
1901                                         Report.Debug (1, "  MERGING JUMP ORIGIN", vector);
1902
1903                                         locals.And (vector.locals);
1904                                         if (parameters != null)
1905                                                 parameters.And (vector.parameters);
1906                                         Breaks = AndFlowReturns (Breaks, vector.Breaks);
1907                                         Returns = AndFlowReturns (Returns, vector.Returns);
1908                                 }
1909
1910                                 Report.Debug (1, "MERGING JUMP ORIGIN DONE", this);
1911                         }
1912
1913                         // <summary>
1914                         //   This is used at the beginning of a finally block if there were
1915                         //   any return statements in the try block or one of the catch blocks.
1916                         // </summary>
1917                         public void MergeFinallyOrigins (ICollection finally_vectors)
1918                         {
1919                                 Report.Debug (1, "MERGING FINALLY ORIGIN", this);
1920
1921                                 real_breaks = FlowReturns.NEVER;
1922
1923                                 foreach (UsageVector vector in finally_vectors) {
1924                                         Report.Debug (1, "  MERGING FINALLY ORIGIN", vector);
1925
1926                                         if (parameters != null)
1927                                                 parameters.And (vector.parameters);
1928                                         Breaks = AndFlowReturns (Breaks, vector.Breaks);
1929                                 }
1930
1931                                 is_finally = true;
1932
1933                                 Report.Debug (1, "MERGING FINALLY ORIGIN DONE", this);
1934                         }
1935
1936                         public void CheckOutParameters (FlowBranching branching)
1937                         {
1938                                 if (parameters != null)
1939                                         branching.CheckOutParameters (parameters, branching.Location);
1940                         }
1941
1942                         // <summary>
1943                         //   Performs an `or' operation on the locals and the parameters.
1944                         // </summary>
1945                         public void Or (UsageVector new_vector)
1946                         {
1947                                 locals.Or (new_vector.locals);
1948                                 if (parameters != null)
1949                                         parameters.Or (new_vector.parameters);
1950                         }
1951
1952                         // <summary>
1953                         //   Performs an `and' operation on the locals.
1954                         // </summary>
1955                         public void AndLocals (UsageVector new_vector)
1956                         {
1957                                 locals.And (new_vector.locals);
1958                         }
1959
1960                         // <summary>
1961                         //   Returns a deep copy of the parameters.
1962                         // </summary>
1963                         public MyBitVector Parameters {
1964                                 get {
1965                                         if (parameters != null)
1966                                                 return parameters.Clone ();
1967                                         else
1968                                                 return null;
1969                                 }
1970                         }
1971
1972                         // <summary>
1973                         //   Returns a deep copy of the locals.
1974                         // </summary>
1975                         public MyBitVector Locals {
1976                                 get {
1977                                         return locals.Clone ();
1978                                 }
1979                         }
1980
1981                         //
1982                         // Debugging stuff.
1983                         //
1984
1985                         public override string ToString ()
1986                         {
1987                                 StringBuilder sb = new StringBuilder ();
1988
1989                                 sb.Append ("Vector (");
1990                                 sb.Append (id);
1991                                 sb.Append (",");
1992                                 sb.Append (Returns);
1993                                 sb.Append (",");
1994                                 sb.Append (Breaks);
1995                                 if (parameters != null) {
1996                                         sb.Append (" - ");
1997                                         sb.Append (parameters);
1998                                 }
1999                                 sb.Append (" - ");
2000                                 sb.Append (locals);
2001                                 sb.Append (")");
2002
2003                                 return sb.ToString ();
2004                         }
2005                 }
2006
2007                 FlowBranching (FlowBranchingType type, Location loc)
2008                 {
2009                         this.Siblings = new ArrayList ();
2010                         this.Block = null;
2011                         this.Location = loc;
2012                         this.Type = type;
2013                         id = ++next_id;
2014                 }
2015
2016                 // <summary>
2017                 //   Creates a new flow branching for `block'.
2018                 //   This is used from Block.Resolve to create the top-level branching of
2019                 //   the block.
2020                 // </summary>
2021                 public FlowBranching (Block block, InternalParameters ip, Location loc)
2022                         : this (FlowBranchingType.BLOCK, loc)
2023                 {
2024                         Block = block;
2025                         Parent = null;
2026
2027                         int count = (ip != null) ? ip.Count : 0;
2028
2029                         param_info = ip;
2030                         param_map = new int [count];
2031                         struct_params = new MyStructInfo [count];
2032                         num_params = 0;
2033
2034                         for (int i = 0; i < count; i++) {
2035                                 Parameter.Modifier mod = param_info.ParameterModifier (i);
2036
2037                                 if ((mod & Parameter.Modifier.OUT) == 0)
2038                                         continue;
2039
2040                                 param_map [i] = ++num_params;
2041
2042                                 Type param_type = param_info.ParameterType (i);
2043
2044                                 struct_params [i] = MyStructInfo.GetStructInfo (param_type);
2045                                 if (struct_params [i] != null)
2046                                         num_params += struct_params [i].Count;
2047                         }
2048
2049                         Siblings = new ArrayList ();
2050                         Siblings.Add (new UsageVector (null, num_params, block.CountVariables));
2051                 }
2052
2053                 // <summary>
2054                 //   Creates a new flow branching which is contained in `parent'.
2055                 //   You should only pass non-null for the `block' argument if this block
2056                 //   introduces any new variables - in this case, we need to create a new
2057                 //   usage vector with a different size than our parent's one.
2058                 // </summary>
2059                 public FlowBranching (FlowBranching parent, FlowBranchingType type,
2060                                       Block block, Location loc)
2061                         : this (type, loc)
2062                 {
2063                         Parent = parent;
2064                         Block = block;
2065
2066                         if (parent != null) {
2067                                 param_info = parent.param_info;
2068                                 param_map = parent.param_map;
2069                                 struct_params = parent.struct_params;
2070                                 num_params = parent.num_params;
2071                         }
2072
2073                         UsageVector vector;
2074                         if (Block != null)
2075                                 vector = new UsageVector (parent.CurrentUsageVector, num_params,
2076                                                           Block.CountVariables);
2077                         else
2078                                 vector = new UsageVector (Parent.CurrentUsageVector);
2079
2080                         Siblings.Add (vector);
2081
2082                         switch (Type) {
2083                         case FlowBranchingType.EXCEPTION:
2084                                 finally_vectors = new ArrayList ();
2085                                 break;
2086
2087                         default:
2088                                 break;
2089                         }
2090                 }
2091
2092                 // <summary>
2093                 //   Returns the branching's current usage vector.
2094                 // </summary>
2095                 public UsageVector CurrentUsageVector
2096                 {
2097                         get {
2098                                 return (UsageVector) Siblings [Siblings.Count - 1];
2099                         }
2100                 }
2101
2102                 // <summary>
2103                 //   Creates a sibling of the current usage vector.
2104                 // </summary>
2105                 public void CreateSibling ()
2106                 {
2107                         Siblings.Add (new UsageVector (Parent.CurrentUsageVector));
2108
2109                         Report.Debug (1, "CREATED SIBLING", CurrentUsageVector);
2110                 }
2111
2112                 // <summary>
2113                 //   Creates a sibling for a `finally' block.
2114                 // </summary>
2115                 public void CreateSiblingForFinally ()
2116                 {
2117                         if (Type != FlowBranchingType.EXCEPTION)
2118                                 throw new NotSupportedException ();
2119
2120                         CreateSibling ();
2121
2122                         CurrentUsageVector.MergeFinallyOrigins (finally_vectors);
2123                 }
2124
2125                 // <summary>
2126                 //   Check whether all `out' parameters have been assigned.
2127                 // </summary>
2128                 public void CheckOutParameters (MyBitVector parameters, Location loc)
2129                 {
2130                         if (InTryBlock ())
2131                                 return;
2132
2133                         for (int i = 0; i < param_map.Length; i++) {
2134                                 int index = param_map [i];
2135
2136                                 if (index == 0)
2137                                         continue;
2138
2139                                 if (parameters [index - 1])
2140                                         continue;
2141
2142                                 // If it's a struct, we must ensure that all its fields have
2143                                 // been assigned.  If the struct has any non-public fields, this
2144                                 // can only be done by assigning the whole struct.
2145
2146                                 MyStructInfo struct_info = struct_params [index - 1];
2147                                 if ((struct_info == null) || struct_info.HasNonPublicFields) {
2148                                         Report.Error (
2149                                                 177, loc, "The out parameter `" +
2150                                                 param_info.ParameterName (i) + "' must be " +
2151                                                 "assigned before control leave the current method.");
2152                                         param_map [i] = 0;
2153                                         continue;
2154                                 }
2155
2156
2157                                 for (int j = 0; j < struct_info.Count; j++) {
2158                                         if (!parameters [index + j]) {
2159                                                 Report.Error (
2160                                                         177, loc, "The out parameter `" +
2161                                                         param_info.ParameterName (i) + "' must be " +
2162                                                         "assigned before control leave the current method.");
2163                                                 param_map [i] = 0;
2164                                                 break;
2165                                         }
2166                                 }
2167                         }
2168                 }
2169
2170                 // <summary>
2171                 //   Merge a child branching.
2172                 // </summary>
2173                 public FlowReturns MergeChild (FlowBranching child)
2174                 {
2175                         FlowReturns returns = CurrentUsageVector.MergeChildren (child, child.Siblings);
2176
2177                         if (child.Type != FlowBranchingType.LOOP_BLOCK)
2178                                 MayLeaveLoop |= child.MayLeaveLoop;
2179                         else
2180                                 MayLeaveLoop = false;
2181
2182                         return returns;
2183                 }
2184  
2185                 // <summary>
2186                 //   Does the toplevel merging.
2187                 // </summary>
2188                 public FlowReturns MergeTopBlock ()
2189                 {
2190                         if ((Type != FlowBranchingType.BLOCK) || (Block == null))
2191                                 throw new NotSupportedException ();
2192
2193                         UsageVector vector = new UsageVector (null, num_params, Block.CountVariables);
2194
2195                         Report.Debug (1, "MERGING TOP BLOCK", Location, vector);
2196
2197                         vector.MergeChildren (this, Siblings);
2198
2199                         Siblings.Clear ();
2200                         Siblings.Add (vector);
2201
2202                         Report.Debug (1, "MERGING TOP BLOCK DONE", Location, vector);
2203
2204                         if (vector.Breaks != FlowReturns.EXCEPTION) {
2205                                 if (!vector.AlwaysBreaks)
2206                                         CheckOutParameters (CurrentUsageVector.Parameters, Location);
2207                                 return vector.AlwaysBreaks ? FlowReturns.ALWAYS : vector.Returns;
2208                         } else
2209                                 return FlowReturns.EXCEPTION;
2210                 }
2211
2212                 public bool InTryBlock ()
2213                 {
2214                         if (finally_vectors != null)
2215                                 return true;
2216                         else if (Parent != null)
2217                                 return Parent.InTryBlock ();
2218                         else
2219                                 return false;
2220                 }
2221
2222                 public void AddFinallyVector (UsageVector vector)
2223                 {
2224                         if (finally_vectors != null) {
2225                                 finally_vectors.Add (vector.Clone ());
2226                                 return;
2227                         }
2228
2229                         if (Parent != null)
2230                                 Parent.AddFinallyVector (vector);
2231                         else
2232                                 throw new NotSupportedException ();
2233                 }
2234
2235                 public bool IsVariableAssigned (VariableInfo vi)
2236                 {
2237                         if (CurrentUsageVector.AlwaysBreaks)
2238                                 return true;
2239                         else
2240                                 return CurrentUsageVector [vi, 0];
2241                 }
2242
2243                 public bool IsVariableAssigned (VariableInfo vi, int field_idx)
2244                 {
2245                         if (CurrentUsageVector.AlwaysBreaks)
2246                                 return true;
2247                         else
2248                                 return CurrentUsageVector [vi, field_idx];
2249                 }
2250
2251                 public void SetVariableAssigned (VariableInfo vi)
2252                 {
2253                         if (CurrentUsageVector.AlwaysBreaks)
2254                                 return;
2255
2256                         CurrentUsageVector [vi, 0] = true;
2257                 }
2258
2259                 public void SetVariableAssigned (VariableInfo vi, int field_idx)
2260                 {
2261                         if (CurrentUsageVector.AlwaysBreaks)
2262                                 return;
2263
2264                         CurrentUsageVector [vi, field_idx] = true;
2265                 }
2266
2267                 public bool IsParameterAssigned (int number)
2268                 {
2269                         int index = param_map [number];
2270
2271                         if (index == 0)
2272                                 return true;
2273
2274                         if (CurrentUsageVector [index])
2275                                 return true;
2276
2277                         // Parameter is not assigned, so check whether it's a struct.
2278                         // If it's either not a struct or a struct which non-public
2279                         // fields, return false.
2280                         MyStructInfo struct_info = struct_params [number];
2281                         if ((struct_info == null) || struct_info.HasNonPublicFields)
2282                                 return false;
2283
2284                         // Ok, so each field must be assigned.
2285                         for (int i = 0; i < struct_info.Count; i++)
2286                                 if (!CurrentUsageVector [index + i])
2287                                         return false;
2288
2289                         return true;
2290                 }
2291
2292                 public bool IsParameterAssigned (int number, string field_name)
2293                 {
2294                         int index = param_map [number];
2295
2296                         if (index == 0)
2297                                 return true;
2298
2299                         MyStructInfo info = (MyStructInfo) struct_params [number];
2300                         if (info == null)
2301                                 return true;
2302
2303                         int field_idx = info [field_name];
2304
2305                         return CurrentUsageVector [index + field_idx];
2306                 }
2307
2308                 public void SetParameterAssigned (int number)
2309                 {
2310                         if (param_map [number] == 0)
2311                                 return;
2312
2313                         if (!CurrentUsageVector.AlwaysBreaks)
2314                                 CurrentUsageVector [param_map [number]] = true;
2315                 }
2316
2317                 public void SetParameterAssigned (int number, string field_name)
2318                 {
2319                         int index = param_map [number];
2320
2321                         if (index == 0)
2322                                 return;
2323
2324                         MyStructInfo info = (MyStructInfo) struct_params [number];
2325                         if (info == null)
2326                                 return;
2327
2328                         int field_idx = info [field_name];
2329
2330                         if (!CurrentUsageVector.AlwaysBreaks)
2331                                 CurrentUsageVector [index + field_idx] = true;
2332                 }
2333
2334                 public bool IsReachable ()
2335                 {
2336                         bool reachable;
2337
2338                         switch (Type) {
2339                         case FlowBranchingType.SWITCH_SECTION:
2340                                 // The code following a switch block is reachable unless the switch
2341                                 // block always returns.
2342                                 reachable = !CurrentUsageVector.AlwaysReturns;
2343                                 break;
2344
2345                         case FlowBranchingType.LOOP_BLOCK:
2346                                 // The code following a loop is reachable unless the loop always
2347                                 // returns or it's an infinite loop without any `break's in it.
2348                                 reachable = !CurrentUsageVector.AlwaysReturns &&
2349                                         (CurrentUsageVector.Breaks != FlowReturns.UNREACHABLE);
2350                                 break;
2351
2352                         default:
2353                                 // The code following a block or exception is reachable unless the
2354                                 // block either always returns or always breaks.
2355                                 reachable = !CurrentUsageVector.AlwaysBreaks &&
2356                                         !CurrentUsageVector.AlwaysReturns;
2357                                 break;
2358                         }
2359
2360                         Report.Debug (1, "REACHABLE", Type, CurrentUsageVector.Returns,
2361                                       CurrentUsageVector.Breaks, CurrentUsageVector, reachable);
2362
2363                         return reachable;
2364                 }
2365
2366                 public override string ToString ()
2367                 {
2368                         StringBuilder sb = new StringBuilder ("FlowBranching (");
2369
2370                         sb.Append (id);
2371                         sb.Append (",");
2372                         sb.Append (Type);
2373                         if (Block != null) {
2374                                 sb.Append (" - ");
2375                                 sb.Append (Block.ID);
2376                                 sb.Append (" - ");
2377                                 sb.Append (Block.StartLocation);
2378                         }
2379                         sb.Append (" - ");
2380                         sb.Append (Siblings.Count);
2381                         sb.Append (" - ");
2382                         sb.Append (CurrentUsageVector);
2383                         sb.Append (")");
2384                         return sb.ToString ();
2385                 }
2386         }
2387
2388         public class MyStructInfo {
2389                 public readonly Type Type;
2390                 public readonly FieldInfo[] Fields;
2391                 public readonly FieldInfo[] NonPublicFields;
2392                 public readonly int Count;
2393                 public readonly int CountNonPublic;
2394                 public readonly bool HasNonPublicFields;
2395
2396                 private static Hashtable field_type_hash = new Hashtable ();
2397                 private Hashtable field_hash;
2398
2399                 // Private constructor.  To save memory usage, we only need to create one instance
2400                 // of this class per struct type.
2401                 private MyStructInfo (Type type)
2402                 {
2403                         this.Type = type;
2404
2405                         if (type is TypeBuilder) {
2406                                 TypeContainer tc = TypeManager.LookupTypeContainer (type);
2407
2408                                 ArrayList fields = tc.Fields;
2409                                 if (fields != null) {
2410                                         foreach (Field field in fields) {
2411                                                 if ((field.ModFlags & Modifiers.STATIC) != 0)
2412                                                         continue;
2413                                                 if ((field.ModFlags & Modifiers.PUBLIC) != 0)
2414                                                         ++Count;
2415                                                 else
2416                                                         ++CountNonPublic;
2417                                         }
2418                                 }
2419
2420                                 Fields = new FieldInfo [Count];
2421                                 NonPublicFields = new FieldInfo [CountNonPublic];
2422
2423                                 Count = CountNonPublic = 0;
2424                                 if (fields != null) {
2425                                         foreach (Field field in fields) {
2426                                                 if ((field.ModFlags & Modifiers.STATIC) != 0)
2427                                                         continue;
2428                                                 if ((field.ModFlags & Modifiers.PUBLIC) != 0)
2429                                                         Fields [Count++] = field.FieldBuilder;
2430                                                 else
2431                                                         NonPublicFields [CountNonPublic++] =
2432                                                                 field.FieldBuilder;
2433                                         }
2434                                 }
2435                                 
2436                         } else {
2437                                 Fields = type.GetFields (BindingFlags.Instance|BindingFlags.Public);
2438                                 Count = Fields.Length;
2439
2440                                 NonPublicFields = type.GetFields (BindingFlags.Instance|BindingFlags.NonPublic);
2441                                 CountNonPublic = NonPublicFields.Length;
2442                         }
2443
2444                         Count += NonPublicFields.Length;
2445
2446                         int number = 0;
2447                         field_hash = new Hashtable ();
2448                         foreach (FieldInfo field in Fields)
2449                                 field_hash.Add (field.Name, ++number);
2450
2451                         if (NonPublicFields.Length != 0)
2452                                 HasNonPublicFields = true;
2453
2454                         foreach (FieldInfo field in NonPublicFields)
2455                                 field_hash.Add (field.Name, ++number);
2456                 }
2457
2458                 public int this [string name] {
2459                         get {
2460                                 if (field_hash.Contains (name))
2461                                         return (int) field_hash [name];
2462                                 else
2463                                         return 0;
2464                         }
2465                 }
2466
2467                 public FieldInfo this [int index] {
2468                         get {
2469                                 if (index >= Fields.Length)
2470                                         return NonPublicFields [index - Fields.Length];
2471                                 else
2472                                         return Fields [index];
2473                         }
2474                 }                      
2475
2476                 public static MyStructInfo GetStructInfo (Type type)
2477                 {
2478                         if (!TypeManager.IsValueType (type) || TypeManager.IsEnumType (type))
2479                                 return null;
2480
2481                         if (!(type is TypeBuilder) && TypeManager.IsBuiltinType (type))
2482                                 return null;
2483
2484                         MyStructInfo info = (MyStructInfo) field_type_hash [type];
2485                         if (info != null)
2486                                 return info;
2487
2488                         info = new MyStructInfo (type);
2489                         field_type_hash.Add (type, info);
2490                         return info;
2491                 }
2492
2493                 public static MyStructInfo GetStructInfo (TypeContainer tc)
2494                 {
2495                         MyStructInfo info = (MyStructInfo) field_type_hash [tc.TypeBuilder];
2496                         if (info != null)
2497                                 return info;
2498
2499                         info = new MyStructInfo (tc.TypeBuilder);
2500                         field_type_hash.Add (tc.TypeBuilder, info);
2501                         return info;
2502                 }
2503         }
2504         
2505         public class VariableInfo : IVariable {
2506                 public Expression Type;
2507                 public LocalBuilder LocalBuilder;
2508                 public Type VariableType;
2509                 public readonly string Name;
2510                 public readonly Location Location;
2511                 public readonly int Block;
2512
2513                 public int Number;
2514                 
2515                 public bool Used;
2516                 public bool Assigned;
2517                 public bool ReadOnly;
2518                 
2519                 public VariableInfo (Expression type, string name, int block, Location l)
2520                 {
2521                         Type = type;
2522                         Name = name;
2523                         Block = block;
2524                         LocalBuilder = null;
2525                         Location = l;
2526                 }
2527
2528                 public VariableInfo (TypeContainer tc, int block, Location l)
2529                 {
2530                         VariableType = tc.TypeBuilder;
2531                         struct_info = MyStructInfo.GetStructInfo (tc);
2532                         Block = block;
2533                         LocalBuilder = null;
2534                         Location = l;
2535                 }
2536
2537                 MyStructInfo struct_info;
2538                 public MyStructInfo StructInfo {
2539                         get {
2540                                 return struct_info;
2541                         }
2542                 }
2543
2544                 public bool IsAssigned (EmitContext ec, Location loc)
2545                 {/* FIXME: we shouldn't just skip this!!!
2546                         if (!ec.DoFlowAnalysis || ec.CurrentBranching.IsVariableAssigned (this))
2547                                 return true;
2548
2549                         MyStructInfo struct_info = StructInfo;
2550                         if ((struct_info == null) || (struct_info.HasNonPublicFields && (Name != null))) {
2551                                 Report.Error (165, loc, "Use of unassigned local variable `" + Name + "'");
2552                                 ec.CurrentBranching.SetVariableAssigned (this);
2553                                 return false;
2554                         }
2555
2556                         int count = struct_info.Count;
2557
2558                         for (int i = 0; i < count; i++) {
2559                                 if (!ec.CurrentBranching.IsVariableAssigned (this, i+1)) {
2560                                         if (Name != null) {
2561                                                 Report.Error (165, loc,
2562                                                               "Use of unassigned local variable `" +
2563                                                               Name + "'");
2564                                                 ec.CurrentBranching.SetVariableAssigned (this);
2565                                                 return false;
2566                                         }
2567
2568                                         FieldInfo field = struct_info [i];
2569                                         Report.Error (171, loc,
2570                                                       "Field `" + TypeManager.MonoBASIC_Name (VariableType) +
2571                                                       "." + field.Name + "' must be fully initialized " +
2572                                                       "before control leaves the constructor");
2573                                         return false;
2574                                 }
2575                         }
2576 */
2577                         return true;
2578                 }
2579
2580                 public bool IsFieldAssigned (EmitContext ec, string name, Location loc)
2581                 {
2582                         if (!ec.DoFlowAnalysis || ec.CurrentBranching.IsVariableAssigned (this) ||
2583                             (struct_info == null))
2584                                 return true;
2585
2586                         int field_idx = StructInfo [name];
2587                         if (field_idx == 0)
2588                                 return true;
2589
2590                         if (!ec.CurrentBranching.IsVariableAssigned (this, field_idx)) {
2591                                 Report.Error (170, loc,
2592                                               "Use of possibly unassigned field `" + name + "'");
2593                                 ec.CurrentBranching.SetVariableAssigned (this, field_idx);
2594                                 return false;
2595                         }
2596
2597                         return true;
2598                 }
2599
2600                 public void SetAssigned (EmitContext ec)
2601                 {
2602                         if (ec.DoFlowAnalysis)
2603                                 ec.CurrentBranching.SetVariableAssigned (this);
2604                 }
2605
2606                 public void SetFieldAssigned (EmitContext ec, string name)
2607                 {
2608                         if (ec.DoFlowAnalysis && (struct_info != null))
2609                                 ec.CurrentBranching.SetVariableAssigned (this, StructInfo [name]);
2610                 }
2611
2612                 public bool Resolve (DeclSpace decl)
2613                 {
2614                         if (struct_info != null)
2615                                 return true;
2616
2617                         if (VariableType == null)
2618                                 VariableType = decl.ResolveType (Type, false, Location);
2619
2620                         if (VariableType == null)
2621                                 return false;
2622
2623                         struct_info = MyStructInfo.GetStructInfo (VariableType);
2624
2625                         return true;
2626                 }
2627
2628                 public void MakePinned ()
2629                 {
2630                         TypeManager.MakePinned (LocalBuilder);
2631                 }
2632
2633                 public override string ToString ()
2634                 {
2635                         return "VariableInfo (" + Number + "," + Type + "," + Location + ")";
2636                 }
2637         }
2638                 
2639         /// <summary>
2640         ///   Block represents a C# block.
2641         /// </summary>
2642         ///
2643         /// <remarks>
2644         ///   This class is used in a number of places: either to represent
2645         ///   explicit blocks that the programmer places or implicit blocks.
2646         ///
2647         ///   Implicit blocks are used as labels or to introduce variable
2648         ///   declarations.
2649         /// </remarks>
2650         public class Block : Statement {
2651                 public readonly Block     Parent;
2652                 public readonly bool      Implicit;
2653                 public readonly Location  StartLocation;
2654                 public Location           EndLocation;
2655
2656                 //
2657                 // The statements in this block
2658                 //
2659                 public ArrayList statements;
2660
2661                 //
2662                 // An array of Blocks.  We keep track of children just
2663                 // to generate the local variable declarations.
2664                 //
2665                 // Statements and child statements are handled through the
2666                 // statements.
2667                 //
2668                 ArrayList children;
2669                 
2670                 //
2671                 // Labels.  (label, block) pairs.
2672                 //
2673                 CaseInsensitiveHashtable labels;
2674
2675                 //
2676                 // Keeps track of (name, type) pairs
2677                 //
2678                 CaseInsensitiveHashtable variables;
2679
2680                 //
2681                 // Keeps track of constants
2682                 CaseInsensitiveHashtable constants;
2683
2684                 //
2685                 // Maps variable names to ILGenerator.LocalBuilders
2686                 //
2687                 CaseInsensitiveHashtable local_builders;
2688
2689                 bool used = false;
2690
2691                 static int id;
2692
2693                 int this_id;
2694                 
2695                 public Block (Block parent)
2696                         : this (parent, false, Location.Null, Location.Null)
2697                 { }
2698
2699                 public Block (Block parent, bool implicit_block)
2700                         : this (parent, implicit_block, Location.Null, Location.Null)
2701                 { }
2702
2703                 public Block (Block parent, bool implicit_block, Parameters parameters)
2704                         : this (parent, implicit_block, parameters, Location.Null, Location.Null)
2705                 { }
2706
2707                 public Block (Block parent, Location start, Location end)
2708                         : this (parent, false, start, end)
2709                 { }
2710
2711                 public Block (Block parent, Parameters parameters, Location start, Location end)
2712                         : this (parent, false, parameters, start, end)
2713                 { }
2714
2715                 public Block (Block parent, bool implicit_block, Location start, Location end)
2716                         : this (parent, implicit_block, Parameters.EmptyReadOnlyParameters,
2717                                 start, end)
2718                 { }
2719
2720                 public Block (Block parent, bool implicit_block, Parameters parameters,
2721                               Location start, Location end)
2722                 {
2723                         if (parent != null)
2724                                 parent.AddChild (this);
2725                         
2726                         this.Parent = parent;
2727                         this.Implicit = implicit_block;
2728                         this.parameters = parameters;
2729                         this.StartLocation = start;
2730                         this.EndLocation = end;
2731                         this.loc = start;
2732                         this_id = id++;
2733                         statements = new ArrayList ();
2734                 }
2735
2736                 public int ID {
2737                         get {
2738                                 return this_id;
2739                         }
2740                 }
2741
2742                 void AddChild (Block b)
2743                 {
2744                         if (children == null)
2745                                 children = new ArrayList ();
2746                         
2747                         children.Add (b);
2748                 }
2749
2750                 public void SetEndLocation (Location loc)
2751                 {
2752                         EndLocation = loc;
2753                 }
2754
2755                 /// <summary>
2756                 ///   Adds a label to the current block. 
2757                 /// </summary>
2758                 ///
2759                 /// <returns>
2760                 ///   false if the name already exists in this block. true
2761                 ///   otherwise.
2762                 /// </returns>
2763                 ///
2764                 public bool AddLabel (string name, LabeledStatement target)
2765                 {
2766                         if (labels == null)
2767                                 labels = new CaseInsensitiveHashtable ();
2768                         if (labels.Contains (name))
2769                                 return false;
2770                         
2771                         labels.Add (name, target);
2772                         return true;
2773                 }
2774
2775                 public LabeledStatement LookupLabel (string name)
2776                 {
2777                         if (labels != null){
2778                                 if (labels.Contains (name))
2779                                         return ((LabeledStatement) labels [name]);
2780                         }
2781
2782                         if (Parent != null)
2783                                 return Parent.LookupLabel (name);
2784
2785                         return null;
2786                 }
2787
2788                 VariableInfo this_variable = null;
2789
2790                 // <summary>
2791                 //   Returns the "this" instance variable of this block.
2792                 //   See AddThisVariable() for more information.
2793                 // </summary>
2794                 public VariableInfo ThisVariable {
2795                         get {
2796                                 if (this_variable != null)
2797                                         return this_variable;
2798                                 else if (Parent != null)
2799                                         return Parent.ThisVariable;
2800                                 else
2801                                         return null;
2802                         }
2803                 }
2804
2805                 Hashtable child_variable_names;
2806
2807                 // <summary>
2808                 //   Marks a variable with name @name as being used in a child block.
2809                 //   If a variable name has been used in a child block, it's illegal to
2810                 //   declare a variable with the same name in the current block.
2811                 // </summary>
2812                 public void AddChildVariableName (string name)
2813                 {
2814                         if (child_variable_names == null)
2815                                 child_variable_names = new CaseInsensitiveHashtable ();
2816
2817                         if (!child_variable_names.Contains (name))
2818                                 child_variable_names.Add (name, true);
2819                 }
2820
2821                 // <summary>
2822                 //   Marks all variables from block @block and all its children as being
2823                 //   used in a child block.
2824                 // </summary>
2825                 public void AddChildVariableNames (Block block)
2826                 {
2827                         if (block.Variables != null) {
2828                                 foreach (string name in block.Variables.Keys)
2829                                         AddChildVariableName (name);
2830                         }
2831
2832                         foreach (Block child in block.children) {
2833                                 if (child.Variables != null) {
2834                                         foreach (string name in child.Variables.Keys)
2835                                                 AddChildVariableName (name);
2836                                 }
2837                         }
2838                 }
2839
2840                 // <summary>
2841                 //   Checks whether a variable name has already been used in a child block.
2842                 // </summary>
2843                 public bool IsVariableNameUsedInChildBlock (string name)
2844                 {
2845                         if (child_variable_names == null)
2846                                 return false;
2847
2848                         return child_variable_names.Contains (name);
2849                 }
2850
2851                 // <summary>
2852                 //   This is used by non-static `struct' constructors which do not have an
2853                 //   initializer - in this case, the constructor must initialize all of the
2854                 //   struct's fields.  To do this, we add a "this" variable and use the flow
2855                 //   analysis code to ensure that it's been fully initialized before control
2856                 //   leaves the constructor.
2857                 // </summary>
2858                 public VariableInfo AddThisVariable (TypeContainer tc, Location l)
2859                 {
2860                         if (this_variable != null)
2861                                 return this_variable;
2862
2863                         this_variable = new VariableInfo (tc, ID, l);
2864
2865                         if (variables == null)
2866                                 variables = new CaseInsensitiveHashtable ();
2867                         variables.Add ("this", this_variable);
2868
2869                         return this_variable;
2870                 }
2871
2872                 public VariableInfo AddVariable (Expression type, string name, Parameters pars, Location l)
2873                 {
2874                         if (variables == null)
2875                                 variables = new CaseInsensitiveHashtable ();
2876
2877                         VariableInfo vi = GetVariableInfo (name);
2878                         if (vi != null) {
2879                                 if (vi.Block != ID)
2880                                         Report.Error (30616, l, "A local variable named `" + name + "' " +
2881                                                       "cannot be declared in this scope since it would " +
2882                                                       "give a different meaning to `" + name + "', which " +
2883                                                       "is already used in a `parent or current' scope to " +
2884                                                       "denote something else");
2885                                 else
2886                                         Report.Error (30290, l, "A local variable `" + name + "' is already " +
2887                                                       "defined in this scope");
2888                                 return null;
2889                         }
2890
2891                         if (IsVariableNameUsedInChildBlock (name)) {
2892                                 Report.Error (136, l, "A local variable named `" + name + "' " +
2893                                               "cannot be declared in this scope since it would " +
2894                                               "give a different meaning to `" + name + "', which " +
2895                                               "is already used in a `child' scope to denote something " +
2896                                               "else");
2897                                 return null;
2898                         }
2899
2900                         if (pars != null) {
2901                                 int idx = 0;
2902                                 Parameter p = pars.GetParameterByName (name, out idx);
2903                                 if (p != null) {
2904                                         Report.Error (30616, l, "A local variable named `" + name + "' " +
2905                                                       "cannot be declared in this scope since it would " +
2906                                                       "give a different meaning to `" + name + "', which " +
2907                                                       "is already used in a `parent or current' scope to " +
2908                                                       "denote something else");
2909                                         return null;
2910                                 }
2911                         }
2912                         
2913                         vi = new VariableInfo (type, name, ID, l);
2914
2915                         variables.Add (name, vi);
2916
2917                         if (variables_initialized)
2918                                 throw new Exception ();
2919
2920                         // Console.WriteLine ("Adding {0} to {1}", name, ID);
2921                         return vi;
2922                 }
2923
2924                 public bool AddConstant (Expression type, string name, Expression value, Parameters pars, Location l)
2925                 {
2926                         if (AddVariable (type, name, pars, l) == null)
2927                                 return false;
2928                         
2929                         if (constants == null)
2930                                 constants = new CaseInsensitiveHashtable ();
2931
2932                         constants.Add (name, value);
2933                         return true;
2934                 }
2935
2936                 public Hashtable Variables {
2937                         get {
2938                                 return variables;
2939                         }
2940                 }
2941
2942                 public VariableInfo GetVariableInfo (string name)
2943                 {
2944                         if (variables != null) {
2945                                 object temp;
2946                                 temp = variables [name];
2947
2948                                 if (temp != null){
2949                                         return (VariableInfo) temp;
2950                                 }
2951                         }
2952
2953                         if (Parent != null)
2954                                 return Parent.GetVariableInfo (name);
2955
2956                         return null;
2957                 }
2958                 
2959                 public Expression GetVariableType (string name)
2960                 {
2961                         VariableInfo vi = GetVariableInfo (name);
2962
2963                         if (vi != null)
2964                                 return vi.Type;
2965
2966                         return null;
2967                 }
2968
2969                 public Expression GetConstantExpression (string name)
2970                 {
2971                         if (constants != null) {
2972                                 object temp;
2973                                 temp = constants [name];
2974                                 
2975                                 if (temp != null)
2976                                         return (Expression) temp;
2977                         }
2978                         
2979                         if (Parent != null)
2980                                 return Parent.GetConstantExpression (name);
2981
2982                         return null;
2983                 }
2984                 
2985                 /// <summary>
2986                 ///   True if the variable named @name has been defined
2987                 ///   in this block
2988                 /// </summary>
2989                 public bool IsVariableDefined (string name)
2990                 {
2991                         // Console.WriteLine ("Looking up {0} in {1}", name, ID);
2992                         if (variables != null) {
2993                                 if (variables.Contains (name))
2994                                         return true;
2995                         }
2996                         
2997                         if (Parent != null)
2998                                 return Parent.IsVariableDefined (name);
2999
3000                         return false;
3001                 }
3002
3003                 /// <summary>
3004                 ///   True if the variable named @name is a constant
3005                 ///  </summary>
3006                 public bool IsConstant (string name)
3007                 {
3008                         Expression e = null;
3009                         
3010                         e = GetConstantExpression (name);
3011                         
3012                         return e != null;
3013                 }
3014                 
3015                 /// <summary>
3016                 ///   Use to fetch the statement associated with this label
3017                 /// </summary>
3018                 public Statement this [string name] {
3019                         get {
3020                                 return (Statement) labels [name];
3021                         }
3022                 }
3023
3024                 Parameters parameters = null;
3025                 public Parameters Parameters {
3026                         get {
3027                                 if (Parent != null)
3028                                         return Parent.Parameters;
3029
3030                                 return parameters;
3031                         }
3032                 }
3033
3034                 /// <returns>
3035                 ///   A list of labels that were not used within this block
3036                 /// </returns>
3037                 public string [] GetUnreferenced ()
3038                 {
3039                         // FIXME: Implement me
3040                         return null;
3041                 }
3042
3043                 public void AddStatement (Statement s)
3044                 {
3045                         statements.Add (s);
3046                         used = true;
3047                 }
3048
3049                 public bool Used {
3050                         get {
3051                                 return used;
3052                         }
3053                 }
3054
3055                 public void Use ()
3056                 {
3057                         used = true;
3058                 }
3059
3060                 bool variables_initialized = false;
3061                 int count_variables = 0, first_variable = 0;
3062
3063                 void UpdateVariableInfo (EmitContext ec)
3064                 {
3065                         DeclSpace ds = ec.DeclSpace;
3066
3067                         first_variable = 0;
3068
3069                         if (Parent != null)
3070                                 first_variable += Parent.CountVariables;
3071
3072                         count_variables = first_variable;
3073                         if (variables != null) {
3074                                 foreach (VariableInfo vi in variables.Values) {
3075                                         if (!vi.Resolve (ds)) {
3076                                                 vi.Number = -1;
3077                                                 continue;
3078                                         }
3079
3080                                         vi.Number = ++count_variables;
3081
3082                                         if (vi.StructInfo != null)
3083                                                 count_variables += vi.StructInfo.Count;
3084                                 }
3085                         }
3086
3087                         variables_initialized = true;
3088                 }
3089
3090                 //
3091                 // <returns>
3092                 //   The number of local variables in this block
3093                 // </returns>
3094                 public int CountVariables
3095                 {
3096                         get {
3097                                 if (!variables_initialized)
3098                                         throw new Exception ();
3099
3100                                 return count_variables;
3101                         }
3102                 }
3103
3104                 /// <summary>
3105                 ///   Emits the variable declarations and labels.
3106                 /// </summary>
3107                 /// <remarks>
3108                 ///   tc: is our typecontainer (to resolve type references)
3109                 ///   ig: is the code generator:
3110                 ///   toplevel: the toplevel block.  This is used for checking 
3111                 ///             that no two labels with the same name are used.
3112                 /// </remarks>
3113                 public void EmitMeta (EmitContext ec, Block toplevel)
3114                 {
3115                         //DeclSpace ds = ec.DeclSpace;
3116                         ILGenerator ig = ec.ig;
3117
3118                         if (!variables_initialized)
3119                                 UpdateVariableInfo (ec);
3120
3121                         //
3122                         // Process this block variables
3123                         //
3124                         if (variables != null){
3125                                 local_builders = new CaseInsensitiveHashtable ();
3126                                 
3127                                 foreach (DictionaryEntry de in variables){
3128                                         string name = (string) de.Key;
3129                                         VariableInfo vi = (VariableInfo) de.Value;
3130
3131                                         if (vi.VariableType == null)
3132                                                 continue;
3133
3134                                         vi.LocalBuilder = ig.DeclareLocal (vi.VariableType);
3135
3136                                         if (CodeGen.SymbolWriter != null)
3137                                                 vi.LocalBuilder.SetLocalSymInfo (name);
3138
3139                                         if (constants == null)
3140                                                 continue;
3141
3142                                         Expression cv = (Expression) constants [name];
3143                                         if (cv == null)
3144                                                 continue;
3145
3146                                         Expression e = cv.Resolve (ec);
3147                                         if (e == null)
3148                                                 continue;
3149
3150                                         if (!(e is Constant)){
3151                                                 Report.Error (133, vi.Location,
3152                                                               "The expression being assigned to `" +
3153                                                               name + "' must be constant (" + e + ")");
3154                                                 continue;
3155                                         }
3156
3157                                         constants.Remove (name);
3158                                         constants.Add (name, e);
3159                                 }
3160                         }
3161
3162                         //
3163                         // Now, handle the children
3164                         //
3165                         if (children != null){
3166                                 foreach (Block b in children)
3167                                         b.EmitMeta (ec, toplevel);
3168                         }
3169                 }
3170
3171                 public void UsageWarning ()
3172                 {
3173                         string name;
3174                         
3175                         if (variables != null){
3176                                 foreach (DictionaryEntry de in variables){
3177                                         VariableInfo vi = (VariableInfo) de.Value;
3178                                         
3179                                         if (vi.Used)
3180                                                 continue;
3181                                         
3182                                         name = (string) de.Key;
3183                                                 
3184                                         if (vi.Assigned){
3185                                                 Report.Warning (
3186                                                         219, vi.Location, "The variable `" + name +
3187                                                         "' is assigned but its value is never used");
3188                                         } else {
3189                                                 Report.Warning (
3190                                                         168, vi.Location, "The variable `" +
3191                                                         name +
3192                                                         "' is declared but never used");
3193                                         } 
3194                                 }
3195                         }
3196
3197                         if (children != null)
3198                                 foreach (Block b in children)
3199                                         b.UsageWarning ();
3200                 }
3201
3202                 bool has_ret = false;
3203
3204                 public override bool Resolve (EmitContext ec)
3205                 {
3206                         Block prev_block = ec.CurrentBlock;
3207                         bool ok = true;
3208
3209                         ec.CurrentBlock = this;
3210                         ec.StartFlowBranching (this);
3211
3212                         Report.Debug (1, "RESOLVE BLOCK", StartLocation, ec.CurrentBranching);
3213
3214                         if (!variables_initialized)
3215                                 UpdateVariableInfo (ec);
3216
3217                         ArrayList new_statements = new ArrayList ();
3218                         bool unreachable = false, warning_shown = false;
3219
3220                         foreach (Statement s in statements){
3221                                 if (unreachable && !(s is LabeledStatement)) {
3222                                         if (!warning_shown && !(s is EmptyStatement)) {
3223                                                 warning_shown = true;
3224                                                 Warning_DeadCodeFound (s.loc);
3225                                         }
3226
3227                                         continue;
3228                                 }
3229
3230                                 if (s.Resolve (ec) == false) {
3231                                         ok = false;
3232                                         continue;
3233                                 }
3234
3235                                 if (s is LabeledStatement)
3236                                         unreachable = false;
3237                                 else
3238                                         unreachable = ! ec.CurrentBranching.IsReachable ();
3239
3240                                 new_statements.Add (s);
3241                         }
3242
3243                         statements = new_statements;
3244
3245                         Report.Debug (1, "RESOLVE BLOCK DONE", StartLocation, ec.CurrentBranching);
3246
3247                         FlowReturns returns = ec.EndFlowBranching ();
3248                         ec.CurrentBlock = prev_block;
3249
3250                         // If we're a non-static `struct' constructor which doesn't have an
3251                         // initializer, then we must initialize all of the struct's fields.
3252                         if ((this_variable != null) && (returns != FlowReturns.EXCEPTION) &&
3253                             !this_variable.IsAssigned (ec, loc))
3254                                 ok = false;
3255
3256                         if ((labels != null) && (RootContext.WarningLevel >= 2)) {
3257                                 foreach (LabeledStatement label in labels.Values)
3258                                         if (!label.HasBeenReferenced)
3259                                                 Report.Warning (164, label.Location,
3260                                                                 "This label has not been referenced");
3261                         }
3262
3263                         if ((returns == FlowReturns.ALWAYS) ||
3264                             (returns == FlowReturns.EXCEPTION) ||
3265                             (returns == FlowReturns.UNREACHABLE))
3266                                 has_ret = true;
3267
3268                         return ok;
3269                 }
3270                 
3271                 protected override bool DoEmit (EmitContext ec)
3272                 {
3273                         Block prev_block = ec.CurrentBlock;
3274
3275                         ec.CurrentBlock = this;
3276
3277                         ec.Mark (StartLocation);
3278                         foreach (Statement s in statements)
3279                                 s.Emit (ec);
3280                                 
3281                         ec.Mark (EndLocation); 
3282                         
3283                         ec.CurrentBlock = prev_block;
3284                         return has_ret;
3285                 }
3286         }
3287
3288         public class SwitchLabel {
3289                 Expression label;
3290                 object converted;
3291                 public Location loc;
3292                 public Label ILLabel;
3293                 public Label ILLabelCode;
3294
3295                 //
3296                 // if expr == null, then it is the default case.
3297                 //
3298                 public SwitchLabel (Expression expr, Location l)
3299                 {
3300                         label = expr;
3301                         loc = l;
3302                 }
3303
3304                 public Expression Label {
3305                         get {
3306                                 return label;
3307                         }
3308                 }
3309
3310                 public object Converted {
3311                         get {
3312                                 return converted;
3313                         }
3314                 }
3315
3316                 //
3317                 // Resolves the expression, reduces it to a literal if possible
3318                 // and then converts it to the requested type.
3319                 //
3320                 public bool ResolveAndReduce (EmitContext ec, Type required_type)
3321                 {
3322                         ILLabel = ec.ig.DefineLabel ();
3323                         ILLabelCode = ec.ig.DefineLabel ();
3324
3325                         if (label == null)
3326                                 return true;
3327                         
3328                         Expression e = label.Resolve (ec);
3329
3330                         if (e == null)
3331                                 return false;
3332
3333                         if (!(e is Constant)){
3334                                 Console.WriteLine ("Value is: " + label);
3335                                 Report.Error (150, loc, "A constant value is expected");
3336                                 return false;
3337                         }
3338
3339                         if (e is StringConstant || e is NullLiteral){
3340                                 if (required_type == TypeManager.string_type){
3341                                         converted = e;
3342                                         ILLabel = ec.ig.DefineLabel ();
3343                                         return true;
3344                                 }
3345                         }
3346
3347                         converted = Expression.ConvertIntLiteral ((Constant) e, required_type, loc);
3348                         if (converted == null)
3349                                 return false;
3350
3351                         return true;
3352                 }
3353         }
3354
3355         public class SwitchSection {
3356                 // An array of SwitchLabels.
3357                 public readonly ArrayList Labels;
3358                 public readonly Block Block;
3359                 
3360                 public SwitchSection (ArrayList labels, Block block)
3361                 {
3362                         Labels = labels;
3363                         Block = block;
3364                 }
3365         }
3366         
3367         public class Switch : Statement {
3368                 public readonly ArrayList Sections;
3369                 public Expression Expr;
3370
3371                 /// <summary>
3372                 ///   Maps constants whose type type SwitchType to their  SwitchLabels.
3373                 /// </summary>
3374                 public Hashtable Elements;
3375
3376                 /// <summary>
3377                 ///   The governing switch type
3378                 /// </summary>
3379                 public Type SwitchType;
3380
3381                 //
3382                 // Computed
3383                 //
3384                 bool got_default;
3385                 Label default_target;
3386                 Expression new_expr;
3387
3388                 //
3389                 // The types allowed to be implicitly cast from
3390                 // on the governing type
3391                 //
3392                 static Type [] allowed_types;
3393                 
3394                 public Switch (Expression e, ArrayList sects, Location l)
3395                 {
3396                         Expr = e;
3397                         Sections = sects;
3398                         loc = l;
3399                 }
3400
3401                 public bool GotDefault {
3402                         get {
3403                                 return got_default;
3404                         }
3405                 }
3406
3407                 public Label DefaultTarget {
3408                         get {
3409                                 return default_target;
3410                         }
3411                 }
3412
3413                 //
3414                 // Determines the governing type for a switch.  The returned
3415                 // expression might be the expression from the switch, or an
3416                 // expression that includes any potential conversions to the
3417                 // integral types or to string.
3418                 //
3419                 Expression SwitchGoverningType (EmitContext ec, Type t)
3420                 {
3421                         if (t == TypeManager.int32_type ||
3422                             t == TypeManager.uint32_type ||
3423                             t == TypeManager.char_type ||
3424                             t == TypeManager.byte_type ||
3425                             t == TypeManager.sbyte_type ||
3426                             t == TypeManager.ushort_type ||
3427                             t == TypeManager.short_type ||
3428                             t == TypeManager.uint64_type ||
3429                             t == TypeManager.int64_type ||
3430                             t == TypeManager.string_type ||
3431                                 t == TypeManager.bool_type ||
3432                                 t.IsSubclassOf (TypeManager.enum_type))
3433                                 return Expr;
3434
3435                         if (allowed_types == null){
3436                                 allowed_types = new Type [] {
3437                                         TypeManager.sbyte_type,
3438                                         TypeManager.byte_type,
3439                                         TypeManager.short_type,
3440                                         TypeManager.ushort_type,
3441                                         TypeManager.int32_type,
3442                                         TypeManager.uint32_type,
3443                                         TypeManager.int64_type,
3444                                         TypeManager.uint64_type,
3445                                         TypeManager.char_type,
3446                                         TypeManager.bool_type,
3447                                         TypeManager.string_type
3448                                 };
3449                         }
3450
3451                         //
3452                         // Try to find a *user* defined implicit conversion.
3453                         //
3454                         // If there is no implicit conversion, or if there are multiple
3455                         // conversions, we have to report an error
3456                         //
3457                         Expression converted = null;
3458                         foreach (Type tt in allowed_types){
3459                                 Expression e;
3460                                 
3461                                 e = Expression.ImplicitUserConversion (ec, Expr, tt, loc);
3462                                 if (e == null)
3463                                         continue;
3464
3465                                 if (converted != null){
3466                                         Report.Error (-12, loc, "More than one conversion to an integral " +
3467                                                       " type exists for type `" +
3468                                                       TypeManager.MonoBASIC_Name (Expr.Type)+"'");
3469                                         return null;
3470                                 } else
3471                                         converted = e;
3472                         }
3473                         return converted;
3474                 }
3475
3476                 void error152 (string n)
3477                 {
3478                         Report.Error (
3479                                 152, "The label `" + n + ":' " +
3480                                 "is already present on this switch statement");
3481                 }
3482                 
3483                 //
3484                 // Performs the basic sanity checks on the switch statement
3485                 // (looks for duplicate keys and non-constant expressions).
3486                 //
3487                 // It also returns a hashtable with the keys that we will later
3488                 // use to compute the switch tables
3489                 //
3490                 bool CheckSwitch (EmitContext ec)
3491                 {
3492                         Type compare_type;
3493                         bool error = false;
3494                         Elements = new CaseInsensitiveHashtable ();
3495                                 
3496                         got_default = false;
3497
3498                         if (TypeManager.IsEnumType (SwitchType)){
3499                                 compare_type = TypeManager.EnumToUnderlying (SwitchType);
3500                         } else
3501                                 compare_type = SwitchType;
3502                         
3503                         foreach (SwitchSection ss in Sections){
3504                                 foreach (SwitchLabel sl in ss.Labels){
3505                                         if (!sl.ResolveAndReduce (ec, SwitchType)){
3506                                                 error = true;
3507                                                 continue;
3508                                         }
3509
3510                                         if (sl.Label == null){
3511                                                 if (got_default){
3512                                                         error152 ("default");
3513                                                         error = true;
3514                                                 }
3515                                                 got_default = true;
3516                                                 continue;
3517                                         }
3518                                         
3519                                         object key = sl.Converted;
3520
3521                                         if (key is Constant)
3522                                                 key = ((Constant) key).GetValue ();
3523
3524                                         if (key == null)
3525                                                 key = NullLiteral.Null;
3526                                         
3527                                         string lname = null;
3528                                         if (compare_type == TypeManager.uint64_type){
3529                                                 ulong v = (ulong) key;
3530
3531                                                 if (Elements.Contains (v))
3532                                                         lname = v.ToString ();
3533                                                 else
3534                                                         Elements.Add (v, sl);
3535                                         } else if (compare_type == TypeManager.int64_type){
3536                                                 long v = (long) key;
3537
3538                                                 if (Elements.Contains (v))
3539                                                         lname = v.ToString ();
3540                                                 else
3541                                                         Elements.Add (v, sl);
3542                                         } else if (compare_type == TypeManager.uint32_type){
3543                                                 uint v = (uint) key;
3544
3545                                                 if (Elements.Contains (v))
3546                                                         lname = v.ToString ();
3547                                                 else
3548                                                         Elements.Add (v, sl);
3549                                         } else if (compare_type == TypeManager.char_type){
3550                                                 char v = (char) key;
3551                                                 
3552                                                 if (Elements.Contains (v))
3553                                                         lname = v.ToString ();
3554                                                 else
3555                                                         Elements.Add (v, sl);
3556                                         } else if (compare_type == TypeManager.byte_type){
3557                                                 byte v = (byte) key;
3558                                                 
3559                                                 if (Elements.Contains (v))
3560                                                         lname = v.ToString ();
3561                                                 else
3562                                                         Elements.Add (v, sl);
3563                                         } else if (compare_type == TypeManager.sbyte_type){
3564                                                 sbyte v = (sbyte) key;
3565                                                 
3566                                                 if (Elements.Contains (v))
3567                                                         lname = v.ToString ();
3568                                                 else
3569                                                         Elements.Add (v, sl);
3570                                         } else if (compare_type == TypeManager.short_type){
3571                                                 short v = (short) key;
3572                                                 
3573                                                 if (Elements.Contains (v))
3574                                                         lname = v.ToString ();
3575                                                 else
3576                                                         Elements.Add (v, sl);
3577                                         } else if (compare_type == TypeManager.ushort_type){
3578                                                 ushort v = (ushort) key;
3579                                                 
3580                                                 if (Elements.Contains (v))
3581                                                         lname = v.ToString ();
3582                                                 else
3583                                                         Elements.Add (v, sl);
3584                                         } else if (compare_type == TypeManager.string_type){
3585                                                 if (key is NullLiteral){
3586                                                         if (Elements.Contains (NullLiteral.Null))
3587                                                                 lname = "null";
3588                                                         else
3589                                                                 Elements.Add (NullLiteral.Null, null);
3590                                                 } else {
3591                                                         string s = (string) key;
3592
3593                                                         if (Elements.Contains (s))
3594                                                                 lname = s;
3595                                                         else
3596                                                                 Elements.Add (s, sl);
3597                                                 }
3598                                         } else if (compare_type == TypeManager.int32_type) {
3599                                                 int v = (int) key;
3600
3601                                                 if (Elements.Contains (v))
3602                                                         lname = v.ToString ();
3603                                                 else
3604                                                         Elements.Add (v, sl);
3605                                         } else if (compare_type == TypeManager.bool_type) {
3606                                                 bool v = (bool) key;
3607
3608                                                 if (Elements.Contains (v))
3609                                                         lname = v.ToString ();
3610                                                 else
3611                                                         Elements.Add (v, sl);
3612                                         }
3613                                         else
3614                                         {
3615                                                 throw new Exception ("Unknown switch type!" +
3616                                                                      SwitchType + " " + compare_type);
3617                                         }
3618
3619                                         if (lname != null){
3620                                                 error152 ("case + " + lname);
3621                                                 error = true;
3622                                         }
3623                                 }
3624                         }
3625                         if (error)
3626                                 return false;
3627                         
3628                         return true;
3629                 }
3630
3631                 void EmitObjectInteger (ILGenerator ig, object k)
3632                 {
3633                         if (k is int)
3634                                 IntConstant.EmitInt (ig, (int) k);
3635                         else if (k is Constant) {
3636                                 EmitObjectInteger (ig, ((Constant) k).GetValue ());
3637                         } 
3638                         else if (k is uint)
3639                                 IntConstant.EmitInt (ig, unchecked ((int) (uint) k));
3640                         else if (k is long)
3641                         {
3642                                 if ((long) k >= int.MinValue && (long) k <= int.MaxValue)
3643                                 {
3644                                         IntConstant.EmitInt (ig, (int) (long) k);
3645                                         ig.Emit (OpCodes.Conv_I8);
3646                                 }
3647                                 else
3648                                         LongConstant.EmitLong (ig, (long) k);
3649                         }
3650                         else if (k is ulong)
3651                         {
3652                                 if ((ulong) k < (1L<<32))
3653                                 {
3654                                         IntConstant.EmitInt (ig, (int) (long) k);
3655                                         ig.Emit (OpCodes.Conv_U8);
3656                                 }
3657                                 else
3658                                 {
3659                                         LongConstant.EmitLong (ig, unchecked ((long) (ulong) k));
3660                                 }
3661                         }
3662                         else if (k is char)
3663                                 IntConstant.EmitInt (ig, (int) ((char) k));
3664                         else if (k is sbyte)
3665                                 IntConstant.EmitInt (ig, (int) ((sbyte) k));
3666                         else if (k is byte)
3667                                 IntConstant.EmitInt (ig, (int) ((byte) k));
3668                         else if (k is short)
3669                                 IntConstant.EmitInt (ig, (int) ((short) k));
3670                         else if (k is ushort)
3671                                 IntConstant.EmitInt (ig, (int) ((ushort) k));
3672                         else if (k is bool)
3673                                 IntConstant.EmitInt (ig, ((bool) k) ? 1 : 0);
3674                         else
3675                                 throw new Exception ("Unhandled case");
3676                 }
3677                 
3678                 // structure used to hold blocks of keys while calculating table switch
3679                 class KeyBlock : IComparable
3680                 {
3681                         public KeyBlock (long _nFirst)
3682                         {
3683                                 nFirst = nLast = _nFirst;
3684                         }
3685                         public long nFirst;
3686                         public long nLast;
3687                         public ArrayList rgKeys = null;
3688                         public int Length
3689                         {
3690                                 get { return (int) (nLast - nFirst + 1); }
3691                         }
3692                         public static long TotalLength (KeyBlock kbFirst, KeyBlock kbLast)
3693                         {
3694                                 return kbLast.nLast - kbFirst.nFirst + 1;
3695                         }
3696                         public int CompareTo (object obj)
3697                         {
3698                                 KeyBlock kb = (KeyBlock) obj;
3699                                 int nLength = Length;
3700                                 int nLengthOther = kb.Length;
3701                                 if (nLengthOther == nLength)
3702                                         return (int) (kb.nFirst - nFirst);
3703                                 return nLength - nLengthOther;
3704                         }
3705                 }
3706
3707                 /// <summary>
3708                 /// This method emits code for a lookup-based switch statement (non-string)
3709                 /// Basically it groups the cases into blocks that are at least half full,
3710                 /// and then spits out individual lookup opcodes for each block.
3711                 /// It emits the longest blocks first, and short blocks are just
3712                 /// handled with direct compares.
3713                 /// </summary>
3714                 /// <param name="ec"></param>
3715                 /// <param name="val"></param>
3716                 /// <returns></returns>
3717                 bool TableSwitchEmit (EmitContext ec, LocalBuilder val)
3718                 {
3719                         int cElements = Elements.Count;
3720                         object [] rgKeys = new object [cElements];
3721                         Elements.Keys.CopyTo (rgKeys, 0);
3722                         Array.Sort (rgKeys);
3723
3724                         // initialize the block list with one element per key
3725                         ArrayList rgKeyBlocks = new ArrayList ();
3726                         foreach (object key in rgKeys)
3727                                 rgKeyBlocks.Add (new KeyBlock (Convert.ToInt64 (key)));
3728
3729                         KeyBlock kbCurr;
3730                         // iteratively merge the blocks while they are at least half full
3731                         // there's probably a really cool way to do this with a tree...
3732                         while (rgKeyBlocks.Count > 1)
3733                         {
3734                                 ArrayList rgKeyBlocksNew = new ArrayList ();
3735                                 kbCurr = (KeyBlock) rgKeyBlocks [0];
3736                                 for (int ikb = 1; ikb < rgKeyBlocks.Count; ikb++)
3737                                 {
3738                                         KeyBlock kb = (KeyBlock) rgKeyBlocks [ikb];
3739                                         if ((kbCurr.Length + kb.Length) * 2 >=  KeyBlock.TotalLength (kbCurr, kb))
3740                                         {
3741                                                 // merge blocks
3742                                                 kbCurr.nLast = kb.nLast;
3743                                         }
3744                                         else
3745                                         {
3746                                                 // start a new block
3747                                                 rgKeyBlocksNew.Add (kbCurr);
3748                                                 kbCurr = kb;
3749                                         }
3750                                 }
3751                                 rgKeyBlocksNew.Add (kbCurr);
3752                                 if (rgKeyBlocks.Count == rgKeyBlocksNew.Count)
3753                                         break;
3754                                 rgKeyBlocks = rgKeyBlocksNew;
3755                         }
3756
3757                         // initialize the key lists
3758                         foreach (KeyBlock kb in rgKeyBlocks)
3759                                 kb.rgKeys = new ArrayList ();
3760
3761                         // fill the key lists
3762                         int iBlockCurr = 0;
3763                         if (rgKeyBlocks.Count > 0) {
3764                                 kbCurr = (KeyBlock) rgKeyBlocks [0];
3765                                 foreach (object key in rgKeys)
3766                                 {
3767                                         bool fNextBlock = (key is UInt64) ? (ulong) key > (ulong) kbCurr.nLast : Convert.ToInt64 (key) > kbCurr.nLast;
3768                                         if (fNextBlock)
3769                                                 kbCurr = (KeyBlock) rgKeyBlocks [++iBlockCurr];
3770                                         kbCurr.rgKeys.Add (key);
3771                                 }
3772                         }
3773
3774                         // sort the blocks so we can tackle the largest ones first
3775                         rgKeyBlocks.Sort ();
3776
3777                         // okay now we can start...
3778                         ILGenerator ig = ec.ig;
3779                         Label lblEnd = ig.DefineLabel ();       // at the end ;-)
3780                         Label lblDefault = ig.DefineLabel ();
3781
3782                         Type typeKeys = null;
3783                         if (rgKeys.Length > 0)
3784                                 typeKeys = rgKeys [0].GetType ();       // used for conversions
3785
3786                         for (int iBlock = rgKeyBlocks.Count - 1; iBlock >= 0; --iBlock)
3787                         {
3788                                 KeyBlock kb = ((KeyBlock) rgKeyBlocks [iBlock]);
3789                                 lblDefault = (iBlock == 0) ? DefaultTarget : ig.DefineLabel ();
3790                                 if (kb.Length <= 2)
3791                                 {
3792                                         foreach (object key in kb.rgKeys)
3793                                         {
3794                                                 ig.Emit (OpCodes.Ldloc, val);
3795                                                 EmitObjectInteger (ig, key);
3796                                                 SwitchLabel sl = (SwitchLabel) Elements [key];
3797                                                 ig.Emit (OpCodes.Beq, sl.ILLabel);
3798                                         }
3799                                 }
3800                                 else
3801                                 {
3802                                         // TODO: if all the keys in the block are the same and there are
3803                                         //       no gaps/defaults then just use a range-check.
3804                                         if (SwitchType == TypeManager.int64_type ||
3805                                                 SwitchType == TypeManager.uint64_type)
3806                                         {
3807                                                 // TODO: optimize constant/I4 cases
3808
3809                                                 // check block range (could be > 2^31)
3810                                                 ig.Emit (OpCodes.Ldloc, val);
3811                                                 EmitObjectInteger (ig, Convert.ChangeType (kb.nFirst, typeKeys));
3812                                                 ig.Emit (OpCodes.Blt, lblDefault);
3813                                                 ig.Emit (OpCodes.Ldloc, val);
3814                                                 EmitObjectInteger (ig, Convert.ChangeType (kb.nFirst, typeKeys));
3815                                                 ig.Emit (OpCodes.Bgt, lblDefault);
3816
3817                                                 // normalize range
3818                                                 ig.Emit (OpCodes.Ldloc, val);
3819                                                 if (kb.nFirst != 0)
3820                                                 {
3821                                                         EmitObjectInteger (ig, Convert.ChangeType (kb.nFirst, typeKeys));
3822                                                         ig.Emit (OpCodes.Sub);
3823                                                 }
3824                                                 ig.Emit (OpCodes.Conv_I4);      // assumes < 2^31 labels!
3825                                         }
3826                                         else
3827                                         {
3828                                                 // normalize range
3829                                                 ig.Emit (OpCodes.Ldloc, val);
3830                                                 int nFirst = (int) kb.nFirst;
3831                                                 if (nFirst > 0)
3832                                                 {
3833                                                         IntConstant.EmitInt (ig, nFirst);
3834                                                         ig.Emit (OpCodes.Sub);
3835                                                 }
3836                                                 else if (nFirst < 0)
3837                                                 {
3838                                                         IntConstant.EmitInt (ig, -nFirst);
3839                                                         ig.Emit (OpCodes.Add);
3840                                                 }
3841                                         }
3842
3843                                         // first, build the list of labels for the switch
3844                                         int iKey = 0;
3845                                         int cJumps = kb.Length;
3846                                         Label [] rgLabels = new Label [cJumps];
3847                                         for (int iJump = 0; iJump < cJumps; iJump++)
3848                                         {
3849                                                 object key = kb.rgKeys [iKey];
3850                                                 if (Convert.ToInt64 (key) == kb.nFirst + iJump)
3851                                                 {
3852                                                         SwitchLabel sl = (SwitchLabel) Elements [key];
3853                                                         rgLabels [iJump] = sl.ILLabel;
3854                                                         iKey++;
3855                                                 }
3856                                                 else
3857                                                         rgLabels [iJump] = lblDefault;
3858                                         }
3859                                         // emit the switch opcode
3860                                         ig.Emit (OpCodes.Switch, rgLabels);
3861                                 }
3862
3863                                 // mark the default for this block
3864                                 if (iBlock != 0)
3865                                         ig.MarkLabel (lblDefault);
3866                         }
3867
3868                         // TODO: find the default case and emit it here,
3869                         //       to prevent having to do the following jump.
3870                         //       make sure to mark other labels in the default section
3871
3872                         // the last default just goes to the end
3873                         ig.Emit (OpCodes.Br, lblDefault);
3874
3875                         // now emit the code for the sections
3876                         bool fFoundDefault = false;
3877                         bool fAllReturn = true;
3878                         foreach (SwitchSection ss in Sections)
3879                         {
3880                                 foreach (SwitchLabel sl in ss.Labels)
3881                                 {
3882                                         ig.MarkLabel (sl.ILLabel);
3883                                         ig.MarkLabel (sl.ILLabelCode);
3884                                         if (sl.Label == null)
3885                                         {
3886                                                 ig.MarkLabel (lblDefault);
3887                                                 fFoundDefault = true;
3888                                         }
3889                                 }
3890                                 bool returns = ss.Block.Emit (ec);
3891                                 fAllReturn &= returns;
3892                                 //ig.Emit (OpCodes.Br, lblEnd);
3893                         }
3894                         
3895                         if (!fFoundDefault) {
3896                                 ig.MarkLabel (lblDefault);
3897                                 fAllReturn = false;
3898                         }
3899                         ig.MarkLabel (lblEnd);
3900
3901                         return fAllReturn;
3902                 }
3903                 //
3904                 // This simple emit switch works, but does not take advantage of the
3905                 // `switch' opcode. 
3906                 // TODO: remove non-string logic from here
3907                 // TODO: binary search strings?
3908                 //
3909                 bool SimpleSwitchEmit (EmitContext ec, LocalBuilder val)
3910                 {
3911                         ILGenerator ig = ec.ig;
3912                         Label end_of_switch = ig.DefineLabel ();
3913                         Label next_test = ig.DefineLabel ();
3914                         Label null_target = ig.DefineLabel ();
3915                         bool default_found = false;
3916                         bool first_test = true;
3917                         bool pending_goto_end = false;
3918                         bool all_return = true;
3919                         bool is_string = false;
3920                         bool null_found;
3921                         
3922                         //
3923                         // Special processing for strings: we cant compare
3924                         // against null.
3925                         //
3926                         if (SwitchType == TypeManager.string_type){
3927                                 ig.Emit (OpCodes.Ldloc, val);
3928                                 is_string = true;
3929                                 
3930                                 if (Elements.Contains (NullLiteral.Null)){
3931                                         ig.Emit (OpCodes.Brfalse, null_target);
3932                                 } else
3933                                         ig.Emit (OpCodes.Brfalse, default_target);
3934
3935                                 ig.Emit (OpCodes.Ldloc, val);
3936                                 ig.Emit (OpCodes.Call, TypeManager.string_isinterneted_string);
3937                                 ig.Emit (OpCodes.Stloc, val);
3938                         }
3939                         
3940                         foreach (SwitchSection ss in Sections){
3941                                 Label sec_begin = ig.DefineLabel ();
3942
3943                                 if (pending_goto_end)
3944                                         ig.Emit (OpCodes.Br, end_of_switch);
3945
3946                                 int label_count = ss.Labels.Count;
3947                                 null_found = false;
3948                                 foreach (SwitchLabel sl in ss.Labels){
3949                                         ig.MarkLabel (sl.ILLabel);
3950                                         
3951                                         if (!first_test){
3952                                                 ig.MarkLabel (next_test);
3953                                                 next_test = ig.DefineLabel ();
3954                                         }
3955                                         //
3956                                         // If we are the default target
3957                                         //
3958                                         if (sl.Label == null){
3959                                                 ig.MarkLabel (default_target);
3960                                                 default_found = true;
3961                                         } else {
3962                                                 object lit = sl.Converted;
3963
3964                                                 if (lit is NullLiteral){
3965                                                         null_found = true;
3966                                                         if (label_count == 1)
3967                                                                 ig.Emit (OpCodes.Br, next_test);
3968                                                         continue;
3969                                                                               
3970                                                 }
3971                                                 if (is_string){
3972                                                         StringConstant str = (StringConstant) lit;
3973
3974                                                         ig.Emit (OpCodes.Ldloc, val);
3975                                                         ig.Emit (OpCodes.Ldstr, str.Value);
3976                                                         if (label_count == 1)
3977                                                                 ig.Emit (OpCodes.Bne_Un, next_test);
3978                                                         else
3979                                                                 ig.Emit (OpCodes.Beq, sec_begin);
3980                                                 } else {
3981                                                         ig.Emit (OpCodes.Ldloc, val);
3982                                                         EmitObjectInteger (ig, lit);
3983                                                         ig.Emit (OpCodes.Ceq);
3984                                                         if (label_count == 1)
3985                                                                 ig.Emit (OpCodes.Brfalse, next_test);
3986                                                         else
3987                                                                 ig.Emit (OpCodes.Brtrue, sec_begin);
3988                                                 }
3989                                         }
3990                                 }
3991                                 if (label_count != 1)
3992                                         ig.Emit (OpCodes.Br, next_test);
3993                                 
3994                                 if (null_found)
3995                                         ig.MarkLabel (null_target);
3996                                 ig.MarkLabel (sec_begin);
3997                                 foreach (SwitchLabel sl in ss.Labels)
3998                                         ig.MarkLabel (sl.ILLabelCode);
3999
4000                                 bool returns = ss.Block.Emit (ec);
4001                                 if (returns)
4002                                         pending_goto_end = false;
4003                                 else {
4004                                         all_return = false;
4005                                         pending_goto_end = true;
4006                                 }
4007                                 first_test = false;
4008                         }
4009                         if (!default_found){
4010                                 ig.MarkLabel (default_target);
4011                                 all_return = false;
4012                         }
4013                         ig.MarkLabel (next_test);
4014                         ig.MarkLabel (end_of_switch);
4015                         
4016                         return all_return;
4017                 }
4018
4019                 public override bool Resolve (EmitContext ec)
4020                 {
4021                         Expr = Expr.Resolve (ec);
4022                         if (Expr == null)
4023                                 return false;
4024
4025                         new_expr = SwitchGoverningType (ec, Expr.Type);
4026                         if (new_expr == null){
4027                                 Report.Error (151, loc, "An integer type or string was expected for switch");
4028                                 return false;
4029                         }
4030
4031                         // Validate switch.
4032                         SwitchType = new_expr.Type;
4033
4034                         if (!CheckSwitch (ec))
4035                                 return false;
4036
4037                         Switch old_switch = ec.Switch;
4038                         ec.Switch = this;
4039                         ec.Switch.SwitchType = SwitchType;
4040
4041                         ec.StartFlowBranching (FlowBranchingType.SWITCH, loc);
4042
4043                         bool first = true;
4044                         foreach (SwitchSection ss in Sections){
4045                                 if (!first)
4046                                         ec.CurrentBranching.CreateSibling ();
4047                                 else
4048                                         first = false;
4049
4050                                 if (ss.Block.Resolve (ec) != true)
4051                                         return false;
4052                         }
4053
4054
4055                         if (!got_default)
4056                                 ec.CurrentBranching.CreateSibling ();
4057
4058                         ec.EndFlowBranching ();
4059                         ec.Switch = old_switch;
4060
4061                         return true;
4062                 }
4063                 
4064                 protected override bool DoEmit (EmitContext ec)
4065                 {
4066                         // Store variable for comparission purposes
4067                         LocalBuilder value = ec.ig.DeclareLocal (SwitchType);
4068                         new_expr.Emit (ec);
4069                         ec.ig.Emit (OpCodes.Stloc, value);
4070
4071                         ILGenerator ig = ec.ig;
4072
4073                         default_target = ig.DefineLabel ();
4074
4075                         //
4076                         // Setup the codegen context
4077                         //
4078                         Label old_end = ec.LoopEnd;
4079                         Switch old_switch = ec.Switch;
4080                         
4081                         ec.LoopEnd = ig.DefineLabel ();
4082                         ec.Switch = this;
4083
4084                         // Emit Code.
4085                         bool all_return;
4086                         if (SwitchType == TypeManager.string_type)
4087                                 all_return = SimpleSwitchEmit (ec, value);
4088                         else
4089                                 all_return = TableSwitchEmit (ec, value);
4090
4091                         // Restore context state. 
4092                         ig.MarkLabel (ec.LoopEnd);
4093
4094                         //
4095                         // Restore the previous context
4096                         //
4097                         ec.LoopEnd = old_end;
4098                         ec.Switch = old_switch;
4099                         
4100                         return all_return;
4101                 }
4102         }
4103
4104         public class Lock : Statement {
4105                 Expression expr;
4106                 Statement Statement;
4107                         
4108                 public Lock (Expression expr, Statement stmt, Location l)
4109                 {
4110                         this.expr = expr;
4111                         Statement = stmt;
4112                         loc = l;
4113                 }
4114
4115                 public override bool Resolve (EmitContext ec)
4116                 {
4117                         expr = expr.Resolve (ec);
4118                         return Statement.Resolve (ec) && expr != null;
4119                 }
4120                 
4121                 protected override bool DoEmit (EmitContext ec)
4122                 {
4123                         Type type = expr.Type;
4124                         bool val;
4125                         
4126                         if (type.IsValueType){
4127                                 Report.Error (30582, loc, "lock statement requires the expression to be " +
4128                                               " a reference type (type is: `" +
4129                                               TypeManager.MonoBASIC_Name (type) + "'");
4130                                 return false;
4131                         }
4132
4133                         ILGenerator ig = ec.ig;
4134                         LocalBuilder temp = ig.DeclareLocal (type);
4135                                 
4136                         expr.Emit (ec);
4137                         ig.Emit (OpCodes.Dup);
4138                         ig.Emit (OpCodes.Stloc, temp);
4139                         ig.Emit (OpCodes.Call, TypeManager.void_monitor_enter_object);
4140
4141                         // try
4142                         ig.BeginExceptionBlock ();
4143                         bool old_in_try = ec.InTry;
4144                         ec.InTry = true;
4145                         Label finish = ig.DefineLabel ();
4146                         val = Statement.Emit (ec);
4147                         ec.InTry = old_in_try;
4148                         // ig.Emit (OpCodes.Leave, finish);
4149
4150                         ig.MarkLabel (finish);
4151                         
4152                         // finally
4153                         ig.BeginFinallyBlock ();
4154                         ig.Emit (OpCodes.Ldloc, temp);
4155                         ig.Emit (OpCodes.Call, TypeManager.void_monitor_exit_object);
4156                         ig.EndExceptionBlock ();
4157                         
4158                         return val;
4159                 }
4160         }
4161
4162         public class Unchecked : Statement {
4163                 public readonly Block Block;
4164                 
4165                 public Unchecked (Block b)
4166                 {
4167                         Block = b;
4168                 }
4169
4170                 public override bool Resolve (EmitContext ec)
4171                 {
4172                         return Block.Resolve (ec);
4173                 }
4174                 
4175                 protected override bool DoEmit (EmitContext ec)
4176                 {
4177                         bool previous_state = ec.CheckState;
4178                         bool previous_state_const = ec.ConstantCheckState;
4179                         bool val;
4180                         
4181                         ec.CheckState = false;
4182                         ec.ConstantCheckState = false;
4183                         val = Block.Emit (ec);
4184                         ec.CheckState = previous_state;
4185                         ec.ConstantCheckState = previous_state_const;
4186
4187                         return val;
4188                 }
4189         }
4190
4191         public class Checked : Statement {
4192                 public readonly Block Block;
4193                 
4194                 public Checked (Block b)
4195                 {
4196                         Block = b;
4197                 }
4198
4199                 public override bool Resolve (EmitContext ec)
4200                 {
4201                         bool previous_state = ec.CheckState;
4202                         bool previous_state_const = ec.ConstantCheckState;
4203                         
4204                         ec.CheckState = true;
4205                         ec.ConstantCheckState = true;
4206                         bool ret = Block.Resolve (ec);
4207                         ec.CheckState = previous_state;
4208                         ec.ConstantCheckState = previous_state_const;
4209
4210                         return ret;
4211                 }
4212
4213                 protected override bool DoEmit (EmitContext ec)
4214                 {
4215                         bool previous_state = ec.CheckState;
4216                         bool previous_state_const = ec.ConstantCheckState;
4217                         bool val;
4218                         
4219                         ec.CheckState = true;
4220                         ec.ConstantCheckState = true;
4221                         val = Block.Emit (ec);
4222                         ec.CheckState = previous_state;
4223                         ec.ConstantCheckState = previous_state_const;
4224
4225                         return val;
4226                 }
4227         }
4228
4229         public class Unsafe : Statement {
4230                 public readonly Block Block;
4231
4232                 public Unsafe (Block b)
4233                 {
4234                         Block = b;
4235                 }
4236
4237                 public override bool Resolve (EmitContext ec)
4238                 {
4239                         bool previous_state = ec.InUnsafe;
4240                         bool val;
4241                         
4242                         ec.InUnsafe = true;
4243                         val = Block.Resolve (ec);
4244                         ec.InUnsafe = previous_state;
4245
4246                         return val;
4247                 }
4248                 
4249                 protected override bool DoEmit (EmitContext ec)
4250                 {
4251                         bool previous_state = ec.InUnsafe;
4252                         bool val;
4253                         
4254                         ec.InUnsafe = true;
4255                         val = Block.Emit (ec);
4256                         ec.InUnsafe = previous_state;
4257
4258                         return val;
4259                 }
4260         }
4261
4262         // 
4263         // Fixed statement
4264         //
4265         public class Fixed : Statement {
4266                 Expression type;
4267                 ArrayList declarators;
4268                 Statement statement;
4269                 Type expr_type;
4270                 FixedData[] data;
4271
4272                 struct FixedData {
4273                         public bool is_object;
4274                         public VariableInfo vi;
4275                         public Expression expr;
4276                         public Expression converted;
4277                 }                       
4278
4279                 public Fixed (Expression type, ArrayList decls, Statement stmt, Location l)
4280                 {
4281                         this.type = type;
4282                         declarators = decls;
4283                         statement = stmt;
4284                         loc = l;
4285                 }
4286
4287                 public override bool Resolve (EmitContext ec)
4288                 {
4289                         expr_type = ec.DeclSpace.ResolveType (type, false, loc);
4290                         if (expr_type == null)
4291                                 return false;
4292
4293                         data = new FixedData [declarators.Count];
4294
4295                         int i = 0;
4296                         foreach (Pair p in declarators){
4297                                 VariableInfo vi = (VariableInfo) p.First;
4298                                 Expression e = (Expression) p.Second;
4299
4300                                 vi.Number = -1;
4301
4302                                 //
4303                                 // The rules for the possible declarators are pretty wise,
4304                                 // but the production on the grammar is more concise.
4305                                 //
4306                                 // So we have to enforce these rules here.
4307                                 //
4308                                 // We do not resolve before doing the case 1 test,
4309                                 // because the grammar is explicit in that the token &
4310                                 // is present, so we need to test for this particular case.
4311                                 //
4312
4313                                 //
4314                                 // Case 1: & object.
4315                                 //
4316                                 if (e is Unary && ((Unary) e).Oper == Unary.Operator.AddressOf){
4317                                         Expression child = ((Unary) e).Expr;
4318
4319                                         vi.MakePinned ();
4320                                         if (child is ParameterReference || child is LocalVariableReference){
4321                                                 Report.Error (
4322                                                         213, loc, 
4323                                                         "No need to use fixed statement for parameters or " +
4324                                                         "local variable declarations (address is already " +
4325                                                         "fixed)");
4326                                                 return false;
4327                                         }
4328                                         
4329                                         e = e.Resolve (ec);
4330                                         if (e == null)
4331                                                 return false;
4332
4333                                         child = ((Unary) e).Expr;
4334                                         
4335                                         if (!TypeManager.VerifyUnManaged (child.Type, loc))
4336                                                 return false;
4337
4338                                         data [i].is_object = true;
4339                                         data [i].expr = e;
4340                                         data [i].converted = null;
4341                                         data [i].vi = vi;
4342                                         i++;
4343
4344                                         continue;
4345                                 }
4346
4347                                 e = e.Resolve (ec);
4348                                 if (e == null)
4349                                         return false;
4350
4351                                 //
4352                                 // Case 2: Array
4353                                 //
4354                                 if (e.Type.IsArray){
4355                                         Type array_type = e.Type.GetElementType ();
4356                                         
4357                                         vi.MakePinned ();
4358                                         //
4359                                         // Provided that array_type is unmanaged,
4360                                         //
4361                                         if (!TypeManager.VerifyUnManaged (array_type, loc))
4362                                                 return false;
4363
4364                                         //
4365                                         // and T* is implicitly convertible to the
4366                                         // pointer type given in the fixed statement.
4367                                         //
4368                                         ArrayPtr array_ptr = new ArrayPtr (e, loc);
4369                                         
4370                                         Expression converted = Expression.ConvertImplicitRequired (
4371                                                 ec, array_ptr, vi.VariableType, loc);
4372                                         if (converted == null)
4373                                                 return false;
4374
4375                                         data [i].is_object = false;
4376                                         data [i].expr = e;
4377                                         data [i].converted = converted;
4378                                         data [i].vi = vi;
4379                                         i++;
4380
4381                                         continue;
4382                                 }
4383
4384                                 //
4385                                 // Case 3: string
4386                                 //
4387                                 if (e.Type == TypeManager.string_type){
4388                                         data [i].is_object = false;
4389                                         data [i].expr = e;
4390                                         data [i].converted = null;
4391                                         data [i].vi = vi;
4392                                         i++;
4393                                 }
4394                         }
4395
4396                         return statement.Resolve (ec);
4397                 }
4398                 
4399                 protected override bool DoEmit (EmitContext ec)
4400                 {
4401                         ILGenerator ig = ec.ig;
4402
4403                         bool is_ret = false;
4404
4405                         for (int i = 0; i < data.Length; i++) {
4406                                 VariableInfo vi = data [i].vi;
4407
4408                                 //
4409                                 // Case 1: & object.
4410                                 //
4411                                 if (data [i].is_object) {
4412                                         //
4413                                         // Store pointer in pinned location
4414                                         //
4415                                         data [i].expr.Emit (ec);
4416                                         ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
4417
4418                                         is_ret = statement.Emit (ec);
4419
4420                                         // Clear the pinned variable.
4421                                         ig.Emit (OpCodes.Ldc_I4_0);
4422                                         ig.Emit (OpCodes.Conv_U);
4423                                         ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
4424
4425                                         continue;
4426                                 }
4427
4428                                 //
4429                                 // Case 2: Array
4430                                 //
4431                                 if (data [i].expr.Type.IsArray){
4432                                         //
4433                                         // Store pointer in pinned location
4434                                         //
4435                                         data [i].converted.Emit (ec);
4436                                         
4437                                         ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
4438
4439                                         is_ret = statement.Emit (ec);
4440                                         
4441                                         // Clear the pinned variable.
4442                                         ig.Emit (OpCodes.Ldc_I4_0);
4443                                         ig.Emit (OpCodes.Conv_U);
4444                                         ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
4445
4446                                         continue;
4447                                 }
4448
4449                                 //
4450                                 // Case 3: string
4451                                 //
4452                                 if (data [i].expr.Type == TypeManager.string_type){
4453                                         LocalBuilder pinned_string = ig.DeclareLocal (TypeManager.string_type);
4454                                         TypeManager.MakePinned (pinned_string);
4455                                         
4456                                         data [i].expr.Emit (ec);
4457                                         ig.Emit (OpCodes.Stloc, pinned_string);
4458
4459                                         Expression sptr = new StringPtr (pinned_string, loc);
4460                                         Expression converted = Expression.ConvertImplicitRequired (
4461                                                 ec, sptr, vi.VariableType, loc);
4462                                         
4463                                         if (converted == null)
4464                                                 continue;
4465
4466                                         converted.Emit (ec);
4467                                         ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
4468                                         
4469                                         is_ret = statement.Emit (ec);
4470
4471                                         // Clear the pinned variable
4472                                         ig.Emit (OpCodes.Ldnull);
4473                                         ig.Emit (OpCodes.Stloc, pinned_string);
4474                                 }
4475                         }
4476
4477                         return is_ret;
4478                 }
4479         }
4480         
4481         public class Catch {
4482                 public readonly string Name;
4483                 public readonly Block  Block;
4484                 public Expression Clause;
4485                 public readonly Location Location;
4486
4487                 Expression type_expr;
4488                 //Expression clus_expr;
4489                 Type type;
4490                 
4491                 public Catch (Expression type, string name, Block block, Expression clause, Location l)
4492                 {
4493                         type_expr = type;
4494                         Name = name;
4495                         Block = block;
4496                         Clause = clause;
4497                         Location = l;
4498                 }
4499
4500                 public Type CatchType {
4501                         get {
4502                                 return type;
4503                         }
4504                 }
4505
4506                 public bool IsGeneral {
4507                         get {
4508                                 return type_expr == null;
4509                         }
4510                 }
4511
4512                 public bool Resolve (EmitContext ec)
4513                 {
4514                         if (type_expr != null) {
4515                                 type = ec.DeclSpace.ResolveType (type_expr, false, Location);
4516                                 if (type == null)
4517                                         return false;
4518
4519                                 if (type != TypeManager.exception_type && !type.IsSubclassOf (TypeManager.exception_type)){
4520                                         Report.Error (30665, Location,
4521                                                       "The type caught or thrown must be derived " +
4522                                                       "from System.Exception");
4523                                         return false;
4524                                 }
4525                         } else
4526                                 type = null;
4527
4528                         if (Clause != null)     {
4529                                 Clause = Statement.ResolveBoolean (ec, Clause, Location);
4530                                 if (Clause == null) {
4531                                         return false;
4532                                 }
4533                         }
4534
4535                         if (!Block.Resolve (ec))
4536                                 return false;
4537
4538                         return true;
4539                 }
4540         }
4541
4542         public class Try : Statement {
4543                 public readonly Block Fini, Block;
4544                 public readonly ArrayList Specific;
4545                 public readonly Catch General;
4546                 
4547                 //
4548                 // specific, general and fini might all be null.
4549                 //
4550                 public Try (Block block, ArrayList specific, Catch general, Block fini, Location l)
4551                 {
4552                         if (specific == null && general == null){
4553                                 Console.WriteLine ("CIR.Try: Either specific or general have to be non-null");
4554                         }
4555                         
4556                         this.Block = block;
4557                         this.Specific = specific;
4558                         this.General = general;
4559                         this.Fini = fini;
4560                         loc = l;
4561                 }
4562
4563                 public override bool Resolve (EmitContext ec)
4564                 {
4565                         bool ok = true;
4566                         
4567                         ec.StartFlowBranching (FlowBranchingType.EXCEPTION, Block.StartLocation);
4568
4569                         Report.Debug (1, "START OF TRY BLOCK", Block.StartLocation);
4570
4571                         bool old_in_try = ec.InTry;
4572                         ec.InTry = true;
4573
4574                         if (!Block.Resolve (ec))
4575                                 ok = false;
4576
4577                         ec.InTry = old_in_try;
4578
4579                         FlowBranching.UsageVector vector = ec.CurrentBranching.CurrentUsageVector;
4580
4581                         Report.Debug (1, "START OF CATCH BLOCKS", vector);
4582
4583                         foreach (Catch c in Specific){
4584                                 ec.CurrentBranching.CreateSibling ();
4585                                 Report.Debug (1, "STARTED SIBLING FOR CATCH", ec.CurrentBranching);
4586
4587                                 if (c.Name != null) {
4588                                         VariableInfo vi = c.Block.GetVariableInfo (c.Name);
4589                                         if (vi == null)
4590                                                 throw new Exception ();
4591
4592                                         vi.Number = -1;
4593                                 }
4594
4595                                 bool old_in_catch = ec.InCatch;
4596                                 ec.InCatch = true;
4597
4598                                 if (!c.Resolve (ec))
4599                                         ok = false;
4600
4601                                 ec.InCatch = old_in_catch;
4602
4603                                 FlowBranching.UsageVector current = ec.CurrentBranching.CurrentUsageVector;
4604
4605                                 if (!current.AlwaysReturns && !current.AlwaysBreaks)
4606                                         vector.AndLocals (current);
4607                         }
4608
4609                         Report.Debug (1, "END OF CATCH BLOCKS", ec.CurrentBranching);
4610
4611                         if (General != null){
4612                                 ec.CurrentBranching.CreateSibling ();
4613                                 Report.Debug (1, "STARTED SIBLING FOR GENERAL", ec.CurrentBranching);
4614
4615                                 bool old_in_catch = ec.InCatch;
4616                                 ec.InCatch = true;
4617
4618                                 if (!General.Resolve (ec))
4619                                         ok = false;
4620
4621                                 ec.InCatch = old_in_catch;
4622
4623                                 FlowBranching.UsageVector current = ec.CurrentBranching.CurrentUsageVector;
4624
4625                                 if (!current.AlwaysReturns && !current.AlwaysBreaks)
4626                                         vector.AndLocals (current);
4627                         }
4628
4629                         Report.Debug (1, "END OF GENERAL CATCH BLOCKS", ec.CurrentBranching);
4630
4631                         if (Fini != null) {
4632                                 ec.CurrentBranching.CreateSiblingForFinally ();
4633                                 Report.Debug (1, "STARTED SIBLING FOR FINALLY", ec.CurrentBranching, vector);
4634
4635                                 bool old_in_finally = ec.InFinally;
4636                                 ec.InFinally = true;
4637
4638                                 if (!Fini.Resolve (ec))
4639                                         ok = false;
4640
4641                                 ec.InFinally = old_in_finally;
4642                         }
4643
4644                         FlowReturns returns = ec.EndFlowBranching ();
4645
4646                         FlowBranching.UsageVector f_vector = ec.CurrentBranching.CurrentUsageVector;
4647
4648                         Report.Debug (1, "END OF FINALLY", ec.CurrentBranching, returns, vector, f_vector);
4649
4650                         if ((returns == FlowReturns.SOMETIMES) || (returns == FlowReturns.ALWAYS)) {
4651                                 ec.CurrentBranching.CheckOutParameters (f_vector.Parameters, loc);
4652                         }
4653
4654                         ec.CurrentBranching.CurrentUsageVector.Or (vector);
4655
4656                         Report.Debug (1, "END OF TRY", ec.CurrentBranching);
4657
4658                         return ok;
4659                 }
4660                 
4661                 protected override bool DoEmit (EmitContext ec)
4662                 {
4663                         ILGenerator ig = ec.ig;
4664                         Label finish = ig.DefineLabel ();;
4665                         bool returns;
4666
4667                         ec.TryCatchLevel++;
4668                         ig.BeginExceptionBlock ();
4669                         bool old_in_try = ec.InTry;
4670                         ec.InTry = true;
4671                         returns = Block.Emit (ec);
4672                         ec.InTry = old_in_try;
4673
4674                         //
4675                         // System.Reflection.Emit provides this automatically:
4676                         // ig.Emit (OpCodes.Leave, finish);
4677
4678                         bool old_in_catch = ec.InCatch;
4679                         ec.InCatch = true;
4680                         //DeclSpace ds = ec.DeclSpace;
4681
4682                         foreach (Catch c in Specific){
4683                                 VariableInfo vi;
4684                                 
4685                                 ig.BeginCatchBlock (c.CatchType);
4686
4687                                 if (c.Name != null){
4688                                         vi = c.Block.GetVariableInfo (c.Name);
4689                                         if (vi == null)
4690                                                 throw new Exception ("Variable does not exist in this block");
4691
4692                                         ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
4693                                 } else
4694                                         ig.Emit (OpCodes.Pop);
4695
4696                                 //
4697                                 // if when clause is there
4698                                 //
4699                                 if (c.Clause != null) {
4700                                         if (c.Clause is BoolConstant) {
4701                                                 bool take = ((BoolConstant) c.Clause).Value;
4702
4703                                                 if (take) 
4704                                                         if (!c.Block.Emit (ec))
4705                                                                 returns = false;
4706                                         } else {
4707                                                 EmitBoolExpression (ec, c.Clause, finish, false);
4708                                                 if (!c.Block.Emit (ec))
4709                                                         returns = false;
4710                                         }
4711                                 } else 
4712                                         if (!c.Block.Emit (ec))
4713                                                 returns = false;
4714                         }
4715
4716                         if (General != null){
4717                                 ig.BeginCatchBlock (TypeManager.object_type);
4718                                 ig.Emit (OpCodes.Pop);
4719
4720                                 if (General.Clause != null) {
4721                                         if (General.Clause is BoolConstant) {
4722                                                 bool take = ((BoolConstant) General.Clause).Value;
4723                                                 if (take) 
4724                                                         if (!General.Block.Emit (ec))
4725                                                                 returns = false;
4726                                         } else {
4727                                                 EmitBoolExpression (ec, General.Clause, finish, false);
4728                                                 if (!General.Block.Emit (ec))
4729                                                         returns = false;
4730                                         }
4731                                 } else 
4732                                         if (!General.Block.Emit (ec))
4733                                                 returns = false;
4734                         }
4735
4736                         ec.InCatch = old_in_catch;
4737
4738                         ig.MarkLabel (finish);
4739                         if (Fini != null){
4740                                 ig.BeginFinallyBlock ();
4741                                 bool old_in_finally = ec.InFinally;
4742                                 ec.InFinally = true;
4743                                 Fini.Emit (ec);
4744                                 ec.InFinally = old_in_finally;
4745                         }
4746                         
4747                         ig.EndExceptionBlock ();
4748                         ec.TryCatchLevel--;
4749
4750                         if (!returns || ec.InTry || ec.InCatch)
4751                                 return returns;
4752
4753                         // Unfortunately, System.Reflection.Emit automatically emits a leave
4754                         // to the end of the finally block.  This is a problem if `returns'
4755                         // is true since we may jump to a point after the end of the method.
4756                         // As a workaround, emit an explicit ret here.
4757
4758                         if (ec.ReturnType != null)
4759                                 ec.ig.Emit (OpCodes.Ldloc, ec.TemporaryReturn ());
4760                         ec.ig.Emit (OpCodes.Ret);
4761
4762                         return true;
4763                 }
4764         }
4765
4766         public class Using : Statement {
4767                 object expression_or_block;
4768                 Statement Statement;
4769                 ArrayList var_list;
4770                 Expression expr;
4771                 Type expr_type;
4772                 Expression conv;
4773                 Expression [] converted_vars;
4774                 ExpressionStatement [] assign;
4775                 
4776                 public Using (object expression_or_block, Statement stmt, Location l)
4777                 {
4778                         this.expression_or_block = expression_or_block;
4779                         Statement = stmt;
4780                         loc = l;
4781                 }
4782
4783                 //
4784                 // Resolves for the case of using using a local variable declaration.
4785                 //
4786                 bool ResolveLocalVariableDecls (EmitContext ec)
4787                 {
4788                         bool need_conv = false;
4789                         expr_type = ec.DeclSpace.ResolveType (expr, false, loc);
4790                         int i = 0;
4791
4792                         if (expr_type == null)
4793                                 return false;
4794
4795                         //
4796                         // The type must be an IDisposable or an implicit conversion
4797                         // must exist.
4798                         //
4799                         converted_vars = new Expression [var_list.Count];
4800                         assign = new ExpressionStatement [var_list.Count];
4801                         if (!TypeManager.ImplementsInterface (expr_type, TypeManager.idisposable_type)){
4802                                 foreach (DictionaryEntry e in var_list){
4803                                         Expression var = (Expression) e.Key;
4804
4805                                         var = var.ResolveLValue (ec, new EmptyExpression ());
4806                                         if (var == null)
4807                                                 return false;
4808                                         
4809                                         converted_vars [i] = Expression.ConvertImplicitRequired (
4810                                                 ec, var, TypeManager.idisposable_type, loc);
4811
4812                                         if (converted_vars [i] == null)
4813                                                 return false;
4814                                         i++;
4815                                 }
4816                                 need_conv = true;
4817                         }
4818
4819                         i = 0;
4820                         foreach (DictionaryEntry e in var_list){
4821                                 LocalVariableReference var = (LocalVariableReference) e.Key;
4822                                 Expression new_expr = (Expression) e.Value;
4823                                 Expression a;
4824
4825                                 a = new Assign (var, new_expr, loc);
4826                                 a = a.Resolve (ec);
4827                                 if (a == null)
4828                                         return false;
4829
4830                                 if (!need_conv)
4831                                         converted_vars [i] = var;
4832                                 assign [i] = (ExpressionStatement) a;
4833                                 i++;
4834                         }
4835
4836                         return true;
4837                 }
4838
4839                 bool ResolveExpression (EmitContext ec)
4840                 {
4841                         if (!TypeManager.ImplementsInterface (expr_type, TypeManager.idisposable_type)){
4842                                 conv = Expression.ConvertImplicitRequired (
4843                                         ec, expr, TypeManager.idisposable_type, loc);
4844
4845                                 if (conv == null)
4846                                         return false;
4847                         }
4848
4849                         return true;
4850                 }
4851                 
4852                 //
4853                 // Emits the code for the case of using using a local variable declaration.
4854                 //
4855                 bool EmitLocalVariableDecls (EmitContext ec)
4856                 {
4857                         ILGenerator ig = ec.ig;
4858                         int i = 0;
4859
4860                         bool old_in_try = ec.InTry;
4861                         ec.InTry = true;
4862                         for (i = 0; i < assign.Length; i++) {
4863                                 assign [i].EmitStatement (ec);
4864                                 
4865                                 ig.BeginExceptionBlock ();
4866                         }
4867                         Statement.Emit (ec);
4868                         ec.InTry = old_in_try;
4869
4870                         bool old_in_finally = ec.InFinally;
4871                         ec.InFinally = true;
4872                         var_list.Reverse ();
4873                         foreach (DictionaryEntry e in var_list){
4874                                 LocalVariableReference var = (LocalVariableReference) e.Key;
4875                                 Label skip = ig.DefineLabel ();
4876                                 i--;
4877                                 
4878                                 ig.BeginFinallyBlock ();
4879                                 
4880                                 var.Emit (ec);
4881                                 ig.Emit (OpCodes.Brfalse, skip);
4882                                 converted_vars [i].Emit (ec);
4883                                 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
4884                                 ig.MarkLabel (skip);
4885                                 ig.EndExceptionBlock ();
4886                         }
4887                         ec.InFinally = old_in_finally;
4888
4889                         return false;
4890                 }
4891
4892                 bool EmitExpression (EmitContext ec)
4893                 {
4894                         //
4895                         // Make a copy of the expression and operate on that.
4896                         //
4897                         ILGenerator ig = ec.ig;
4898                         LocalBuilder local_copy = ig.DeclareLocal (expr_type);
4899                         if (conv != null)
4900                                 conv.Emit (ec);
4901                         else
4902                                 expr.Emit (ec);
4903                         ig.Emit (OpCodes.Stloc, local_copy);
4904
4905                         bool old_in_try = ec.InTry;
4906                         ec.InTry = true;
4907                         ig.BeginExceptionBlock ();
4908                         Statement.Emit (ec);
4909                         ec.InTry = old_in_try;
4910                         
4911                         Label skip = ig.DefineLabel ();
4912                         bool old_in_finally = ec.InFinally;
4913                         ig.BeginFinallyBlock ();
4914                         ig.Emit (OpCodes.Ldloc, local_copy);
4915                         ig.Emit (OpCodes.Brfalse, skip);
4916                         ig.Emit (OpCodes.Ldloc, local_copy);
4917                         ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
4918                         ig.MarkLabel (skip);
4919                         ec.InFinally = old_in_finally;
4920                         ig.EndExceptionBlock ();
4921
4922                         return false;
4923                 }
4924                 
4925                 public override bool Resolve (EmitContext ec)
4926                 {
4927                         if (expression_or_block is DictionaryEntry){
4928                                 expr = (Expression) ((DictionaryEntry) expression_or_block).Key;
4929                                 var_list = (ArrayList)((DictionaryEntry)expression_or_block).Value;
4930
4931                                 if (!ResolveLocalVariableDecls (ec))
4932                                         return false;
4933
4934                         } else if (expression_or_block is Expression){
4935                                 expr = (Expression) expression_or_block;
4936
4937                                 expr = expr.Resolve (ec);
4938                                 if (expr == null)
4939                                         return false;
4940
4941                                 expr_type = expr.Type;
4942
4943                                 if (!ResolveExpression (ec))
4944                                         return false;
4945                         }                       
4946
4947                         return Statement.Resolve (ec);
4948                 }
4949                 
4950                 protected override bool DoEmit (EmitContext ec)
4951                 {
4952                         if (expression_or_block is DictionaryEntry)
4953                                 return EmitLocalVariableDecls (ec);
4954                         else if (expression_or_block is Expression)
4955                                 return EmitExpression (ec);
4956
4957                         return false;
4958                 }
4959         }
4960
4961         /// <summary>
4962         ///   Implementation of the foreach C# statement
4963         /// </summary>
4964         public class Foreach : Statement {
4965                 Expression type;
4966                 LocalVariableReference variable;
4967                 Expression expr;
4968                 Statement statement;
4969                 ForeachHelperMethods hm;
4970                 Expression empty, conv;
4971                 Type array_type, element_type;
4972                 Type var_type;
4973                 
4974                 public Foreach (Expression type, LocalVariableReference var, Expression expr,
4975                                 Statement stmt, Location l)
4976                 {
4977                         if (type != null) {
4978                                 this.type = type;
4979                         }
4980                         else
4981                         {
4982                                 VariableInfo vi = var.VariableInfo;
4983                                 this.type = vi.Type;
4984                         }
4985                         this.variable = var;
4986                         this.expr = expr;
4987                         statement = stmt;
4988                         loc = l;
4989                 }
4990                 
4991                 public override bool Resolve (EmitContext ec)
4992                 {       
4993                         expr = expr.Resolve (ec);
4994                         if (expr == null)
4995                                 return false;
4996
4997                         var_type = ec.DeclSpace.ResolveType (type, false, loc);
4998                         if (var_type == null)
4999                                 return false;
5000                         
5001                         //
5002                         // We need an instance variable.  Not sure this is the best
5003                         // way of doing this.
5004                         //
5005                         // FIXME: When we implement propertyaccess, will those turn
5006                         // out to return values in ExprClass?  I think they should.
5007                         //
5008                         if (!(expr.eclass == ExprClass.Variable || expr.eclass == ExprClass.Value ||
5009                               expr.eclass == ExprClass.PropertyAccess || expr.eclass == ExprClass.IndexerAccess)){
5010                                 error1579 (expr.Type);
5011                                 return false;
5012                         }
5013
5014                         if (expr.Type.IsArray) {
5015                                 array_type = expr.Type;
5016                                 element_type = array_type.GetElementType ();
5017
5018                                 empty = new EmptyExpression (element_type);
5019                         } else {
5020                                 hm = ProbeCollectionType (ec, expr.Type);
5021                                 if (hm == null){
5022                                         error1579 (expr.Type);
5023                                         return false;
5024                                 }
5025
5026                                 array_type = expr.Type;
5027                                 element_type = hm.element_type;
5028
5029                                 empty = new EmptyExpression (hm.element_type);
5030                         }
5031
5032                         ec.StartFlowBranching (FlowBranchingType.LOOP_BLOCK, loc);
5033                         ec.CurrentBranching.CreateSibling ();
5034
5035                         //
5036                         //
5037                         // FIXME: maybe we can apply the same trick we do in the
5038                         // array handling to avoid creating empty and conv in some cases.
5039                         //
5040                         // Although it is not as important in this case, as the type
5041                         // will not likely be object (what the enumerator will return).
5042                         //
5043                         conv = Expression.ConvertExplicit (ec, empty, var_type, false, loc);
5044                         if (conv == null)
5045                                 return false;
5046
5047                         if (variable.ResolveLValue (ec, empty) == null)
5048                                 return false;
5049                         
5050                         if (!statement.Resolve (ec))
5051                                 return false;
5052
5053                         //FlowReturns returns = ec.EndFlowBranching ();
5054
5055                         return true;
5056                 }
5057                 
5058                 //
5059                 // Retrieves a `public bool MoveNext ()' method from the Type `t'
5060                 //
5061                 static MethodInfo FetchMethodMoveNext (Type t)
5062                 {
5063                         MemberList move_next_list;
5064                         
5065                         move_next_list = TypeContainer.FindMembers (
5066                                 t, MemberTypes.Method,
5067                                 BindingFlags.Public | BindingFlags.Instance,
5068                                 Type.FilterName, "MoveNext");
5069                         if (move_next_list.Count == 0)
5070                                 return null;
5071
5072                         foreach (MemberInfo m in move_next_list){
5073                                 MethodInfo mi = (MethodInfo) m;
5074                                 Type [] args;
5075                                 
5076                                 args = TypeManager.GetArgumentTypes (mi);
5077                                 if (args != null && args.Length == 0){
5078                                         if (mi.ReturnType == TypeManager.bool_type)
5079                                                 return mi;
5080                                 }
5081                         }
5082                         return null;
5083                 }
5084                 
5085                 //
5086                 // Retrieves a `public T get_Current ()' method from the Type `t'
5087                 //
5088                 static MethodInfo FetchMethodGetCurrent (Type t)
5089                 {
5090                         MemberList move_next_list;
5091                         
5092                         move_next_list = TypeContainer.FindMembers (
5093                                 t, MemberTypes.Method,
5094                                 BindingFlags.Public | BindingFlags.Instance,
5095                                 Type.FilterName, "get_Current");
5096                         if (move_next_list.Count == 0)
5097                                 return null;
5098
5099                         foreach (MemberInfo m in move_next_list){
5100                                 MethodInfo mi = (MethodInfo) m;
5101                                 Type [] args;
5102
5103                                 args = TypeManager.GetArgumentTypes (mi);
5104                                 if (args != null && args.Length == 0)
5105                                         return mi;
5106                         }
5107                         return null;
5108                 }
5109
5110                 // 
5111                 // This struct records the helper methods used by the Foreach construct
5112                 //
5113                 class ForeachHelperMethods {
5114                         public EmitContext ec;
5115                         public MethodInfo get_enumerator;
5116                         public MethodInfo move_next;
5117                         public MethodInfo get_current;
5118                         public Type element_type;
5119                         public Type enumerator_type;
5120                         public bool is_disposable;
5121
5122                         public ForeachHelperMethods (EmitContext ec)
5123                         {
5124                                 this.ec = ec;
5125                                 this.element_type = TypeManager.object_type;
5126                                 this.enumerator_type = TypeManager.ienumerator_type;
5127                                 this.is_disposable = true;
5128                         }
5129                 }
5130                 
5131                 static bool GetEnumeratorFilter (MemberInfo m, object criteria)
5132                 {
5133                         if (m == null)
5134                                 return false;
5135                         
5136                         if (!(m is MethodInfo))
5137                                 return false;
5138                         
5139                         if (m.Name != "GetEnumerator")
5140                                 return false;
5141
5142                         MethodInfo mi = (MethodInfo) m;
5143                         Type [] args = TypeManager.GetArgumentTypes (mi);
5144                         if (args != null){
5145                                 if (args.Length != 0)
5146                                         return false;
5147                         }
5148                         ForeachHelperMethods hm = (ForeachHelperMethods) criteria;
5149                         EmitContext ec = hm.ec;
5150
5151                         //
5152                         // Check whether GetEnumerator is accessible to us
5153                         //
5154                         MethodAttributes prot = mi.Attributes & MethodAttributes.MemberAccessMask;
5155
5156                         Type declaring = mi.DeclaringType;
5157                         if (prot == MethodAttributes.Private){
5158                                 if (declaring != ec.ContainerType)
5159                                         return false;
5160                         } else if (prot == MethodAttributes.FamANDAssem){
5161                                 // If from a different assembly, false
5162                                 if (!(mi is MethodBuilder))
5163                                         return false;
5164                                 //
5165                                 // Are we being invoked from the same class, or from a derived method?
5166                                 //
5167                                 if (ec.ContainerType != declaring){
5168                                         if (!ec.ContainerType.IsSubclassOf (declaring))
5169                                                 return false;
5170                                 }
5171                         } else if (prot == MethodAttributes.FamORAssem){
5172                                 if (!(mi is MethodBuilder ||
5173                                       ec.ContainerType == declaring ||
5174                                       ec.ContainerType.IsSubclassOf (declaring)))
5175                                         return false;
5176                         } if (prot == MethodAttributes.Family){
5177                                 if (!(ec.ContainerType == declaring ||
5178                                       ec.ContainerType.IsSubclassOf (declaring)))
5179                                         return false;
5180                         }
5181
5182                         //
5183                         // Ok, we can access it, now make sure that we can do something
5184                         // with this `GetEnumerator'
5185                         //
5186
5187                         if (mi.ReturnType == TypeManager.ienumerator_type ||
5188                             TypeManager.ienumerator_type.IsAssignableFrom (mi.ReturnType) ||
5189                             (!RootContext.StdLib && TypeManager.ImplementsInterface (mi.ReturnType, TypeManager.ienumerator_type))) {
5190                                 hm.move_next = TypeManager.bool_movenext_void;
5191                                 hm.get_current = TypeManager.object_getcurrent_void;
5192                                 return true;
5193                         }
5194
5195                         //
5196                         // Ok, so they dont return an IEnumerable, we will have to
5197                         // find if they support the GetEnumerator pattern.
5198                         //
5199                         Type return_type = mi.ReturnType;
5200
5201                         hm.move_next = FetchMethodMoveNext (return_type);
5202                         if (hm.move_next == null)
5203                                 return false;
5204                         hm.get_current = FetchMethodGetCurrent (return_type);
5205                         if (hm.get_current == null)
5206                                 return false;
5207
5208                         hm.element_type = hm.get_current.ReturnType;
5209                         hm.enumerator_type = return_type;
5210                         hm.is_disposable = TypeManager.ImplementsInterface (
5211                                 hm.enumerator_type, TypeManager.idisposable_type);
5212
5213                         return true;
5214                 }
5215                 
5216                 /// <summary>
5217                 ///   This filter is used to find the GetEnumerator method
5218                 ///   on which IEnumerator operates
5219                 /// </summary>
5220                 static MemberFilter FilterEnumerator;
5221                 
5222                 static Foreach ()
5223                 {
5224                         FilterEnumerator = new MemberFilter (GetEnumeratorFilter);
5225                 }
5226
5227                 void error1579 (Type t)
5228                 {
5229                         Report.Error (1579, loc,
5230                                       "foreach statement cannot operate on variables of type `" +
5231                                       t.FullName + "' because that class does not provide a " +
5232                                       " GetEnumerator method or it is inaccessible");
5233                 }
5234
5235                 static bool TryType (Type t, ForeachHelperMethods hm)
5236                 {
5237                         MemberList mi;
5238                         
5239                         mi = TypeContainer.FindMembers (t, MemberTypes.Method,
5240                                                         BindingFlags.Public | BindingFlags.NonPublic |
5241                                                         BindingFlags.Instance,
5242                                                         FilterEnumerator, hm);
5243
5244                         if (mi.Count == 0)
5245                                 return false;
5246
5247                         hm.get_enumerator = (MethodInfo) mi [0];
5248                         return true;    
5249                 }
5250                 
5251                 //
5252                 // Looks for a usable GetEnumerator in the Type, and if found returns
5253                 // the three methods that participate: GetEnumerator, MoveNext and get_Current
5254                 //
5255                 ForeachHelperMethods ProbeCollectionType (EmitContext ec, Type t)
5256                 {
5257                         ForeachHelperMethods hm = new ForeachHelperMethods (ec);
5258
5259                         if (TryType (t, hm))
5260                                 return hm;
5261
5262                         //
5263                         // Now try to find the method in the interfaces
5264                         //
5265                         while (t != null){
5266                                 Type [] ifaces = t.GetInterfaces ();
5267
5268                                 foreach (Type i in ifaces){
5269                                         if (TryType (i, hm))
5270                                                 return hm;
5271                                 }
5272                                 
5273                                 //
5274                                 // Since TypeBuilder.GetInterfaces only returns the interface
5275                                 // types for this type, we have to keep looping, but once
5276                                 // we hit a non-TypeBuilder (ie, a Type), then we know we are
5277                                 // done, because it returns all the types
5278                                 //
5279                                 if ((t is TypeBuilder))
5280                                         t = t.BaseType;
5281                                 else
5282                                         break;
5283                         } 
5284
5285                         return null;
5286                 }
5287
5288                 //
5289                 // FIXME: possible optimization.
5290                 // We might be able to avoid creating `empty' if the type is the sam
5291                 //
5292                 bool EmitCollectionForeach (EmitContext ec)
5293                 {
5294                         ILGenerator ig = ec.ig;
5295                         LocalBuilder enumerator, disposable;
5296
5297                         enumerator = ig.DeclareLocal (hm.enumerator_type);
5298                         if (hm.is_disposable)
5299                                 disposable = ig.DeclareLocal (TypeManager.idisposable_type);
5300                         else
5301                                 disposable = null;
5302                         
5303                         //
5304                         // Instantiate the enumerator
5305                         //
5306                         if (expr.Type.IsValueType){
5307                                 if (expr is IMemoryLocation){
5308                                         IMemoryLocation ml = (IMemoryLocation) expr;
5309
5310                                         ml.AddressOf (ec, AddressOp.Load);
5311                                 } else
5312                                         throw new Exception ("Expr " + expr + " of type " + expr.Type +
5313                                                              " does not implement IMemoryLocation");
5314                                 ig.Emit (OpCodes.Call, hm.get_enumerator);
5315                         } else {
5316                                 expr.Emit (ec);
5317                                 ig.Emit (OpCodes.Callvirt, hm.get_enumerator);
5318                         }
5319                         ig.Emit (OpCodes.Stloc, enumerator);
5320
5321                         //
5322                         // Protect the code in a try/finalize block, so that
5323                         // if the beast implement IDisposable, we get rid of it
5324                         //
5325                         bool old_in_try = ec.InTry;
5326
5327                         if (hm.is_disposable)
5328                                 ec.InTry = true;
5329                         
5330                         Label end_try = ig.DefineLabel ();
5331                         
5332                         ig.MarkLabel (ec.LoopBegin);
5333                         ig.Emit (OpCodes.Ldloc, enumerator);
5334                         ig.Emit (OpCodes.Callvirt, hm.move_next);
5335                         ig.Emit (OpCodes.Brfalse, end_try);
5336                         ig.Emit (OpCodes.Ldloc, enumerator);
5337                         ig.Emit (OpCodes.Callvirt, hm.get_current);
5338                         variable.EmitAssign (ec, conv);
5339                         statement.Emit (ec);
5340                         ig.Emit (OpCodes.Br, ec.LoopBegin);
5341                         ig.MarkLabel (end_try);
5342                         ec.InTry = old_in_try;
5343                         
5344                         // The runtime provides this for us.
5345                         // ig.Emit (OpCodes.Leave, end);
5346
5347                         //
5348                         // Now the finally block
5349                         //
5350                         if (hm.is_disposable) {
5351                                 Label end_finally = ig.DefineLabel ();
5352                                 bool old_in_finally = ec.InFinally;
5353                                 ec.InFinally = true;
5354                                 ig.BeginFinallyBlock ();
5355                         
5356                                 ig.Emit (OpCodes.Ldloc, enumerator);
5357                                 ig.Emit (OpCodes.Isinst, TypeManager.idisposable_type);
5358                                 ig.Emit (OpCodes.Stloc, disposable);
5359                                 ig.Emit (OpCodes.Ldloc, disposable);
5360                                 ig.Emit (OpCodes.Brfalse, end_finally);
5361                                 ig.Emit (OpCodes.Ldloc, disposable);
5362                                 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
5363                                 ig.MarkLabel (end_finally);
5364                                 ec.InFinally = old_in_finally;
5365
5366                                 // The runtime generates this anyways.
5367                                 // ig.Emit (OpCodes.Endfinally);
5368
5369                                 ig.EndExceptionBlock ();
5370                         }
5371
5372                         ig.MarkLabel (ec.LoopEnd);
5373                         return false;
5374                 }
5375
5376                 //
5377                 // FIXME: possible optimization.
5378                 // We might be able to avoid creating `empty' if the type is the sam
5379                 //
5380                 bool EmitArrayForeach (EmitContext ec)
5381                 {
5382                         int rank = array_type.GetArrayRank ();
5383                         ILGenerator ig = ec.ig;
5384
5385                         LocalBuilder copy = ig.DeclareLocal (array_type);
5386                         
5387                         //
5388                         // Make our copy of the array
5389                         //
5390                         expr.Emit (ec);
5391                         ig.Emit (OpCodes.Stloc, copy);
5392                         
5393                         if (rank == 1){
5394                                 LocalBuilder counter = ig.DeclareLocal (TypeManager.int32_type);
5395
5396                                 Label loop, test;
5397                                 
5398                                 ig.Emit (OpCodes.Ldc_I4_0);
5399                                 ig.Emit (OpCodes.Stloc, counter);
5400                                 test = ig.DefineLabel ();
5401                                 ig.Emit (OpCodes.Br, test);
5402
5403                                 loop = ig.DefineLabel ();
5404                                 ig.MarkLabel (loop);
5405
5406                                 ig.Emit (OpCodes.Ldloc, copy);
5407                                 ig.Emit (OpCodes.Ldloc, counter);
5408                                 ArrayAccess.EmitLoadOpcode (ig, var_type);
5409
5410                                 variable.EmitAssign (ec, conv);
5411
5412                                 statement.Emit (ec);
5413
5414                                 ig.MarkLabel (ec.LoopBegin);
5415                                 ig.Emit (OpCodes.Ldloc, counter);
5416                                 ig.Emit (OpCodes.Ldc_I4_1);
5417                                 ig.Emit (OpCodes.Add);
5418                                 ig.Emit (OpCodes.Stloc, counter);
5419
5420                                 ig.MarkLabel (test);
5421                                 ig.Emit (OpCodes.Ldloc, counter);
5422                                 ig.Emit (OpCodes.Ldloc, copy);
5423                                 ig.Emit (OpCodes.Ldlen);
5424                                 ig.Emit (OpCodes.Conv_I4);
5425                                 ig.Emit (OpCodes.Blt, loop);
5426                         } else {
5427                                 LocalBuilder [] dim_len   = new LocalBuilder [rank];
5428                                 LocalBuilder [] dim_count = new LocalBuilder [rank];
5429                                 Label [] loop = new Label [rank];
5430                                 Label [] test = new Label [rank];
5431                                 int dim;
5432                                 
5433                                 for (dim = 0; dim < rank; dim++){
5434                                         dim_len [dim] = ig.DeclareLocal (TypeManager.int32_type);
5435                                         dim_count [dim] = ig.DeclareLocal (TypeManager.int32_type);
5436                                         test [dim] = ig.DefineLabel ();
5437                                         loop [dim] = ig.DefineLabel ();
5438                                 }
5439                                         
5440                                 for (dim = 0; dim < rank; dim++){
5441                                         ig.Emit (OpCodes.Ldloc, copy);
5442                                         IntLiteral.EmitInt (ig, dim);
5443                                         ig.Emit (OpCodes.Callvirt, TypeManager.int_getlength_int);
5444                                         ig.Emit (OpCodes.Stloc, dim_len [dim]);
5445                                 }
5446
5447                                 for (dim = 0; dim < rank; dim++){
5448                                         ig.Emit (OpCodes.Ldc_I4_0);
5449                                         ig.Emit (OpCodes.Stloc, dim_count [dim]);
5450                                         ig.Emit (OpCodes.Br, test [dim]);
5451                                         ig.MarkLabel (loop [dim]);
5452                                 }
5453
5454                                 ig.Emit (OpCodes.Ldloc, copy);
5455                                 for (dim = 0; dim < rank; dim++)
5456                                         ig.Emit (OpCodes.Ldloc, dim_count [dim]);
5457
5458                                 //
5459                                 // FIXME: Maybe we can cache the computation of `get'?
5460                                 //
5461                                 Type [] args = new Type [rank];
5462                                 MethodInfo get;
5463
5464                                 for (int i = 0; i < rank; i++)
5465                                         args [i] = TypeManager.int32_type;
5466
5467                                 ModuleBuilder mb = CodeGen.ModuleBuilder;
5468                                 get = mb.GetArrayMethod (
5469                                         array_type, "Get",
5470                                         CallingConventions.HasThis| CallingConventions.Standard,
5471                                         var_type, args);
5472                                 ig.Emit (OpCodes.Call, get);
5473                                 variable.EmitAssign (ec, conv);
5474                                 statement.Emit (ec);
5475                                 ig.MarkLabel (ec.LoopBegin);
5476                                 for (dim = rank - 1; dim >= 0; dim--){
5477                                         ig.Emit (OpCodes.Ldloc, dim_count [dim]);
5478                                         ig.Emit (OpCodes.Ldc_I4_1);
5479                                         ig.Emit (OpCodes.Add);
5480                                         ig.Emit (OpCodes.Stloc, dim_count [dim]);
5481
5482                                         ig.MarkLabel (test [dim]);
5483                                         ig.Emit (OpCodes.Ldloc, dim_count [dim]);
5484                                         ig.Emit (OpCodes.Ldloc, dim_len [dim]);
5485                                         ig.Emit (OpCodes.Blt, loop [dim]);
5486                                 }
5487                         }
5488                         ig.MarkLabel (ec.LoopEnd);
5489                         
5490                         return false;
5491                 }
5492                 
5493                 protected override bool DoEmit (EmitContext ec)
5494                 {
5495                         bool ret_val;
5496                         
5497                         ILGenerator ig = ec.ig;
5498                         
5499                         Label old_begin = ec.LoopBegin, old_end = ec.LoopEnd;
5500                         bool old_inloop = ec.InLoop;
5501                         int old_loop_begin_try_catch_level = ec.LoopBeginTryCatchLevel;
5502                         ec.LoopBegin = ig.DefineLabel ();
5503                         ec.LoopEnd = ig.DefineLabel ();
5504                         ec.InLoop = true;
5505                         ec.LoopBeginTryCatchLevel = ec.TryCatchLevel;
5506                         
5507                         if (hm != null)
5508                                 ret_val = EmitCollectionForeach (ec);
5509                         else
5510                                 ret_val = EmitArrayForeach (ec);
5511                         
5512                         ec.LoopBegin = old_begin;
5513                         ec.LoopEnd = old_end;
5514                         ec.InLoop = old_inloop;
5515                         ec.LoopBeginTryCatchLevel = old_loop_begin_try_catch_level;
5516
5517                         return ret_val;
5518                 }
5519         }
5520         
5521         /// <summary>
5522         ///   AddHandler statement
5523         /// </summary>
5524         public class AddHandler : Statement {
5525                 Expression EvtId;
5526                 Expression EvtHandler;
5527
5528                 //
5529                 // keeps track whether EvtId is already resolved
5530                 //
5531                 bool resolved;
5532
5533                 public AddHandler (Expression evt_id, Expression evt_handler, Location l)
5534                 {
5535                         EvtId = evt_id;
5536                         EvtHandler = evt_handler;
5537                         loc = l;
5538                         resolved = false;
5539                         //Console.WriteLine ("Adding handler '" + evt_handler + "' for Event '" + evt_id +"'");
5540                 }
5541
5542                 public override bool Resolve (EmitContext ec)
5543                 {
5544                         //
5545                         // if EvetId is of EventExpr type that means
5546                         // this is already resolved 
5547                         //
5548                         if (EvtId is EventExpr) {
5549                                 resolved = true;
5550                                 return true;
5551                         }
5552
5553                         EvtId = EvtId.Resolve(ec);
5554                         EvtHandler = EvtHandler.Resolve(ec,ResolveFlags.MethodGroup);
5555                         if (EvtId == null || (!(EvtId is EventExpr))) {
5556                                 Report.Error (30676, "Need an event designator.");
5557                                 return false;
5558                         }
5559
5560                         if (EvtHandler == null) 
5561                         {
5562                                 Report.Error (999, "'AddHandler' statement needs an event handler.");
5563                                 return false;
5564                         }
5565
5566                         return true;
5567                 }
5568
5569                 protected override bool DoEmit (EmitContext ec)
5570                 {
5571                         //
5572                         // Already resolved and emitted don't do anything
5573                         //
5574                         if (resolved)
5575                                 return true;
5576
5577                         Expression e, d;
5578                         ArrayList args = new ArrayList();
5579                         Argument arg = new Argument (EvtHandler, Argument.AType.Expression);
5580                         args.Add (arg);
5581                         
5582                         
5583
5584                         // The even type was already resolved to a delegate, so
5585                         // we must un-resolve its name to generate a type expression
5586                         string ts = (EvtId.Type.ToString()).Replace ('+','.');
5587                         Expression dtype = Mono.MonoBASIC.Parser.DecomposeQI (ts, Location.Null);
5588
5589                         // which we can use to declare a new event handler
5590                         // of the same type
5591                         d = new New (dtype, args, Location.Null);
5592                         d = d.Resolve(ec);
5593                         e = new CompoundAssign(Binary.Operator.Addition, EvtId, d, Location.Null);
5594
5595                         // we resolve it all and emit the code
5596                         e = e.Resolve(ec);
5597                         if (e != null) 
5598                         {
5599                                 e.Emit(ec);
5600                                 return true;
5601                         }
5602
5603                         return false;
5604                 }
5605         }
5606
5607         /// <summary>
5608         ///   RemoveHandler statement
5609         /// </summary>
5610         public class RemoveHandler : Statement \r
5611         {
5612                 Expression EvtId;
5613                 Expression EvtHandler;
5614
5615                 public RemoveHandler (Expression evt_id, Expression evt_handler, Location l)
5616                 {
5617                         EvtId = evt_id;
5618                         EvtHandler = evt_handler;
5619                         loc = l;
5620                 }
5621
5622                 public override bool Resolve (EmitContext ec)
5623                 {
5624                         EvtId = EvtId.Resolve(ec);
5625                         EvtHandler = EvtHandler.Resolve(ec,ResolveFlags.MethodGroup);
5626                         if (EvtId == null || (!(EvtId is EventExpr))) \r
5627                         {
5628                                 Report.Error (30676, "Need an event designator.");
5629                                 return false;
5630                         }
5631
5632                         if (EvtHandler == null) 
5633                         {
5634                                 Report.Error (999, "'AddHandler' statement needs an event handler.");
5635                                 return false;
5636                         }
5637                         return true;
5638                 }
5639
5640                 protected override bool DoEmit (EmitContext ec)
5641                 {
5642                         Expression e, d;
5643                         ArrayList args = new ArrayList();
5644                         Argument arg = new Argument (EvtHandler, Argument.AType.Expression);
5645                         args.Add (arg);
5646                         
5647                         // The even type was already resolved to a delegate, so
5648                         // we must un-resolve its name to generate a type expression
5649                         string ts = (EvtId.Type.ToString()).Replace ('+','.');
5650                         Expression dtype = Mono.MonoBASIC.Parser.DecomposeQI (ts, Location.Null);
5651
5652                         // which we can use to declare a new event handler
5653                         // of the same type
5654                         d = new New (dtype, args, Location.Null);
5655                         d = d.Resolve(ec);
5656                         // detach the event
5657                         e = new CompoundAssign(Binary.Operator.Subtraction, EvtId, d, Location.Null);
5658
5659                         // we resolve it all and emit the code
5660                         e = e.Resolve(ec);
5661                         if (e != null) 
5662                         {
5663                                 e.Emit(ec);
5664                                 return true;
5665                         }
5666
5667                         return false;
5668                 }
5669         }
5670
5671         public class RedimClause {
5672                 public Expression Expr;
5673                 public ArrayList NewIndexes;
5674                 
5675                 public RedimClause (Expression e, ArrayList args)
5676                 {
5677                         Expr = e;
5678                         NewIndexes = args;
5679                 }
5680         }
5681
5682         public class ReDim : Statement {
5683                 ArrayList RedimTargets;
5684                 Type BaseType;
5685                 bool Preserve;
5686
5687                 private StatementExpression ReDimExpr;
5688
5689                 public ReDim (ArrayList targets, bool opt_preserve, Location l)
5690                 {
5691                         loc = l;
5692                         RedimTargets = targets;
5693                         Preserve = opt_preserve;
5694                 }
5695
5696                 public override bool Resolve (EmitContext ec)
5697                 {
5698                         Expression RedimTarget;
5699                         ArrayList NewIndexes;
5700
5701                         foreach (RedimClause rc in RedimTargets) {
5702                                 RedimTarget = rc.Expr;
5703                                 NewIndexes = rc.NewIndexes;
5704
5705                                 RedimTarget = RedimTarget.Resolve (ec);
5706                                 if (!RedimTarget.Type.IsArray)
5707                                         Report.Error (49, "'ReDim' statement requires an array");
5708
5709                                 ArrayList args = new ArrayList();
5710                                 foreach (Argument a in NewIndexes) {
5711                                         if (a.Resolve(ec, loc))
5712                                                 args.Add (a.Expr);
5713                                 }
5714
5715                                 for (int x = 0; x < args.Count; x++) {
5716                                         args[x] = new Binary (Binary.Operator.Addition,
5717                                                                 (Expression) args[x], new IntLiteral (1), Location.Null);       
5718                                 }
5719
5720                                 NewIndexes = args;
5721                                 if (RedimTarget.Type.GetArrayRank() != args.Count)
5722                                         Report.Error (30415, "'ReDim' cannot change the number of dimensions of an array.");
5723
5724                                 BaseType = RedimTarget.Type.GetElementType();
5725                                 Expression BaseTypeExpr = MonoBASIC.Parser.DecomposeQI(BaseType.FullName.ToString(), Location.Null);
5726                                 ArrayCreation acExpr = new ArrayCreation (BaseTypeExpr, NewIndexes, "", null, Location.Null);   
5727                                 // TODO: we are in a foreach we probably can't reuse ReDimExpr, must turn it into an array(list)
5728                                 if (Preserve)
5729                                 {
5730                                         ExpressionStatement PreserveExpr = (ExpressionStatement) new Preserve(RedimTarget, acExpr, loc);
5731                                         ReDimExpr = (StatementExpression) new StatementExpression ((ExpressionStatement) new Assign (RedimTarget, PreserveExpr, loc), loc);
5732                                 }
5733                                 else
5734                                         ReDimExpr = (StatementExpression) new StatementExpression ((ExpressionStatement) new Assign (RedimTarget, acExpr, loc), loc);
5735                                 ReDimExpr.Resolve(ec);
5736                         }
5737                         return true;
5738                 }
5739                                 
5740                 protected override bool DoEmit (EmitContext ec)
5741                 {
5742                         ReDimExpr.Emit(ec);
5743                         return false;
5744                 }               
5745                 
5746         }
5747         
5748         public class Erase : Statement {
5749                 Expression EraseTarget;
5750                 
5751                 private StatementExpression EraseExpr;
5752                 
5753                 public Erase (Expression expr, Location l)
5754                 {
5755                         loc = l;
5756                         EraseTarget = expr;
5757                 }
5758                 
5759                 public override bool Resolve (EmitContext ec)
5760                 {
5761                         EraseTarget = EraseTarget.Resolve (ec);
5762                         if (!EraseTarget.Type.IsArray) 
5763                                 Report.Error (49, "'Erase' statement requires an array");
5764
5765                         EraseExpr = (StatementExpression) new StatementExpression ((ExpressionStatement) new Assign (EraseTarget, NullLiteral.Null, loc), loc);
5766                         EraseExpr.Resolve(ec);
5767                         
5768                         return true;
5769                 }
5770                                 
5771                 protected override bool DoEmit (EmitContext ec)
5772                 {
5773                         EraseExpr.Emit(ec);
5774                         return false;
5775                 }               
5776                 
5777         }
5778         
5779         
5780 }