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