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