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