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