2 // statement.cs: Statement representation for the IL tree.
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)
11 // (C) 2001, 2002 Ximian, Inc.
16 using System.Reflection;
17 using System.Reflection.Emit;
18 using System.Diagnostics;
20 namespace Mono.MonoBASIC {
22 using System.Collections;
24 public abstract class Statement {
28 /// Resolves the statement, true means that all sub-statements
31 public virtual bool Resolve (EmitContext ec)
37 /// Return value indicates whether all code paths emitted return.
39 protected abstract bool DoEmit (EmitContext ec);
42 /// Return value indicates whether all code paths emitted return.
44 public virtual bool Emit (EmitContext ec)
47 Report.Debug (8, "MARK", this, loc);
51 public static Expression ResolveBoolean (EmitContext ec, Expression e, Location loc)
57 if (e.Type != TypeManager.bool_type){
58 e = Expression.ConvertImplicit (ec, e, TypeManager.bool_type, Location.Null);
63 30311, loc, "Can not convert the expression to a boolean");
72 /// Encapsulates the emission of a boolean test and jumping to a
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.
79 public static void EmitBoolExpression (EmitContext ec, Expression bool_expr,
80 Label target, bool target_is_for_true)
82 ILGenerator ig = ec.ig;
85 if (bool_expr is Unary){
86 Unary u = (Unary) bool_expr;
88 if (u.Oper == Unary.Operator.LogicalNot){
91 u.EmitLogicalNot (ec);
93 } else if (bool_expr is Binary){
94 Binary b = (Binary) bool_expr;
96 if (b.EmitBranchable (ec, target, target_is_for_true))
103 if (target_is_for_true){
105 ig.Emit (OpCodes.Brfalse, target);
107 ig.Emit (OpCodes.Brtrue, target);
110 ig.Emit (OpCodes.Brtrue, target);
112 ig.Emit (OpCodes.Brfalse, target);
116 public static void Warning_DeadCodeFound (Location loc)
118 Report.Warning (162, loc, "Unreachable code detected");
122 public class EmptyStatement : Statement {
123 public override bool Resolve (EmitContext ec)
128 protected override bool DoEmit (EmitContext ec)
134 public class If : Statement {
136 public Statement TrueStatement;
137 public Statement FalseStatement;
139 public If (Expression expr, Statement trueStatement, Location l)
142 TrueStatement = trueStatement;
146 public If (Expression expr,
147 Statement trueStatement,
148 Statement falseStatement,
152 TrueStatement = trueStatement;
153 FalseStatement = falseStatement;
157 public override bool Resolve (EmitContext ec)
159 Report.Debug (1, "START IF BLOCK", loc);
161 expr = ResolveBoolean (ec, expr, loc);
166 ec.StartFlowBranching (FlowBranchingType.BLOCK, loc);
168 if (!TrueStatement.Resolve (ec)) {
169 ec.KillFlowBranching ();
173 ec.CurrentBranching.CreateSibling ();
175 if ((FalseStatement != null) && !FalseStatement.Resolve (ec)) {
176 ec.KillFlowBranching ();
180 ec.EndFlowBranching ();
182 Report.Debug (1, "END IF BLOCK", loc);
187 protected override bool DoEmit (EmitContext ec)
189 ILGenerator ig = ec.ig;
190 Label false_target = ig.DefineLabel ();
192 bool is_true_ret, is_false_ret;
195 // Dead code elimination
197 if (expr is BoolConstant){
198 bool take = ((BoolConstant) expr).Value;
201 if (FalseStatement != null){
202 Warning_DeadCodeFound (FalseStatement.loc);
204 return TrueStatement.Emit (ec);
206 Warning_DeadCodeFound (TrueStatement.loc);
207 if (FalseStatement != null)
208 return FalseStatement.Emit (ec);
212 EmitBoolExpression (ec, expr, false_target, false);
214 is_true_ret = TrueStatement.Emit (ec);
215 is_false_ret = is_true_ret;
217 if (FalseStatement != null){
218 bool branch_emitted = false;
220 end = ig.DefineLabel ();
222 ig.Emit (OpCodes.Br, end);
223 branch_emitted = true;
226 ig.MarkLabel (false_target);
227 is_false_ret = FalseStatement.Emit (ec);
232 ig.MarkLabel (false_target);
233 is_false_ret = false;
236 return is_true_ret && is_false_ret;
240 public enum DoOptions {
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;
255 public Do (Statement statement, Expression boolExpr, DoOptions do_test, Location l)
258 EmbeddedStatement = statement;
264 public override bool Resolve (EmitContext ec)
268 ec.StartFlowBranching (FlowBranchingType.LOOP_BLOCK, loc);
270 if (!EmbeddedStatement.Resolve (ec))
273 expr = ResolveBoolean (ec, expr, loc);
276 else if (expr is BoolConstant){
277 bool res = ((BoolConstant) expr).Value;
283 ec.CurrentBranching.Infinite = infinite;
284 FlowReturns returns = ec.EndFlowBranching ();
285 may_return = returns != FlowReturns.NEVER;
290 protected override bool DoEmit (EmitContext ec)
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;
299 ec.LoopBegin = ig.DefineLabel ();
300 ec.LoopEnd = ig.DefineLabel ();
302 ec.LoopBeginTryCatchLevel = ec.TryCatchLevel;
304 if (test == DoOptions.TEST_AFTER) {
306 EmbeddedStatement.Emit (ec);
307 ig.MarkLabel (ec.LoopBegin);
310 // Dead code elimination
312 if (expr is BoolConstant){
313 bool res = ((BoolConstant) expr).Value;
316 ec.ig.Emit (OpCodes.Br, loop);
318 EmitBoolExpression (ec, expr, loop, true);
320 ig.MarkLabel (ec.LoopEnd);
325 ig.MarkLabel (ec.LoopBegin);
328 // Dead code elimination
330 if (expr is BoolConstant){
331 bool res = ((BoolConstant) expr).Value;
334 ec.ig.Emit (OpCodes.Br, ec.LoopEnd);
336 EmitBoolExpression (ec, expr, ec.LoopEnd, true);
338 EmbeddedStatement.Emit (ec);
339 ec.ig.Emit (OpCodes.Br, loop);
340 ig.MarkLabel (ec.LoopEnd);
342 ec.LoopBeginTryCatchLevel = old_loop_begin_try_catch_level;
343 ec.LoopBegin = old_begin;
344 ec.LoopEnd = old_end;
345 ec.InLoop = old_inloop;
348 return may_return == false;
354 public class While : Statement {
355 public Expression expr;
356 public readonly Statement Statement;
357 bool may_return, empty, infinite;
359 public While (Expression boolExpr, Statement statement, Location l)
361 this.expr = boolExpr;
362 Statement = statement;
366 public override bool Resolve (EmitContext ec)
370 expr = ResolveBoolean (ec, expr, loc);
374 ec.StartFlowBranching (FlowBranchingType.LOOP_BLOCK, loc);
377 // Inform whether we are infinite or not
379 if (expr is BoolConstant){
380 BoolConstant bc = (BoolConstant) expr;
382 if (bc.Value == false){
383 Warning_DeadCodeFound (Statement.loc);
389 // We are not infinite, so the loop may or may not be executed.
391 ec.CurrentBranching.CreateSibling ();
394 if (!Statement.Resolve (ec))
398 ec.KillFlowBranching ();
400 ec.CurrentBranching.Infinite = infinite;
401 FlowReturns returns = ec.EndFlowBranching ();
402 may_return = returns != FlowReturns.NEVER;
408 protected override bool DoEmit (EmitContext ec)
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;
420 ec.LoopBegin = ig.DefineLabel ();
421 ec.LoopEnd = ig.DefineLabel ();
423 ec.LoopBeginTryCatchLevel = ec.TryCatchLevel;
426 // Inform whether we are infinite or not
428 if (expr is BoolConstant){
429 ig.MarkLabel (ec.LoopBegin);
431 ig.Emit (OpCodes.Br, ec.LoopBegin);
434 // Inform that we are infinite (ie, `we return'), only
435 // if we do not `break' inside the code.
437 ret = may_return == false;
438 ig.MarkLabel (ec.LoopEnd);
440 Label while_loop = ig.DefineLabel ();
442 ig.Emit (OpCodes.Br, ec.LoopBegin);
443 ig.MarkLabel (while_loop);
447 ig.MarkLabel (ec.LoopBegin);
449 EmitBoolExpression (ec, expr, while_loop, true);
450 ig.MarkLabel (ec.LoopEnd);
455 ec.LoopBegin = old_begin;
456 ec.LoopEnd = old_end;
457 ec.InLoop = old_inloop;
458 ec.LoopBeginTryCatchLevel = old_loop_begin_try_catch_level;
464 public class For : Statement {
465 Expression LoopControlVar;
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;
477 public For (Expression loopVar,
484 LoopControlVar = loopVar;
488 this.statement = statement;
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);
497 is_lcv_object = false;
500 public override bool Resolve (EmitContext ec)
504 LoopControlVar = LoopControlVar.Resolve (ec);
505 if (LoopControlVar == null)
508 Start = Start.Resolve (ec);
509 Limit = Limit.Resolve (ec);
510 StepValue = StepValue.Resolve (ec);
511 if (StepValue == null || Start == null || Limit == null)
515 if (StepValue is Constant) {
517 value = GetValue (StepValue);
518 if (value > 0) // Positive Step value
519 Test = new Binary (Binary.Operator.LessThanOrEqual, LoopControlVar, Limit, loc);
521 Test = new Binary (Binary.Operator.GreaterThanOrEqual, LoopControlVar, Limit, loc);
524 if (Start is Constant && Limit is Constant) {
526 AddnTest = ConstantFold.BinaryFold (ec, Binary.Operator.LessThanOrEqual,
527 (Constant) Start, (Constant) Limit, loc);
529 AddnTest = ConstantFold.BinaryFold (ec, Binary.Operator.GreaterThanOrEqual,
530 (Constant) Start, (Constant) Limit, loc);
534 string method_to_call = null;
538 switch (Type.GetTypeCode (LoopControlVar.Type)) {
539 case TypeCode.Boolean :
541 case TypeCode.DateTime :
542 case TypeCode.String :
543 Report.Error (30337,loc,"'For' loop control variable cannot be of type '" + LoopControlVar.Type + "'");
547 Test = new Binary (Binary.Operator.LessThanOrEqual, LoopControlVar, Limit, loc);
549 case TypeCode.Int16 :
551 left = new Binary (Binary.Operator.ExclusiveOr,
552 new Binary (Binary.Operator.RightShift, StepValue, new IntLiteral (15), loc),
555 right = new Binary (Binary.Operator.ExclusiveOr,
556 new Binary (Binary.Operator.RightShift, StepValue, new IntLiteral (15), loc),
559 Test = new Binary (Binary.Operator.LessThanOrEqual, left, right, loc);
562 case TypeCode.Int32 :
564 left = new Binary (Binary.Operator.ExclusiveOr,
565 new Binary (Binary.Operator.RightShift, StepValue, new IntLiteral (31), loc),
568 right = new Binary (Binary.Operator.ExclusiveOr,
569 new Binary (Binary.Operator.RightShift, StepValue, new IntLiteral (31), loc),
572 Test = new Binary (Binary.Operator.LessThanOrEqual, left, right, loc);
575 case TypeCode.Int64 :
577 left = new Binary (Binary.Operator.ExclusiveOr,
578 new Binary (Binary.Operator.RightShift, StepValue, new IntLiteral (63), loc),
581 right = new Binary (Binary.Operator.ExclusiveOr,
582 new Binary (Binary.Operator.RightShift, StepValue, new IntLiteral (63), loc),
585 Test = new Binary (Binary.Operator.LessThanOrEqual, left, right, loc);
588 case TypeCode.Decimal :
589 method_to_call = "Microsoft.VisualBasic.CompilerServices.FlowControl.ForNextCheckDec";
591 case TypeCode.Single :
592 method_to_call = "Microsoft.VisualBasic.CompilerServices.FlowControl.ForNextCheckR4";
594 case TypeCode.Double :
595 method_to_call = "Microsoft.VisualBasic.CompilerServices.FlowControl.ForNextCheckR8";
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);
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);
631 if (InitStatement != null){
632 if (!InitStatement.Resolve (ec))
636 if (AddnTest != null) {
637 AddnTest = ResolveBoolean (ec, AddnTest, loc);
638 if (AddnTest == null)
643 Test = ResolveBoolean (ec, Test, loc);
646 else if (Test is BoolConstant){
647 BoolConstant bc = (BoolConstant) Test;
649 if (bc.Value == false){
650 Warning_DeadCodeFound (statement.loc);
658 if (Increment != null) {
659 if (!Increment.Resolve (ec))
663 ec.StartFlowBranching (FlowBranchingType.LOOP_BLOCK, loc);
665 ec.CurrentBranching.CreateSibling ();
667 if (!statement.Resolve (ec))
671 ec.KillFlowBranching ();
673 ec.CurrentBranching.Infinite = infinite;
674 FlowReturns returns = ec.EndFlowBranching ();
675 may_return = returns != FlowReturns.NEVER;
681 protected override bool DoEmit (EmitContext ec)
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 ();
694 if (!is_lcv_object && InitStatement != null)
695 if (! (InitStatement is EmptyStatement))
696 InitStatement.Emit (ec);
698 ec.LoopBegin = ig.DefineLabel ();
699 ec.LoopEnd = ig.DefineLabel ();
701 ec.LoopBeginTryCatchLevel = ec.TryCatchLevel;
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);
712 EmitBoolExpression (ec, AddnTest, test, false);
714 ig.Emit (OpCodes.Br, test);
718 ig.MarkLabel (ec.LoopBegin);
719 if (!is_lcv_object && !(Increment is EmptyStatement))
724 // If test is null, there is no test, and we are just
728 EmitBoolExpression (ec, Test, loop, true);
730 ig.Emit (OpCodes.Br, loop);
731 ig.MarkLabel (ec.LoopEnd);
733 ec.LoopBegin = old_begin;
734 ec.LoopEnd = old_end;
735 ec.InLoop = old_inloop;
736 ec.LoopBeginTryCatchLevel = old_loop_begin_try_catch_level;
739 // Inform whether we are infinite or not
745 if (Test is BoolConstant){
746 BoolConstant bc = (BoolConstant) Test;
749 return may_return == false;
753 return may_return == false;
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;
771 public class StatementExpression : Statement {
772 public Expression expr;
774 public StatementExpression (ExpressionStatement expr, Location l)
780 public override bool Resolve (EmitContext ec)
782 expr = (Expression) expr.Resolve (ec);
786 protected override bool DoEmit (EmitContext ec)
788 ILGenerator ig = ec.ig;
790 if (expr is ExpressionStatement)
791 ((ExpressionStatement) expr).EmitStatement (ec);
794 if (! (expr is StatementSequence))
795 ig.Emit (OpCodes.Pop);
801 public override string ToString ()
803 return "StatementExpression (" + expr + ")";
808 /// Implements the return statement
810 public class Return : Statement {
811 public Expression Expr;
813 public Return (Expression expr, Location l)
819 public override bool Resolve (EmitContext ec)
822 Expr = Expr.Resolve (ec);
827 FlowBranching.UsageVector vector = ec.CurrentBranching.CurrentUsageVector;
829 if (ec.CurrentBranching.InTryBlock ())
830 ec.CurrentBranching.AddFinallyVector (vector);
832 vector.Returns = FlowReturns.ALWAYS;
833 vector.Breaks = FlowReturns.ALWAYS;
837 protected override bool DoEmit (EmitContext ec)
840 Report.Error (157,loc,"Control can not leave the body of the finally block");
844 if (ec.ReturnType == null){
846 Report.Error (127, loc, "Return with a value not allowed here");
851 Report.Error (126, loc, "An object of type `" +
852 TypeManager.MonoBASIC_Name (ec.ReturnType) + "' is " +
853 "expected for the return statement");
857 if (Expr.Type != ec.ReturnType)
858 Expr = Expression.ConvertImplicitRequired (
859 ec, Expr, ec.ReturnType, loc);
866 if (ec.InTry || ec.InCatch)
867 ec.ig.Emit (OpCodes.Stloc, ec.TemporaryReturn ());
870 if (ec.InTry || ec.InCatch) {
871 if (!ec.HasReturnLabel) {
872 ec.ReturnLabel = ec.ig.DefineLabel ();
873 ec.HasReturnLabel = true;
875 ec.ig.Emit (OpCodes.Leave, ec.ReturnLabel);
877 ec.ig.Emit (OpCodes.Ret);
883 public class Goto : Statement {
886 LabeledStatement label;
888 public override bool Resolve (EmitContext ec)
890 label = block.LookupLabel (target);
894 "No such label `" + target + "' in this scope");
898 // If this is a forward goto.
899 if (!label.IsDefined)
900 label.AddUsageVector (ec.CurrentBranching.CurrentUsageVector);
902 ec.CurrentBranching.CurrentUsageVector.Breaks = FlowReturns.ALWAYS;
907 public Goto (Block parent_block, string label, Location l)
909 block = parent_block;
914 public string Target {
920 protected override bool DoEmit (EmitContext ec)
922 Label l = label.LabelTarget (ec);
923 ec.ig.Emit (OpCodes.Br, l);
929 public class LabeledStatement : Statement {
930 public readonly Location Location;
938 public LabeledStatement (string label_name, Location l)
940 this.label_name = label_name;
944 public Label LabelTarget (EmitContext ec)
948 label = ec.ig.DefineLabel ();
954 public bool IsDefined {
960 public bool HasBeenReferenced {
966 public void AddUsageVector (FlowBranching.UsageVector vector)
969 vectors = new ArrayList ();
971 vectors.Add (vector.Clone ());
974 public override bool Resolve (EmitContext ec)
977 ec.CurrentBranching.CurrentUsageVector.MergeJumpOrigins (vectors);
979 ec.CurrentBranching.CurrentUsageVector.Breaks = FlowReturns.NEVER;
980 ec.CurrentBranching.CurrentUsageVector.Returns = FlowReturns.NEVER;
988 protected override bool DoEmit (EmitContext ec)
991 ec.ig.MarkLabel (label);
999 /// `goto default' statement
1001 public class GotoDefault : Statement {
1003 public GotoDefault (Location l)
1008 public override bool Resolve (EmitContext ec)
1010 ec.CurrentBranching.CurrentUsageVector.Breaks = FlowReturns.UNREACHABLE;
1014 protected override bool DoEmit (EmitContext ec)
1016 if (ec.Switch == null){
1017 Report.Error (153, loc, "goto default is only valid in a switch statement");
1021 if (!ec.Switch.GotDefault){
1022 Report.Error (30132, loc, "No default target on switch statement");
1025 ec.ig.Emit (OpCodes.Br, ec.Switch.DefaultTarget);
1031 /// `goto case' statement
1033 public class GotoCase : Statement {
1037 public GotoCase (Expression e, Location l)
1043 public override bool Resolve (EmitContext ec)
1045 if (ec.Switch == null){
1046 Report.Error (153, loc, "goto case is only valid in a switch statement");
1050 expr = expr.Resolve (ec);
1054 if (!(expr is Constant)){
1055 Report.Error (30132, loc, "Target expression for goto case is not constant");
1059 object val = Expression.ConvertIntLiteral (
1060 (Constant) expr, ec.Switch.SwitchType, loc);
1065 SwitchLabel sl = (SwitchLabel) ec.Switch.Elements [val];
1070 "No such label 'case " + val + "': for the goto case");
1073 label = sl.ILLabelCode;
1075 ec.CurrentBranching.CurrentUsageVector.Breaks = FlowReturns.UNREACHABLE;
1079 protected override bool DoEmit (EmitContext ec)
1081 ec.ig.Emit (OpCodes.Br, label);
1086 public class Throw : Statement {
1089 public Throw (Expression expr, Location l)
1095 public override bool Resolve (EmitContext ec)
1098 expr = expr.Resolve (ec);
1102 ExprClass eclass = expr.eclass;
1104 if (!(eclass == ExprClass.Variable || eclass == ExprClass.PropertyAccess ||
1105 eclass == ExprClass.Value || eclass == ExprClass.IndexerAccess)) {
1106 expr.Error118 ("value, variable, property or indexer access ");
1112 if ((t != TypeManager.exception_type) &&
1113 !t.IsSubclassOf (TypeManager.exception_type) &&
1114 !(expr is NullLiteral)) {
1115 Report.Error (30665, loc,
1116 "The type caught or thrown must be derived " +
1117 "from System.Exception");
1122 ec.CurrentBranching.CurrentUsageVector.Returns = FlowReturns.EXCEPTION;
1123 ec.CurrentBranching.CurrentUsageVector.Breaks = FlowReturns.EXCEPTION;
1127 protected override bool DoEmit (EmitContext ec)
1131 ec.ig.Emit (OpCodes.Rethrow);
1135 "A throw statement with no argument is only " +
1136 "allowed in a catch clause");
1143 ec.ig.Emit (OpCodes.Throw);
1149 // Support 'End' Statement which terminates execution immediately
1151 public class End : Statement {
1153 public End (Location l)
1158 public override bool Resolve (EmitContext ec)
1163 protected override bool DoEmit (EmitContext ec)
1165 Expression e = null;
1166 Expression tmp = Mono.MonoBASIC.Parser.DecomposeQI (
1167 "Microsoft.VisualBasic.CompilerServices.ProjectData.EndApp",
1170 e = new Invocation (tmp, null, loc);
1182 public class Break : Statement {
1184 public Break (Location l)
1189 public override bool Resolve (EmitContext ec)
1191 ec.CurrentBranching.MayLeaveLoop = true;
1192 ec.CurrentBranching.CurrentUsageVector.Breaks = FlowReturns.ALWAYS;
1196 protected override bool DoEmit (EmitContext ec)
1198 ILGenerator ig = ec.ig;
1200 if (ec.InLoop == false && ec.Switch == null){
1201 Report.Error (139, loc, "No enclosing loop or switch to continue to");
1205 if (ec.InTry || ec.InCatch)
1206 ig.Emit (OpCodes.Leave, ec.LoopEnd);
1208 ig.Emit (OpCodes.Br, ec.LoopEnd);
1214 public enum ExitType {
1225 public class Exit : Statement {
1226 public readonly ExitType type;
1227 public Exit (ExitType t, Location l)
1233 public override bool Resolve (EmitContext ec)
1235 ec.CurrentBranching.MayLeaveLoop = true;
1236 ec.CurrentBranching.CurrentUsageVector.Breaks = FlowReturns.ALWAYS;
1240 protected override bool DoEmit (EmitContext ec)
1242 ILGenerator ig = ec.ig;
1244 if (type != ExitType.SUB && type != ExitType.FUNCTION &&
1245 type != ExitType.PROPERTY && type != ExitType.TRY) {
1246 if (ec.InLoop == false && ec.Switch == null){
1247 if (type == ExitType.FOR)
1248 Report.Error (30096, loc, "No enclosing FOR loop to exit from");
1249 if (type == ExitType.WHILE)
1250 Report.Error (30097, loc, "No enclosing WHILE loop to exit from");
1251 if (type == ExitType.DO)
1252 Report.Error (30089, loc, "No enclosing DO loop to exit from");
1253 if (type == ExitType.SELECT)
1254 Report.Error (30099, loc, "No enclosing SELECT to exit from");
1259 if (ec.InTry || ec.InCatch)
1260 ig.Emit (OpCodes.Leave, ec.LoopEnd);
1262 ig.Emit (OpCodes.Br, ec.LoopEnd);
1265 Report.Error (30393, loc,
1266 "Control can not leave the body of the finally block");
1270 if (ec.InTry || ec.InCatch) {
1271 if (!ec.HasReturnLabel) {
1272 ec.ReturnLabel = ec.ig.DefineLabel ();
1273 ec.HasReturnLabel = true;
1275 ec.ig.Emit (OpCodes.Leave, ec.ReturnLabel);
1277 if(type == ExitType.SUB) {
1278 ec.ig.Emit (OpCodes.Ret);
1280 ec.ig.Emit (OpCodes.Ldloc_0);
1281 ec.ig.Emit (OpCodes.Ret);
1293 public class Continue : Statement {
1295 public Continue (Location l)
1300 public override bool Resolve (EmitContext ec)
1302 ec.CurrentBranching.CurrentUsageVector.Breaks = FlowReturns.ALWAYS;
1306 protected override bool DoEmit (EmitContext ec)
1308 Label begin = ec.LoopBegin;
1311 Report.Error (139, loc, "No enclosing loop to continue to");
1316 // UGH: Non trivial. This Br might cross a try/catch boundary
1320 // try { ... } catch { continue; }
1324 // try {} catch { while () { continue; }}
1326 if (ec.TryCatchLevel > ec.LoopBeginTryCatchLevel)
1327 ec.ig.Emit (OpCodes.Leave, begin);
1328 else if (ec.TryCatchLevel < ec.LoopBeginTryCatchLevel)
1329 throw new Exception ("Should never happen");
1331 ec.ig.Emit (OpCodes.Br, begin);
1337 // This is used in the control flow analysis code to specify whether the
1338 // current code block may return to its enclosing block before reaching
1341 public enum FlowReturns {
1342 // It can never return.
1345 // This means that the block contains a conditional return statement
1349 // The code always returns, ie. there's an unconditional return / break
1353 // The code always throws an exception.
1356 // The current code block is unreachable. This happens if it's immediately
1357 // following a FlowReturns.ALWAYS block.
1362 // This is a special bit vector which can inherit from another bit vector doing a
1363 // copy-on-write strategy. The inherited vector may have a smaller size than the
1366 public class MyBitVector {
1367 public readonly int Count;
1368 public readonly MyBitVector InheritsFrom;
1373 public MyBitVector (int Count)
1374 : this (null, Count)
1377 public MyBitVector (MyBitVector InheritsFrom, int Count)
1379 this.InheritsFrom = InheritsFrom;
1384 // Checks whether this bit vector has been modified. After setting this to true,
1385 // we won't use the inherited vector anymore, but our own copy of it.
1387 public bool IsDirty {
1394 initialize_vector ();
1399 // Get/set bit `index' in the bit vector.
1401 public bool this [int index]
1405 throw new ArgumentOutOfRangeException ();
1407 // We're doing a "copy-on-write" strategy here; as long
1408 // as nobody writes to the array, we can use our parent's
1409 // copy instead of duplicating the vector.
1412 return vector [index];
1413 else if (InheritsFrom != null) {
1414 BitArray inherited = InheritsFrom.Vector;
1416 if (index < inherited.Count)
1417 return inherited [index];
1426 throw new ArgumentOutOfRangeException ();
1428 // Only copy the vector if we're actually modifying it.
1430 if (this [index] != value) {
1431 initialize_vector ();
1433 vector [index] = value;
1439 // If you explicitly convert the MyBitVector to a BitArray, you will get a deep
1440 // copy of the bit vector.
1442 public static explicit operator BitArray (MyBitVector vector)
1444 vector.initialize_vector ();
1445 return vector.Vector;
1449 // Performs an `or' operation on the bit vector. The `new_vector' may have a
1450 // different size than the current one.
1452 public void Or (MyBitVector new_vector)
1454 BitArray new_array = new_vector.Vector;
1456 initialize_vector ();
1459 if (vector.Count < new_array.Count)
1460 upper = vector.Count;
1462 upper = new_array.Count;
1464 for (int i = 0; i < upper; i++)
1465 vector [i] = vector [i] | new_array [i];
1469 // Perfonrms an `and' operation on the bit vector. The `new_vector' may have
1470 // a different size than the current one.
1472 public void And (MyBitVector new_vector)
1474 BitArray new_array = new_vector.Vector;
1476 initialize_vector ();
1479 if (vector.Count < new_array.Count)
1480 lower = upper = vector.Count;
1482 lower = new_array.Count;
1483 upper = vector.Count;
1486 for (int i = 0; i < lower; i++)
1487 vector [i] = vector [i] & new_array [i];
1489 for (int i = lower; i < upper; i++)
1494 // This does a deep copy of the bit vector.
1496 public MyBitVector Clone ()
1498 MyBitVector retval = new MyBitVector (Count);
1500 retval.Vector = Vector;
1509 else if (!is_dirty && (InheritsFrom != null))
1510 return InheritsFrom.Vector;
1512 initialize_vector ();
1518 initialize_vector ();
1520 for (int i = 0; i < System.Math.Min (vector.Count, value.Count); i++)
1521 vector [i] = value [i];
1525 void initialize_vector ()
1530 vector = new BitArray (Count, false);
1531 if (InheritsFrom != null)
1532 Vector = InheritsFrom.Vector;
1537 public override string ToString ()
1539 StringBuilder sb = new StringBuilder ("MyBitVector (");
1541 BitArray vector = Vector;
1545 sb.Append ("INHERITED - ");
1546 for (int i = 0; i < vector.Count; i++) {
1549 sb.Append (vector [i]);
1553 return sb.ToString ();
1558 // The type of a FlowBranching.
1560 public enum FlowBranchingType {
1561 // Normal (conditional or toplevel) block.
1578 // A new instance of this class is created every time a new block is resolved
1579 // and if there's branching in the block's control flow.
1581 public class FlowBranching {
1583 // The type of this flow branching.
1585 public readonly FlowBranchingType Type;
1588 // The block this branching is contained in. This may be null if it's not
1589 // a top-level block and it doesn't declare any local variables.
1591 public readonly Block Block;
1594 // The parent of this branching or null if this is the top-block.
1596 public readonly FlowBranching Parent;
1599 // Start-Location of this flow branching.
1601 public readonly Location Location;
1604 // A list of UsageVectors. A new vector is added each time control flow may
1605 // take a different path.
1607 public ArrayList Siblings;
1610 // If this is an infinite loop.
1612 public bool Infinite;
1615 // If we may leave the current loop.
1617 public bool MayLeaveLoop;
1622 InternalParameters param_info;
1624 MyStructInfo[] struct_params;
1626 ArrayList finally_vectors;
1628 static int next_id = 0;
1632 // Performs an `And' operation on the FlowReturns status
1633 // (for instance, a block only returns ALWAYS if all its siblings
1636 public static FlowReturns AndFlowReturns (FlowReturns a, FlowReturns b)
1638 if (b == FlowReturns.UNREACHABLE)
1642 case FlowReturns.NEVER:
1643 if (b == FlowReturns.NEVER)
1644 return FlowReturns.NEVER;
1646 return FlowReturns.SOMETIMES;
1648 case FlowReturns.SOMETIMES:
1649 return FlowReturns.SOMETIMES;
1651 case FlowReturns.ALWAYS:
1652 if ((b == FlowReturns.ALWAYS) || (b == FlowReturns.EXCEPTION))
1653 return FlowReturns.ALWAYS;
1655 return FlowReturns.SOMETIMES;
1657 case FlowReturns.EXCEPTION:
1658 if (b == FlowReturns.EXCEPTION)
1659 return FlowReturns.EXCEPTION;
1660 else if (b == FlowReturns.ALWAYS)
1661 return FlowReturns.ALWAYS;
1663 return FlowReturns.SOMETIMES;
1670 // The vector contains a BitArray with information about which local variables
1671 // and parameters are already initialized at the current code position.
1673 public class UsageVector {
1675 // If this is true, then the usage vector has been modified and must be
1676 // merged when we're done with this branching.
1678 public bool IsDirty;
1681 // The number of parameters in this block.
1683 public readonly int CountParameters;
1686 // The number of locals in this block.
1688 public readonly int CountLocals;
1691 // If not null, then we inherit our state from this vector and do a
1692 // copy-on-write. If null, then we're the first sibling in a top-level
1693 // block and inherit from the empty vector.
1695 public readonly UsageVector InheritsFrom;
1700 MyBitVector locals, parameters;
1701 FlowReturns real_returns, real_breaks;
1704 static int next_id = 0;
1708 // Normally, you should not use any of these constructors.
1710 public UsageVector (UsageVector parent, int num_params, int num_locals)
1712 this.InheritsFrom = parent;
1713 this.CountParameters = num_params;
1714 this.CountLocals = num_locals;
1715 this.real_returns = FlowReturns.NEVER;
1716 this.real_breaks = FlowReturns.NEVER;
1718 if (parent != null) {
1719 locals = new MyBitVector (parent.locals, CountLocals);
1721 parameters = new MyBitVector (parent.parameters, num_params);
1722 real_returns = parent.Returns;
1723 real_breaks = parent.Breaks;
1725 locals = new MyBitVector (null, CountLocals);
1727 parameters = new MyBitVector (null, num_params);
1733 public UsageVector (UsageVector parent)
1734 : this (parent, parent.CountParameters, parent.CountLocals)
1738 // This does a deep copy of the usage vector.
1740 public UsageVector Clone ()
1742 UsageVector retval = new UsageVector (null, CountParameters, CountLocals);
1744 retval.locals = locals.Clone ();
1745 if (parameters != null)
1746 retval.parameters = parameters.Clone ();
1747 retval.real_returns = real_returns;
1748 retval.real_breaks = real_breaks;
1754 // State of parameter `number'.
1756 public bool this [int number]
1761 else if (number == 0)
1762 throw new ArgumentException ();
1764 return parameters [number - 1];
1770 else if (number == 0)
1771 throw new ArgumentException ();
1773 parameters [number - 1] = value;
1778 // State of the local variable `vi'.
1779 // If the local variable is a struct, use a non-zero `field_idx'
1780 // to check an individual field in it.
1782 public bool this [VariableInfo vi, int field_idx]
1785 if (vi.Number == -1)
1787 else if (vi.Number == 0)
1788 throw new ArgumentException ();
1790 return locals [vi.Number + field_idx - 1];
1794 if (vi.Number == -1)
1796 else if (vi.Number == 0)
1797 throw new ArgumentException ();
1799 locals [vi.Number + field_idx - 1] = value;
1804 // Specifies when the current block returns.
1805 // If this is FlowReturns.UNREACHABLE, then control can never reach the
1806 // end of the method (so that we don't need to emit a return statement).
1807 // The same applies for FlowReturns.EXCEPTION, but in this case the return
1808 // value will never be used.
1810 public FlowReturns Returns {
1812 return real_returns;
1816 real_returns = value;
1821 // Specifies whether control may return to our containing block
1822 // before reaching the end of this block. This happens if there
1823 // is a break/continue/goto/return in it.
1824 // This can also be used to find out whether the statement immediately
1825 // following the current block may be reached or not.
1827 public FlowReturns Breaks {
1833 real_breaks = value;
1837 public bool AlwaysBreaks {
1839 return (Breaks == FlowReturns.ALWAYS) ||
1840 (Breaks == FlowReturns.EXCEPTION) ||
1841 (Breaks == FlowReturns.UNREACHABLE);
1845 public bool MayBreak {
1847 return Breaks != FlowReturns.NEVER;
1851 public bool AlwaysReturns {
1853 return (Returns == FlowReturns.ALWAYS) ||
1854 (Returns == FlowReturns.EXCEPTION);
1858 public bool MayReturn {
1860 return (Returns == FlowReturns.SOMETIMES) ||
1861 (Returns == FlowReturns.ALWAYS);
1866 // Merge a child branching.
1868 public FlowReturns MergeChildren (FlowBranching branching, ICollection children)
1870 MyBitVector new_locals = null;
1871 MyBitVector new_params = null;
1873 FlowReturns new_returns = FlowReturns.NEVER;
1874 FlowReturns new_breaks = FlowReturns.NEVER;
1875 bool new_returns_set = false, new_breaks_set = false;
1877 Report.Debug (2, "MERGING CHILDREN", branching, branching.Type,
1878 this, children.Count);
1880 foreach (UsageVector child in children) {
1881 Report.Debug (2, " MERGING CHILD", child, child.is_finally);
1883 if (!child.is_finally) {
1884 if (child.Breaks != FlowReturns.UNREACHABLE) {
1885 // If Returns is already set, perform an
1886 // `And' operation on it, otherwise just set just.
1887 if (!new_returns_set) {
1888 new_returns = child.Returns;
1889 new_returns_set = true;
1891 new_returns = AndFlowReturns (
1892 new_returns, child.Returns);
1895 // If Breaks is already set, perform an
1896 // `And' operation on it, otherwise just set just.
1897 if (!new_breaks_set) {
1898 new_breaks = child.Breaks;
1899 new_breaks_set = true;
1901 new_breaks = AndFlowReturns (
1902 new_breaks, child.Breaks);
1905 // Ignore unreachable children.
1906 if (child.Returns == FlowReturns.UNREACHABLE)
1909 // A local variable is initialized after a flow branching if it
1910 // has been initialized in all its branches which do neither
1911 // always return or always throw an exception.
1913 // If a branch may return, but does not always return, then we
1914 // can treat it like a never-returning branch here: control will
1915 // only reach the code position after the branching if we did not
1918 // It's important to distinguish between always and sometimes
1919 // returning branches here:
1922 // 2 if (something) {
1926 // 6 Console.WriteLine (a);
1928 // The if block in lines 3-4 always returns, so we must not look
1929 // at the initialization of `a' in line 4 - thus it'll still be
1930 // uninitialized in line 6.
1932 // On the other hand, the following is allowed:
1939 // 6 Console.WriteLine (a);
1941 // Here, `a' is initialized in line 3 and we must not look at
1942 // line 5 since it always returns.
1944 if (child.is_finally) {
1945 if (new_locals == null)
1946 new_locals = locals.Clone ();
1947 new_locals.Or (child.locals);
1949 if (parameters != null) {
1950 if (new_params == null)
1951 new_params = parameters.Clone ();
1952 new_params.Or (child.parameters);
1956 if (!child.AlwaysReturns && !child.AlwaysBreaks) {
1957 if (new_locals != null)
1958 new_locals.And (child.locals);
1960 new_locals = locals.Clone ();
1961 new_locals.Or (child.locals);
1963 } else if (children.Count == 1) {
1964 new_locals = locals.Clone ();
1965 new_locals.Or (child.locals);
1968 // An `out' parameter must be assigned in all branches which do
1969 // not always throw an exception.
1970 if (parameters != null) {
1971 if (child.Breaks != FlowReturns.EXCEPTION) {
1972 if (new_params != null)
1973 new_params.And (child.parameters);
1975 new_params = parameters.Clone ();
1976 new_params.Or (child.parameters);
1978 } else if (children.Count == 1) {
1979 new_params = parameters.Clone ();
1980 new_params.Or (child.parameters);
1986 Returns = new_returns;
1987 if ((branching.Type == FlowBranchingType.BLOCK) ||
1988 (branching.Type == FlowBranchingType.EXCEPTION) ||
1989 (new_breaks == FlowReturns.UNREACHABLE) ||
1990 (new_breaks == FlowReturns.EXCEPTION))
1991 Breaks = new_breaks;
1992 else if (branching.Type == FlowBranchingType.SWITCH_SECTION)
1993 Breaks = new_returns;
1994 else if (branching.Type == FlowBranchingType.SWITCH){
1995 if (new_breaks == FlowReturns.ALWAYS)
1996 Breaks = FlowReturns.ALWAYS;
2000 // We've now either reached the point after the branching or we will
2001 // never get there since we always return or always throw an exception.
2003 // If we can reach the point after the branching, mark all locals and
2004 // parameters as initialized which have been initialized in all branches
2005 // we need to look at (see above).
2008 if (((new_breaks != FlowReturns.ALWAYS) &&
2009 (new_breaks != FlowReturns.EXCEPTION) &&
2010 (new_breaks != FlowReturns.UNREACHABLE)) ||
2011 (children.Count == 1)) {
2012 if (new_locals != null)
2013 locals.Or (new_locals);
2015 if (new_params != null)
2016 parameters.Or (new_params);
2019 Report.Debug (2, "MERGING CHILDREN DONE", branching.Type,
2020 new_params, new_locals, new_returns, new_breaks,
2021 branching.Infinite, branching.MayLeaveLoop, this);
2023 if (branching.Type == FlowBranchingType.SWITCH_SECTION) {
2024 if ((new_breaks != FlowReturns.ALWAYS) &&
2025 (new_breaks != FlowReturns.EXCEPTION) &&
2026 (new_breaks != FlowReturns.UNREACHABLE))
2027 Report.Error (163, branching.Location,
2028 "Control cannot fall through from one " +
2029 "case label to another");
2032 if (branching.Infinite && !branching.MayLeaveLoop) {
2033 Report.Debug (1, "INFINITE", new_returns, new_breaks,
2034 Returns, Breaks, this);
2036 // We're actually infinite.
2037 if (new_returns == FlowReturns.NEVER) {
2038 Breaks = FlowReturns.UNREACHABLE;
2039 return FlowReturns.UNREACHABLE;
2042 // If we're an infinite loop and do not break, the code after
2043 // the loop can never be reached. However, if we may return
2044 // from the loop, then we do always return (or stay in the loop
2046 if ((new_returns == FlowReturns.SOMETIMES) ||
2047 (new_returns == FlowReturns.ALWAYS)) {
2048 Returns = FlowReturns.ALWAYS;
2049 return FlowReturns.ALWAYS;
2057 // Tells control flow analysis that the current code position may be reached with
2058 // a forward jump from any of the origins listed in `origin_vectors' which is a
2059 // list of UsageVectors.
2061 // This is used when resolving forward gotos - in the following example, the
2062 // variable `a' is uninitialized in line 8 becase this line may be reached via
2063 // the goto in line 4:
2073 // 8 Console.WriteLine (a);
2076 public void MergeJumpOrigins (ICollection origin_vectors)
2078 Report.Debug (1, "MERGING JUMP ORIGIN", this);
2080 real_breaks = FlowReturns.NEVER;
2081 real_returns = FlowReturns.NEVER;
2083 foreach (UsageVector vector in origin_vectors) {
2084 Report.Debug (1, " MERGING JUMP ORIGIN", vector);
2086 locals.And (vector.locals);
2087 if (parameters != null)
2088 parameters.And (vector.parameters);
2089 Breaks = AndFlowReturns (Breaks, vector.Breaks);
2090 Returns = AndFlowReturns (Returns, vector.Returns);
2093 Report.Debug (1, "MERGING JUMP ORIGIN DONE", this);
2097 // This is used at the beginning of a finally block if there were
2098 // any return statements in the try block or one of the catch blocks.
2100 public void MergeFinallyOrigins (ICollection finally_vectors)
2102 Report.Debug (1, "MERGING FINALLY ORIGIN", this);
2104 real_breaks = FlowReturns.NEVER;
2106 foreach (UsageVector vector in finally_vectors) {
2107 Report.Debug (1, " MERGING FINALLY ORIGIN", vector);
2109 if (parameters != null)
2110 parameters.And (vector.parameters);
2111 Breaks = AndFlowReturns (Breaks, vector.Breaks);
2116 Report.Debug (1, "MERGING FINALLY ORIGIN DONE", this);
2119 // Performs an `or' operation on the locals and the parameters.
2121 public void Or (UsageVector new_vector)
2123 locals.Or (new_vector.locals);
2124 if (parameters != null)
2125 parameters.Or (new_vector.parameters);
2129 // Performs an `and' operation on the locals.
2131 public void AndLocals (UsageVector new_vector)
2133 locals.And (new_vector.locals);
2137 // Returns a deep copy of the parameters.
2139 public MyBitVector Parameters {
2141 if (parameters != null)
2142 return parameters.Clone ();
2149 // Returns a deep copy of the locals.
2151 public MyBitVector Locals {
2153 return locals.Clone ();
2161 public override string ToString ()
2163 StringBuilder sb = new StringBuilder ();
2165 sb.Append ("Vector (");
2168 sb.Append (Returns);
2171 if (parameters != null) {
2173 sb.Append (parameters);
2179 return sb.ToString ();
2183 FlowBranching (FlowBranchingType type, Location loc)
2185 this.Siblings = new ArrayList ();
2187 this.Location = loc;
2193 // Creates a new flow branching for `block'.
2194 // This is used from Block.Resolve to create the top-level branching of
2197 public FlowBranching (Block block, InternalParameters ip, Location loc)
2198 : this (FlowBranchingType.BLOCK, loc)
2203 int count = (ip != null) ? ip.Count : 0;
2206 param_map = new int [count];
2207 struct_params = new MyStructInfo [count];
2210 for (int i = 0; i < count; i++) {
2211 Parameter.Modifier mod = param_info.ParameterModifier (i);
2213 // if ((mod & Parameter.Modifier.OUT) == 0)
2216 param_map [i] = ++num_params;
2218 Type param_type = param_info.ParameterType (i);
2220 struct_params [i] = MyStructInfo.GetStructInfo (param_type);
2221 if (struct_params [i] != null)
2222 num_params += struct_params [i].Count;
2225 Siblings = new ArrayList ();
2226 Siblings.Add (new UsageVector (null, num_params, block.CountVariables));
2230 // Creates a new flow branching which is contained in `parent'.
2231 // You should only pass non-null for the `block' argument if this block
2232 // introduces any new variables - in this case, we need to create a new
2233 // usage vector with a different size than our parent's one.
2235 public FlowBranching (FlowBranching parent, FlowBranchingType type,
2236 Block block, Location loc)
2242 if (parent != null) {
2243 param_info = parent.param_info;
2244 param_map = parent.param_map;
2245 struct_params = parent.struct_params;
2246 num_params = parent.num_params;
2251 vector = new UsageVector (parent.CurrentUsageVector, num_params,
2252 Block.CountVariables);
2254 vector = new UsageVector (Parent.CurrentUsageVector);
2256 Siblings.Add (vector);
2259 case FlowBranchingType.EXCEPTION:
2260 finally_vectors = new ArrayList ();
2269 // Returns the branching's current usage vector.
2271 public UsageVector CurrentUsageVector
2274 return (UsageVector) Siblings [Siblings.Count - 1];
2279 // Creates a sibling of the current usage vector.
2281 public void CreateSibling ()
2283 Siblings.Add (new UsageVector (Parent.CurrentUsageVector));
2285 Report.Debug (1, "CREATED SIBLING", CurrentUsageVector);
2289 // Creates a sibling for a `finally' block.
2291 public void CreateSiblingForFinally ()
2293 if (Type != FlowBranchingType.EXCEPTION)
2294 throw new NotSupportedException ();
2298 CurrentUsageVector.MergeFinallyOrigins (finally_vectors);
2303 // Merge a child branching.
2305 public FlowReturns MergeChild (FlowBranching child)
2307 FlowReturns returns = CurrentUsageVector.MergeChildren (child, child.Siblings);
2309 if (child.Type != FlowBranchingType.LOOP_BLOCK)
2310 MayLeaveLoop |= child.MayLeaveLoop;
2312 MayLeaveLoop = false;
2318 // Does the toplevel merging.
2320 public FlowReturns MergeTopBlock ()
2322 if ((Type != FlowBranchingType.BLOCK) || (Block == null))
2323 throw new NotSupportedException ();
2325 UsageVector vector = new UsageVector (null, num_params, Block.CountVariables);
2327 Report.Debug (1, "MERGING TOP BLOCK", Location, vector);
2329 vector.MergeChildren (this, Siblings);
2332 Siblings.Add (vector);
2334 Report.Debug (1, "MERGING TOP BLOCK DONE", Location, vector);
2336 if (vector.Breaks != FlowReturns.EXCEPTION) {
2337 return vector.AlwaysBreaks ? FlowReturns.ALWAYS : vector.Returns;
2339 return FlowReturns.EXCEPTION;
2342 public bool InTryBlock ()
2344 if (finally_vectors != null)
2346 else if (Parent != null)
2347 return Parent.InTryBlock ();
2352 public void AddFinallyVector (UsageVector vector)
2354 if (finally_vectors != null) {
2355 finally_vectors.Add (vector.Clone ());
2360 Parent.AddFinallyVector (vector);
2362 throw new NotSupportedException ();
2365 public bool IsVariableAssigned (VariableInfo vi)
2367 if (CurrentUsageVector.AlwaysBreaks)
2370 return CurrentUsageVector [vi, 0];
2373 public bool IsVariableAssigned (VariableInfo vi, int field_idx)
2375 if (CurrentUsageVector.AlwaysBreaks)
2378 return CurrentUsageVector [vi, field_idx];
2381 public void SetVariableAssigned (VariableInfo vi)
2383 if (CurrentUsageVector.AlwaysBreaks)
2386 CurrentUsageVector [vi, 0] = true;
2389 public void SetVariableAssigned (VariableInfo vi, int field_idx)
2391 if (CurrentUsageVector.AlwaysBreaks)
2394 CurrentUsageVector [vi, field_idx] = true;
2397 public bool IsParameterAssigned (int number)
2399 int index = param_map [number];
2404 if (CurrentUsageVector [index])
2407 // Parameter is not assigned, so check whether it's a struct.
2408 // If it's either not a struct or a struct which non-public
2409 // fields, return false.
2410 MyStructInfo struct_info = struct_params [number];
2411 if ((struct_info == null) || struct_info.HasNonPublicFields)
2414 // Ok, so each field must be assigned.
2415 for (int i = 0; i < struct_info.Count; i++)
2416 if (!CurrentUsageVector [index + i])
2422 public bool IsParameterAssigned (int number, string field_name)
2424 int index = param_map [number];
2429 MyStructInfo info = (MyStructInfo) struct_params [number];
2433 int field_idx = info [field_name];
2435 return CurrentUsageVector [index + field_idx];
2438 public void SetParameterAssigned (int number)
2440 if (param_map [number] == 0)
2443 if (!CurrentUsageVector.AlwaysBreaks)
2444 CurrentUsageVector [param_map [number]] = true;
2447 public void SetParameterAssigned (int number, string field_name)
2449 int index = param_map [number];
2454 MyStructInfo info = (MyStructInfo) struct_params [number];
2458 int field_idx = info [field_name];
2460 if (!CurrentUsageVector.AlwaysBreaks)
2461 CurrentUsageVector [index + field_idx] = true;
2464 public bool IsReachable ()
2469 case FlowBranchingType.SWITCH_SECTION:
2470 // The code following a switch block is reachable unless the switch
2471 // block always returns.
2472 reachable = !CurrentUsageVector.AlwaysReturns;
2475 case FlowBranchingType.LOOP_BLOCK:
2476 // The code following a loop is reachable unless the loop always
2477 // returns or it's an infinite loop without any `break's in it.
2478 reachable = !CurrentUsageVector.AlwaysReturns &&
2479 (CurrentUsageVector.Breaks != FlowReturns.UNREACHABLE);
2483 // The code following a block or exception is reachable unless the
2484 // block either always returns or always breaks.
2485 reachable = !CurrentUsageVector.AlwaysBreaks &&
2486 !CurrentUsageVector.AlwaysReturns;
2490 Report.Debug (1, "REACHABLE", Type, CurrentUsageVector.Returns,
2491 CurrentUsageVector.Breaks, CurrentUsageVector, reachable);
2496 public override string ToString ()
2498 StringBuilder sb = new StringBuilder ("FlowBranching (");
2503 if (Block != null) {
2505 sb.Append (Block.ID);
2507 sb.Append (Block.StartLocation);
2510 sb.Append (Siblings.Count);
2512 sb.Append (CurrentUsageVector);
2514 return sb.ToString ();
2518 public class MyStructInfo {
2519 public readonly Type Type;
2520 public readonly FieldInfo[] Fields;
2521 public readonly FieldInfo[] NonPublicFields;
2522 public readonly int Count;
2523 public readonly int CountNonPublic;
2524 public readonly bool HasNonPublicFields;
2526 private static Hashtable field_type_hash = new Hashtable ();
2527 private Hashtable field_hash;
2529 // Private constructor. To save memory usage, we only need to create one instance
2530 // of this class per struct type.
2531 private MyStructInfo (Type type)
2535 if (type is TypeBuilder) {
2536 TypeContainer tc = TypeManager.LookupTypeContainer (type);
2538 ArrayList fields = tc.Fields;
2539 if (fields != null) {
2540 foreach (Field field in fields) {
2541 if ((field.ModFlags & Modifiers.STATIC) != 0)
2543 if ((field.ModFlags & Modifiers.PUBLIC) != 0)
2550 Fields = new FieldInfo [Count];
2551 NonPublicFields = new FieldInfo [CountNonPublic];
2553 Count = CountNonPublic = 0;
2554 if (fields != null) {
2555 foreach (Field field in fields) {
2556 if ((field.ModFlags & Modifiers.STATIC) != 0)
2558 if ((field.ModFlags & Modifiers.PUBLIC) != 0)
2559 Fields [Count++] = field.FieldBuilder;
2561 NonPublicFields [CountNonPublic++] =
2567 Fields = type.GetFields (BindingFlags.Instance|BindingFlags.Public);
2568 Count = Fields.Length;
2570 NonPublicFields = type.GetFields (BindingFlags.Instance|BindingFlags.NonPublic);
2571 CountNonPublic = NonPublicFields.Length;
2574 Count += NonPublicFields.Length;
2577 field_hash = new Hashtable ();
2578 foreach (FieldInfo field in Fields)
2579 field_hash.Add (field.Name, ++number);
2581 if (NonPublicFields.Length != 0)
2582 HasNonPublicFields = true;
2584 foreach (FieldInfo field in NonPublicFields)
2585 field_hash.Add (field.Name, ++number);
2588 public int this [string name] {
2590 if (field_hash.Contains (name))
2591 return (int) field_hash [name];
2597 public FieldInfo this [int index] {
2599 if (index >= Fields.Length)
2600 return NonPublicFields [index - Fields.Length];
2602 return Fields [index];
2606 public static MyStructInfo GetStructInfo (Type type)
2608 if (!TypeManager.IsValueType (type) || TypeManager.IsEnumType (type))
2611 if (!(type is TypeBuilder) && TypeManager.IsBuiltinType (type))
2614 MyStructInfo info = (MyStructInfo) field_type_hash [type];
2618 info = new MyStructInfo (type);
2619 field_type_hash.Add (type, info);
2623 public static MyStructInfo GetStructInfo (TypeContainer tc)
2625 MyStructInfo info = (MyStructInfo) field_type_hash [tc.TypeBuilder];
2629 info = new MyStructInfo (tc.TypeBuilder);
2630 field_type_hash.Add (tc.TypeBuilder, info);
2635 public class VariableInfo : IVariable {
2636 public Expression Type;
2637 public LocalBuilder LocalBuilder;
2638 public Type VariableType;
2639 public readonly string Name;
2640 public readonly Location Location;
2641 public readonly int Block;
2646 public bool Assigned;
2647 public bool ReadOnly;
2649 public VariableInfo (Expression type, string name, int block, Location l)
2654 LocalBuilder = null;
2658 public VariableInfo (TypeContainer tc, int block, Location l)
2660 VariableType = tc.TypeBuilder;
2661 struct_info = MyStructInfo.GetStructInfo (tc);
2663 LocalBuilder = null;
2667 MyStructInfo struct_info;
2668 public MyStructInfo StructInfo {
2674 public bool IsAssigned (EmitContext ec, Location loc)
2675 {/* FIXME: we shouldn't just skip this!!!
2676 if (!ec.DoFlowAnalysis || ec.CurrentBranching.IsVariableAssigned (this))
2679 MyStructInfo struct_info = StructInfo;
2680 if ((struct_info == null) || (struct_info.HasNonPublicFields && (Name != null))) {
2681 Report.Error (165, loc, "Use of unassigned local variable `" + Name + "'");
2682 ec.CurrentBranching.SetVariableAssigned (this);
2686 int count = struct_info.Count;
2688 for (int i = 0; i < count; i++) {
2689 if (!ec.CurrentBranching.IsVariableAssigned (this, i+1)) {
2691 Report.Error (165, loc,
2692 "Use of unassigned local variable `" +
2694 ec.CurrentBranching.SetVariableAssigned (this);
2698 FieldInfo field = struct_info [i];
2699 Report.Error (171, loc,
2700 "Field `" + TypeManager.MonoBASIC_Name (VariableType) +
2701 "." + field.Name + "' must be fully initialized " +
2702 "before control leaves the constructor");
2710 public bool IsFieldAssigned (EmitContext ec, string name, Location loc)
2712 if (!ec.DoFlowAnalysis || ec.CurrentBranching.IsVariableAssigned (this) ||
2713 (struct_info == null))
2716 int field_idx = StructInfo [name];
2720 if (!ec.CurrentBranching.IsVariableAssigned (this, field_idx)) {
2721 Report.Error (170, loc,
2722 "Use of possibly unassigned field `" + name + "'");
2723 ec.CurrentBranching.SetVariableAssigned (this, field_idx);
2730 public void SetAssigned (EmitContext ec)
2732 if (ec.DoFlowAnalysis)
2733 ec.CurrentBranching.SetVariableAssigned (this);
2736 public void SetFieldAssigned (EmitContext ec, string name)
2738 if (ec.DoFlowAnalysis && (struct_info != null))
2739 ec.CurrentBranching.SetVariableAssigned (this, StructInfo [name]);
2742 public bool Resolve (DeclSpace decl)
2744 if (struct_info != null)
2747 if (VariableType == null)
2748 VariableType = decl.ResolveType (Type, false, Location);
2750 if (VariableType == null)
2753 struct_info = MyStructInfo.GetStructInfo (VariableType);
2758 public void MakePinned ()
2760 TypeManager.MakePinned (LocalBuilder);
2763 public override string ToString ()
2765 return "VariableInfo (" + Number + "," + Type + "," + Location + ")";
2770 /// Block represents a C# block.
2774 /// This class is used in a number of places: either to represent
2775 /// explicit blocks that the programmer places or implicit blocks.
2777 /// Implicit blocks are used as labels or to introduce variable
2780 public class Block : Statement {
2781 public readonly Block Parent;
2782 public readonly bool Implicit;
2783 public readonly Location StartLocation;
2784 public Location EndLocation;
2787 // The statements in this block
2789 public ArrayList statements;
2792 // An array of Blocks. We keep track of children just
2793 // to generate the local variable declarations.
2795 // Statements and child statements are handled through the
2801 // Labels. (label, block) pairs.
2803 CaseInsensitiveHashtable labels;
2806 // Keeps track of (name, type) pairs
2808 CaseInsensitiveHashtable variables;
2811 // Keeps track of constants
2812 CaseInsensitiveHashtable constants;
2815 // Maps variable names to ILGenerator.LocalBuilders
2817 CaseInsensitiveHashtable local_builders;
2819 // to hold names of variables required for late binding
2820 public const string lateBindingArgs = "1_LBArgs";
2821 public const string lateBindingArgNames = "1_LBArgsNames";
2822 public const string lateBindingCopyBack = "1_LBCopyBack";
2824 bool isLateBindingRequired = false;
2832 public Block (Block parent)
2833 : this (parent, false, Location.Null, Location.Null)
2836 public Block (Block parent, bool implicit_block)
2837 : this (parent, implicit_block, Location.Null, Location.Null)
2840 public Block (Block parent, bool implicit_block, Parameters parameters)
2841 : this (parent, implicit_block, parameters, Location.Null, Location.Null)
2844 public Block (Block parent, Location start, Location end)
2845 : this (parent, false, start, end)
2848 public Block (Block parent, Parameters parameters, Location start, Location end)
2849 : this (parent, false, parameters, start, end)
2852 public Block (Block parent, bool implicit_block, Location start, Location end)
2853 : this (parent, implicit_block, Parameters.EmptyReadOnlyParameters,
2857 public Block (Block parent, bool implicit_block, Parameters parameters,
2858 Location start, Location end)
2861 parent.AddChild (this);
2864 // Add variables that may be required for late binding
2865 variables = new CaseInsensitiveHashtable ();
2866 ArrayList rank_specifier = new ArrayList ();
2867 ArrayList element = new ArrayList ();
2868 element.Add (new EmptyExpression ());
2869 rank_specifier.Add (element);
2870 Expression e = Mono.MonoBASIC.Parser.DecomposeQI ("System.Object[]", start);
2871 AddVariable (e, Block.lateBindingArgs, null, start);
2872 e = Mono.MonoBASIC.Parser.DecomposeQI ("System.String[]", start);
2873 AddVariable (e, Block.lateBindingArgNames, null, start);
2874 e = Mono.MonoBASIC.Parser.DecomposeQI ("System.Boolean[]", start);
2875 AddVariable (e, Block.lateBindingCopyBack, null, start);
2878 this.Parent = parent;
2879 this.Implicit = implicit_block;
2880 this.parameters = parameters;
2881 this.StartLocation = start;
2882 this.EndLocation = end;
2885 statements = new ArrayList ();
2888 public bool IsLateBindingRequired {
2890 return isLateBindingRequired;
2893 isLateBindingRequired = value;
2903 void AddChild (Block b)
2905 if (children == null)
2906 children = new ArrayList ();
2911 public void SetEndLocation (Location loc)
2917 /// Adds a label to the current block.
2921 /// false if the name already exists in this block. true
2925 public bool AddLabel (string name, LabeledStatement target)
2928 labels = new CaseInsensitiveHashtable ();
2929 if (labels.Contains (name))
2932 labels.Add (name, target);
2936 public LabeledStatement LookupLabel (string name)
2938 if (labels != null){
2939 if (labels.Contains (name))
2940 return ((LabeledStatement) labels [name]);
2944 return Parent.LookupLabel (name);
2949 VariableInfo this_variable = null;
2952 // Returns the "this" instance variable of this block.
2953 // See AddThisVariable() for more information.
2955 public VariableInfo ThisVariable {
2957 if (this_variable != null)
2958 return this_variable;
2959 else if (Parent != null)
2960 return Parent.ThisVariable;
2966 Hashtable child_variable_names;
2969 // Marks a variable with name @name as being used in a child block.
2970 // If a variable name has been used in a child block, it's illegal to
2971 // declare a variable with the same name in the current block.
2973 public void AddChildVariableName (string name)
2975 if (child_variable_names == null)
2976 child_variable_names = new CaseInsensitiveHashtable ();
2978 if (!child_variable_names.Contains (name))
2979 child_variable_names.Add (name, true);
2983 // Marks all variables from block @block and all its children as being
2984 // used in a child block.
2986 public void AddChildVariableNames (Block block)
2988 if (block.Variables != null) {
2989 foreach (string name in block.Variables.Keys)
2990 AddChildVariableName (name);
2993 foreach (Block child in block.children) {
2994 if (child.Variables != null) {
2995 foreach (string name in child.Variables.Keys)
2996 AddChildVariableName (name);
3002 // Checks whether a variable name has already been used in a child block.
3004 public bool IsVariableNameUsedInChildBlock (string name)
3006 if (child_variable_names == null)
3009 return child_variable_names.Contains (name);
3013 // This is used by non-static `struct' constructors which do not have an
3014 // initializer - in this case, the constructor must initialize all of the
3015 // struct's fields. To do this, we add a "this" variable and use the flow
3016 // analysis code to ensure that it's been fully initialized before control
3017 // leaves the constructor.
3019 public VariableInfo AddThisVariable (TypeContainer tc, Location l)
3021 if (this_variable != null)
3022 return this_variable;
3024 this_variable = new VariableInfo (tc, ID, l);
3026 if (variables == null)
3027 variables = new CaseInsensitiveHashtable ();
3028 variables.Add ("this", this_variable);
3030 return this_variable;
3033 public VariableInfo AddVariable (Expression type, string name, Parameters pars, Location l)
3035 if (variables == null)
3036 variables = new CaseInsensitiveHashtable ();
3038 VariableInfo vi = GetVariableInfo (name);
3041 Report.Error (30616, l, "A local variable named `" + name + "' " +
3042 "cannot be declared in this scope since it would " +
3043 "give a different meaning to `" + name + "', which " +
3044 "is already used in a `parent or current' scope to " +
3045 "denote something else");
3047 Report.Error (30290, l, "A local variable `" + name + "' is already " +
3048 "defined in this scope");
3052 if (IsVariableNameUsedInChildBlock (name)) {
3053 Report.Error (136, l, "A local variable named `" + name + "' " +
3054 "cannot be declared in this scope since it would " +
3055 "give a different meaning to `" + name + "', which " +
3056 "is already used in a `child' scope to denote something " +
3063 Parameter p = pars.GetParameterByName (name, out idx);
3065 Report.Error (30616, l, "A local variable named `" + name + "' " +
3066 "cannot be declared in this scope since it would " +
3067 "give a different meaning to `" + name + "', which " +
3068 "is already used in a `parent or current' scope to " +
3069 "denote something else");
3074 vi = new VariableInfo (type, name, ID, l);
3076 variables.Add (name, vi);
3078 if (variables_initialized)
3079 throw new Exception ();
3081 // Console.WriteLine ("Adding {0} to {1}", name, ID);
3085 public bool AddConstant (Expression type, string name, Expression value, Parameters pars, Location l)
3087 if (AddVariable (type, name, pars, l) == null)
3090 if (constants == null)
3091 constants = new CaseInsensitiveHashtable ();
3093 constants.Add (name, value);
3097 public Hashtable Variables {
3103 public VariableInfo GetVariableInfo (string name)
3105 if (variables != null) {
3107 temp = variables [name];
3110 return (VariableInfo) temp;
3115 return Parent.GetVariableInfo (name);
3120 public Expression GetVariableType (string name)
3122 VariableInfo vi = GetVariableInfo (name);
3130 public Expression GetConstantExpression (string name)
3132 if (constants != null) {
3134 temp = constants [name];
3137 return (Expression) temp;
3141 return Parent.GetConstantExpression (name);
3147 /// True if the variable named @name has been defined
3150 public bool IsVariableDefined (string name)
3152 // Console.WriteLine ("Looking up {0} in {1}", name, ID);
3153 if (variables != null) {
3154 if (variables.Contains (name))
3159 return Parent.IsVariableDefined (name);
3165 /// True if the variable named @name is a constant
3167 public bool IsConstant (string name)
3169 Expression e = null;
3171 e = GetConstantExpression (name);
3177 /// Use to fetch the statement associated with this label
3179 public Statement this [string name] {
3181 return (Statement) labels [name];
3185 Parameters parameters = null;
3186 public Parameters Parameters {
3189 return Parent.Parameters;
3196 /// A list of labels that were not used within this block
3198 public string [] GetUnreferenced ()
3200 // FIXME: Implement me
3204 public void AddStatement (Statement s)
3221 bool variables_initialized = false;
3222 int count_variables = 0, first_variable = 0;
3224 void UpdateVariableInfo (EmitContext ec)
3226 DeclSpace ds = ec.DeclSpace;
3231 first_variable += Parent.CountVariables;
3233 count_variables = first_variable;
3234 if (variables != null) {
3235 foreach (VariableInfo vi in variables.Values) {
3236 if (!vi.Resolve (ds)) {
3241 vi.Number = ++count_variables;
3243 if (vi.StructInfo != null)
3244 count_variables += vi.StructInfo.Count;
3248 variables_initialized = true;
3253 // The number of local variables in this block
3255 public int CountVariables
3258 if (!variables_initialized)
3259 throw new Exception ();
3261 return count_variables;
3266 /// Emits the variable declarations and labels.
3269 /// tc: is our typecontainer (to resolve type references)
3270 /// ig: is the code generator:
3271 /// toplevel: the toplevel block. This is used for checking
3272 /// that no two labels with the same name are used.
3274 public void EmitMeta (EmitContext ec, Block toplevel)
3276 //DeclSpace ds = ec.DeclSpace;
3277 ILGenerator ig = ec.ig;
3279 if (!variables_initialized)
3280 UpdateVariableInfo (ec);
3283 // Process this block variables
3285 if (variables != null){
3286 local_builders = new CaseInsensitiveHashtable ();
3288 foreach (DictionaryEntry de in variables){
3289 string name = (string) de.Key;
3291 if (!isLateBindingRequired) {
3292 if (name.Equals (Block.lateBindingArgs) ||
3293 name.Equals (Block.lateBindingArgNames) ||
3294 name.Equals (Block.lateBindingCopyBack))
3298 VariableInfo vi = (VariableInfo) de.Value;
3300 if (vi.VariableType == null)
3303 vi.LocalBuilder = ig.DeclareLocal (vi.VariableType);
3305 if (CodeGen.SymbolWriter != null)
3306 vi.LocalBuilder.SetLocalSymInfo (name);
3308 if (constants == null)
3311 Expression cv = (Expression) constants [name];
3315 Expression e = cv.Resolve (ec);
3319 if (!(e is Constant)){
3320 Report.Error (133, vi.Location,
3321 "The expression being assigned to `" +
3322 name + "' must be constant (" + e + ")");
3326 constants.Remove (name);
3327 constants.Add (name, e);
3332 // Now, handle the children
3334 if (children != null){
3335 foreach (Block b in children)
3336 b.EmitMeta (ec, toplevel);
3340 public void UsageWarning ()
3344 if (variables != null){
3345 foreach (DictionaryEntry de in variables){
3346 VariableInfo vi = (VariableInfo) de.Value;
3351 name = (string) de.Key;
3355 219, vi.Location, "The variable `" + name +
3356 "' is assigned but its value is never used");
3359 168, vi.Location, "The variable `" +
3361 "' is declared but never used");
3366 if (children != null)
3367 foreach (Block b in children)
3371 bool has_ret = false;
3373 public override bool Resolve (EmitContext ec)
3375 Block prev_block = ec.CurrentBlock;
3378 ec.CurrentBlock = this;
3380 if (!variables_initialized)
3381 UpdateVariableInfo (ec);
3383 ec.StartFlowBranching (this);
3385 Report.Debug (1, "RESOLVE BLOCK", StartLocation, ec.CurrentBranching);
3387 ArrayList new_statements = new ArrayList ();
3388 bool unreachable = false, warning_shown = false;
3390 foreach (Statement s in statements){
3391 if (unreachable && !(s is LabeledStatement)) {
3392 if (!warning_shown && !(s is EmptyStatement)) {
3393 warning_shown = true;
3394 Warning_DeadCodeFound (s.loc);
3399 if (s.Resolve (ec) == false) {
3404 if (s is LabeledStatement)
3405 unreachable = false;
3407 unreachable = ! ec.CurrentBranching.IsReachable ();
3409 new_statements.Add (s);
3412 statements = new_statements;
3414 Report.Debug (1, "RESOLVE BLOCK DONE", StartLocation, ec.CurrentBranching);
3416 FlowReturns returns = ec.EndFlowBranching ();
3417 ec.CurrentBlock = prev_block;
3419 // If we're a non-static `struct' constructor which doesn't have an
3420 // initializer, then we must initialize all of the struct's fields.
3421 if ((this_variable != null) && (returns != FlowReturns.EXCEPTION) &&
3422 !this_variable.IsAssigned (ec, loc))
3425 if ((labels != null) && (RootContext.WarningLevel >= 2)) {
3426 foreach (LabeledStatement label in labels.Values)
3427 if (!label.HasBeenReferenced)
3428 Report.Warning (164, label.Location,
3429 "This label has not been referenced");
3432 if ((returns == FlowReturns.ALWAYS) ||
3433 (returns == FlowReturns.EXCEPTION) ||
3434 (returns == FlowReturns.UNREACHABLE))
3440 protected override bool DoEmit (EmitContext ec)
3442 Block prev_block = ec.CurrentBlock;
3444 ec.CurrentBlock = this;
3446 ec.Mark (StartLocation);
3447 foreach (Statement s in statements)
3450 ec.Mark (EndLocation);
3452 ec.CurrentBlock = prev_block;
3457 public class StatementSequence : Expression {
3459 ArrayList args, originalArgs;
3461 bool isRetValRequired;
3462 bool isLeftHandSide;
3463 bool isIndexerAccess;
3465 Expression type_expr;
3467 public StatementSequence (Block parent, Location loc, Expression expr)
3468 : this (parent, loc, expr, null)
3471 public StatementSequence (Block parent, Location loc, Expression expr, string name,
3472 Expression type_expr, ArrayList a, bool isRetValRequired,
3473 bool isLeftHandSide)
3474 : this (parent, loc, expr, a)
3476 this.memberName = name;
3477 this.type_expr = type_expr;
3478 this.isRetValRequired = isRetValRequired;
3479 this.isLeftHandSide = isLeftHandSide;
3482 public StatementSequence (Block parent, Location loc, Expression expr, ArrayList a,
3483 bool isRetValRequired, bool isLeftHandSide)
3484 : this (parent, loc, expr, a)
3486 this.isRetValRequired = isRetValRequired;
3487 this.isLeftHandSide = isLeftHandSide;
3488 if (expr is MemberAccess) {
3489 this.expr = ((MemberAccess)expr).Expr;
3490 this.memberName = ((MemberAccess)expr).Identifier;
3491 this.isIndexerAccess = false;
3492 } else if (expr is IndexerAccess) {
3493 this.expr = ((IndexerAccess) expr).Instance;
3494 this.memberName = "";
3495 this.isIndexerAccess = true;
3499 public StatementSequence (Block parent, Location loc, Expression expr, ArrayList a)
3501 stmtBlock = new Block (parent);
3503 originalArgs = new ArrayList ();
3505 for (int index = 0; index < a.Count; index ++) {
3506 Argument argument = (Argument) args [index];
3507 originalArgs.Add (new Argument (argument.Expr, argument.ArgType));
3512 stmtBlock.IsLateBindingRequired = true;
3514 this.isRetValRequired = this.isLeftHandSide = false;
3515 this.memberName = "";
3516 this.type_expr = null;
3519 public ArrayList Arguments {
3528 public bool IsLeftHandSide {
3530 isLeftHandSide = value;
3534 public Block StmtBlock {
3540 public override Expression DoResolve (EmitContext ec)
3542 if (!stmtBlock.Resolve (ec))
3544 eclass = ExprClass.Value;
3545 type = TypeManager.object_type;
3549 public bool ResolveArguments (EmitContext ec) {
3551 bool argNamesFound = false;
3552 if (Arguments != null)
3554 for (int index = 0; index < Arguments.Count; index ++)
3556 Argument a = (Argument) Arguments [index];
3557 if (a.ParamName == null || a.ParamName == "") {
3558 if (argNamesFound) {
3559 Report.Error (30241, loc, "Named Argument expected");
3563 argNamesFound = true;
3564 if (a.ArgType == Argument.AType.NoArg)
3565 a = new Argument (Parser.DecomposeQI ("System.Reflection.Missing.Value", loc), Argument.AType.Expression);
3566 if (!a.Resolve (ec, loc))
3568 Arguments [index] = a;
3574 public void GenerateLateBindingStatements ()
3577 ArrayList arrayInitializers = new ArrayList ();
3578 ArrayList ArgumentNames = null;
3580 //arrayInitializers = new ArrayList ();
3581 argCount = args.Count;
3582 for (int index = 0; index < args.Count; index ++) {
3583 Argument a = (Argument) args [index];
3584 Expression argument = a.Expr;
3585 arrayInitializers.Add (argument);
3586 if (a.ParamName != null && a.ParamName != "") {
3587 if (ArgumentNames == null)
3588 ArgumentNames = new ArrayList ();
3589 ArgumentNames.Add (new StringLiteral (a.ParamName));
3594 // __LateBindingArgs = new Object () {arg1, arg2 ...}
3595 ArrayCreation new_expr = new ArrayCreation (Parser.DecomposeQI ("System.Object", loc), "[]", arrayInitializers, loc);
3596 Assign assign_stmt = null;
3598 LocalVariableReference v1 = new LocalVariableReference (stmtBlock, Block.lateBindingArgs, loc);
3599 assign_stmt = new Assign (v1, new_expr, loc);
3600 stmtBlock.AddStatement (new StatementExpression ((ExpressionStatement) assign_stmt, loc));
3601 // __LateBindingArgNames = new string () { argument names}
3602 LocalVariableReference v2 = null;
3603 if (ArgumentNames != null && ArgumentNames.Count > 0) {
3604 new_expr = new ArrayCreation (Parser.DecomposeQI ("System.String", loc), "[]", ArgumentNames, loc);
3605 v2 = new LocalVariableReference (stmtBlock, Block.lateBindingArgNames, loc);
3606 assign_stmt = new Assign (v2, new_expr, loc);
3607 stmtBlock.AddStatement (new StatementExpression ((ExpressionStatement) assign_stmt, loc));
3610 //string memName = "";
3611 //bool isIndexerAccess = true;
3613 ArrayList invocationArgs = new ArrayList ();
3614 if (isIndexerAccess || memberName == "") {
3615 invocationArgs.Add (new Argument (expr, Argument.AType.Expression));
3616 invocationArgs.Add (new Argument (v1, Argument.AType.Expression));
3617 invocationArgs.Add (new Argument (NullLiteral.Null, Argument.AType.Expression));
3618 Expression tmp = null;
3619 if (!isLeftHandSide)
3620 tmp = Parser.DecomposeQI ("Microsoft.VisualBasic.CompilerServices.LateBinding.LateIndexGet", loc);
3622 tmp = Parser.DecomposeQI ("Microsoft.VisualBasic.CompilerServices.LateBinding.LateIndexSet", loc);
3623 Invocation invStmt = new Invocation (tmp, invocationArgs, Location.Null);
3624 invStmt.IsLateBinding = true;
3625 stmtBlock.AddStatement (new StatementExpression ((ExpressionStatement) invStmt, loc));
3630 invocationArgs.Add (new Argument (expr, Argument.AType.Expression));
3632 invocationArgs.Add (new Argument (NullLiteral.Null, Argument.AType.Expression));
3633 if (type_expr != null)
3634 invocationArgs.Add (new Argument (type_expr, Argument.AType.Expression));
3636 invocationArgs.Add (new Argument (NullLiteral.Null, Argument.AType.Expression));
3637 invocationArgs.Add (new Argument (new StringLiteral (memberName), Argument.AType.Expression));
3638 invocationArgs.Add (new Argument (v1, Argument.AType.Expression));
3639 if (ArgumentNames != null && ArgumentNames.Count > 0)
3640 invocationArgs.Add (new Argument (v2, Argument.AType.Expression));
3642 invocationArgs.Add (new Argument (NullLiteral.Null, Argument.AType.Expression));
3644 // __LateBindingCopyBack = new Boolean (no_of_args) {}
3645 bool isCopyBackRequired = false;
3646 if (!isLeftHandSide) {
3647 for (int i = 0; i < argCount; i++) {
3648 Argument origArg = (Argument) Arguments [i];
3649 Expression origExpr = origArg.Expr;
3650 if (!(origExpr is Constant || origArg.ArgType == Argument.AType.NoArg))
3651 isCopyBackRequired = true;
3655 LocalVariableReference v3 = new LocalVariableReference (stmtBlock, Block.lateBindingCopyBack, loc);
3656 if (isCopyBackRequired) {
3657 ArrayList rank_specifier = new ArrayList ();
3658 rank_specifier.Add (new IntLiteral (argCount));
3659 arrayInitializers = new ArrayList ();
3660 for (int i = 0; i < argCount; i++) {
3661 Argument a = (Argument) Arguments [i];
3662 Expression origExpr = a.Expr;
3663 if (origExpr is Constant || a.ArgType == Argument.AType.NoArg || origExpr is New)
3664 arrayInitializers.Add (new BoolLiteral (false));
3666 arrayInitializers.Add (new BoolLiteral (true));
3669 new_expr = new ArrayCreation (Parser.DecomposeQI ("System.Boolean", loc), "[]", arrayInitializers, loc);
3670 assign_stmt = new Assign (v3, new_expr, loc);
3671 stmtBlock.AddStatement (new StatementExpression ((ExpressionStatement) assign_stmt, loc));
3672 invocationArgs.Add (new Argument (v3, Argument.AType.Expression));
3673 } else if (! isLeftHandSide) {
3674 invocationArgs.Add (new Argument (NullLiteral.Null, Argument.AType.Expression));
3677 Expression etmp = null;
3678 if (isLeftHandSide) {
3680 etmp = Parser.DecomposeQI ("Microsoft.VisualBasic.CompilerServices.LateBinding.LateSet", loc);
3681 } else if (isRetValRequired) {
3683 etmp = Parser.DecomposeQI ("Microsoft.VisualBasic.CompilerServices.LateBinding.LateGet", loc);
3685 etmp = Parser.DecomposeQI ("Microsoft.VisualBasic.CompilerServices.LateBinding.LateCall", loc);
3688 Invocation inv_stmt = new Invocation (etmp, invocationArgs, Location.Null);
3689 inv_stmt.IsLateBinding = true;
3690 stmtBlock.AddStatement (new StatementExpression ((ExpressionStatement) inv_stmt, loc));
3692 if (! isCopyBackRequired)
3695 for (int i = argCount - 1; i >= 0; i --) {
3696 Argument arg = (Argument) originalArgs [i];
3697 Expression origExpr = (Expression) arg.Expr;
3698 if (arg.ArgType == Argument.AType.NoArg)
3700 if (origExpr is Constant)
3702 if (origExpr is New)
3705 Expression intExpr = new IntLiteral (i);
3706 ArrayList argsLocal = new ArrayList ();
3707 argsLocal.Add (new Argument (intExpr, Argument.AType.Expression));
3708 Expression indexExpr = new Invocation (new SimpleName (Block.lateBindingCopyBack, loc), argsLocal, loc);
3709 Expression value = new Invocation (new SimpleName (Block.lateBindingArgs, loc), argsLocal, loc);
3710 assign_stmt = new Assign (origExpr, value, loc);
3711 Expression boolExpr = new Binary (Binary.Operator.Inequality, indexExpr, new BoolLiteral (false), loc);
3712 Statement ifStmt = new If (boolExpr, new StatementExpression ((ExpressionStatement) assign_stmt, loc), loc);
3713 stmtBlock.AddStatement (ifStmt);
3717 public override void Emit (EmitContext ec)
3719 stmtBlock.Emit (ec);
3723 public class SwitchLabel {
3724 public enum LabelType : byte {
3725 Operator, Range, Label, Else
3728 Expression label, start, end;
3729 LabelType label_type;
3730 Expression label_condition, start_condition, end_condition;
3731 Binary.Operator oper;
3732 public Location loc;
3733 public Label ILLabel;
3734 public Label ILLabelCode;
3737 // if expr == null, then it is the default case.
3739 public SwitchLabel (Expression start, Expression end, LabelType ltype, Binary.Operator oper, Location l) {
3742 this.label_type = ltype;
3745 label_condition = start_condition = end_condition = null;
3748 public SwitchLabel (Expression expr, LabelType ltype, Binary.Operator oper, Location l)
3752 label_condition = start_condition = end_condition = null;
3754 this.label_type = ltype;
3758 public Expression Label {
3764 public LabelType Type {
3770 public Expression ConditionStart {
3772 return start_condition;
3776 public Expression ConditionEnd {
3778 return end_condition;
3782 public Expression ConditionLabel {
3784 return label_condition;
3789 // Resolves the expression, reduces it to a literal if possible
3790 // and then converts it to the requested type.
3792 public bool ResolveAndReduce (EmitContext ec, Expression expr)
3794 ILLabel = ec.ig.DefineLabel ();
3795 ILLabelCode = ec.ig.DefineLabel ();
3797 Expression e = null;
3798 switch (label_type) {
3799 case LabelType.Label :
3802 e = label.Resolve (ec);
3804 e = Expression.ConvertImplicit (ec, e, expr.Type, loc);
3807 label_condition = new Binary (Binary.Operator.Equality, expr, e, loc);
3808 if ((label_condition = label_condition.DoResolve (ec)) == null)
3811 case LabelType.Operator :
3812 e = label.Resolve (ec);
3813 label_condition = new Binary (oper, expr, e, loc);
3814 if ((label_condition = label_condition.DoResolve (ec)) == null)
3817 case LabelType.Range :
3818 if (start == null || end == null)
3820 e = start.Resolve (ec);
3822 e = Expression.ConvertImplicit (ec, e, expr.Type, loc);
3825 start_condition = new Binary (Binary.Operator.GreaterThanOrEqual, expr, e, loc);
3826 start_condition = start_condition.Resolve (ec);
3827 e = end.Resolve (ec);
3829 e = Expression.ConvertImplicit (ec, e, expr.Type, loc);
3832 end_condition = new Binary (Binary.Operator.LessThanOrEqual, expr, e, loc);
3833 end_condition = end_condition.Resolve (ec);
3834 if (start_condition == null || end_condition == null)
3838 case LabelType.Else :
3845 public class SwitchSection {
3846 // An array of SwitchLabels.
3847 public readonly ArrayList Labels;
3848 public readonly Block Block;
3850 public SwitchSection (ArrayList labels, Block block)
3857 public class Switch : Statement {
3858 public readonly ArrayList Sections;
3859 public Expression Expr;
3862 /// Maps constants whose type type SwitchType to their SwitchLabels.
3864 public Hashtable Elements;
3867 /// The governing switch type
3869 public Type SwitchType;
3875 Label default_target;
3876 Expression new_expr;
3879 // The types allowed to be implicitly cast from
3880 // on the governing type
3882 //static Type [] allowed_types;
3884 public Switch (Expression e, ArrayList sects, Location l)
3891 public bool GotDefault {
3897 public Label DefaultTarget {
3899 return default_target;
3904 // Determines the governing type for a switch. The returned
3905 // expression might be the expression from the switch, or an
3906 // expression that includes any potential conversions to the
3907 // integral types or to string.
3909 Expression SwitchGoverningType (EmitContext ec, Type t)
3911 if (t == TypeManager.byte_type ||
3912 t == TypeManager.short_type ||
3913 t == TypeManager.int32_type ||
3914 t == TypeManager.int64_type ||
3915 t == TypeManager.decimal_type ||
3916 t == TypeManager.float_type ||
3917 t == TypeManager.double_type ||
3918 t == TypeManager.date_type ||
3919 t == TypeManager.char_type ||
3920 t == TypeManager.object_type ||
3921 t == TypeManager.string_type ||
3922 t == TypeManager.bool_type ||
3923 t.IsSubclassOf (TypeManager.enum_type))
3926 if (allowed_types == null){
3927 allowed_types = new Type [] {
3928 TypeManager.sbyte_type,
3929 TypeManager.byte_type,
3930 TypeManager.short_type,
3931 TypeManager.ushort_type,
3932 TypeManager.int32_type,
3933 TypeManager.uint32_type,
3934 TypeManager.int64_type,
3935 TypeManager.uint64_type,
3936 TypeManager.char_type,
3937 TypeManager.bool_type,
3938 TypeManager.string_type
3943 // Try to find a *user* defined implicit conversion.
3945 // If there is no implicit conversion, or if there are multiple
3946 // conversions, we have to report an error
3948 Expression converted = null;
3949 foreach (Type tt in allowed_types){
3952 e = Expression.ImplicitUserConversion (ec, Expr, tt, loc);
3956 if (converted != null){
3957 Report.Error (-12, loc, "More than one conversion to an integral " +
3958 " type exists for type `" +
3959 TypeManager.MonoBASIC_Name (Expr.Type)+"'");
3969 void error152 (string n)
3972 152, "The label `" + n + ":' " +
3973 "is already present on this switch statement");
3977 // Performs the basic sanity checks on the switch statement
3978 // (looks for duplicate keys and non-constant expressions).
3980 // It also returns a hashtable with the keys that we will later
3981 // use to compute the switch tables
3983 bool CheckSwitch (EmitContext ec)
3987 Elements = new CaseInsensitiveHashtable ();
3989 got_default = false;
3991 if (TypeManager.IsEnumType (SwitchType)){
3992 compare_type = TypeManager.EnumToUnderlying (SwitchType);
3994 compare_type = SwitchType;
3996 for (int secIndex = 0; secIndex < Sections.Count; secIndex ++) {
3997 SwitchSection ss = (SwitchSection) Sections [secIndex];
3998 for (int labelIndex = 0; labelIndex < ss.Labels.Count; labelIndex ++) {
3999 SwitchLabel sl = (SwitchLabel) ss.Labels [labelIndex];
4000 if (!sl.ResolveAndReduce (ec, Expr)){
4005 if (sl.Type == SwitchLabel.LabelType.Else){
4007 error152 ("default");
4021 void EmitObjectInteger (ILGenerator ig, object k)
4024 IntConstant.EmitInt (ig, (int) k);
4025 else if (k is Constant) {
4026 EmitObjectInteger (ig, ((Constant) k).GetValue ());
4029 IntConstant.EmitInt (ig, unchecked ((int) (uint) k));
4032 if ((long) k >= int.MinValue && (long) k <= int.MaxValue)
4034 IntConstant.EmitInt (ig, (int) (long) k);
4035 ig.Emit (OpCodes.Conv_I8);
4038 LongConstant.EmitLong (ig, (long) k);
4040 else if (k is ulong)
4042 if ((ulong) k < (1L<<32))
4044 IntConstant.EmitInt (ig, (int) (long) k);
4045 ig.Emit (OpCodes.Conv_U8);
4049 LongConstant.EmitLong (ig, unchecked ((long) (ulong) k));
4053 IntConstant.EmitInt (ig, (int) ((char) k));
4054 else if (k is sbyte)
4055 IntConstant.EmitInt (ig, (int) ((sbyte) k));
4057 IntConstant.EmitInt (ig, (int) ((byte) k));
4058 else if (k is short)
4059 IntConstant.EmitInt (ig, (int) ((short) k));
4060 else if (k is ushort)
4061 IntConstant.EmitInt (ig, (int) ((ushort) k));
4063 IntConstant.EmitInt (ig, ((bool) k) ? 1 : 0);
4065 throw new Exception ("Unhandled case");
4068 // structure used to hold blocks of keys while calculating table switch
4069 class KeyBlock : IComparable
4071 public KeyBlock (long _nFirst)
4073 nFirst = nLast = _nFirst;
4077 public ArrayList rgKeys = null;
4080 get { return (int) (nLast - nFirst + 1); }
4082 public static long TotalLength (KeyBlock kbFirst, KeyBlock kbLast)
4084 return kbLast.nLast - kbFirst.nFirst + 1;
4086 public int CompareTo (object obj)
4088 KeyBlock kb = (KeyBlock) obj;
4089 int nLength = Length;
4090 int nLengthOther = kb.Length;
4091 if (nLengthOther == nLength)
4092 return (int) (kb.nFirst - nFirst);
4093 return nLength - nLengthOther;
4099 /// This method emits code for a lookup-based switch statement (non-string)
4100 /// Basically it groups the cases into blocks that are at least half full,
4101 /// and then spits out individual lookup opcodes for each block.
4102 /// It emits the longest blocks first, and short blocks are just
4103 /// handled with direct compares.
4105 /// <param name="ec"></param>
4106 /// <param name="val"></param>
4107 /// <returns></returns>
4108 bool TableSwitchEmit (EmitContext ec, LocalBuilder val)
4110 int cElements = Elements.Count;
4111 object [] rgKeys = new object [cElements];
4112 Elements.Keys.CopyTo (rgKeys, 0);
4113 Array.Sort (rgKeys);
4115 // initialize the block list with one element per key
4116 ArrayList rgKeyBlocks = new ArrayList ();
4117 foreach (object key in rgKeys)
4118 rgKeyBlocks.Add (new KeyBlock (Convert.ToInt64 (key)));
4121 // iteratively merge the blocks while they are at least half full
4122 // there's probably a really cool way to do this with a tree...
4123 while (rgKeyBlocks.Count > 1)
4125 ArrayList rgKeyBlocksNew = new ArrayList ();
4126 kbCurr = (KeyBlock) rgKeyBlocks [0];
4127 for (int ikb = 1; ikb < rgKeyBlocks.Count; ikb++)
4129 KeyBlock kb = (KeyBlock) rgKeyBlocks [ikb];
4130 if ((kbCurr.Length + kb.Length) * 2 >= KeyBlock.TotalLength (kbCurr, kb))
4133 kbCurr.nLast = kb.nLast;
4137 // start a new block
4138 rgKeyBlocksNew.Add (kbCurr);
4142 rgKeyBlocksNew.Add (kbCurr);
4143 if (rgKeyBlocks.Count == rgKeyBlocksNew.Count)
4145 rgKeyBlocks = rgKeyBlocksNew;
4148 // initialize the key lists
4149 foreach (KeyBlock kb in rgKeyBlocks)
4150 kb.rgKeys = new ArrayList ();
4152 // fill the key lists
4154 if (rgKeyBlocks.Count > 0) {
4155 kbCurr = (KeyBlock) rgKeyBlocks [0];
4156 foreach (object key in rgKeys)
4158 bool fNextBlock = (key is UInt64) ? (ulong) key > (ulong) kbCurr.nLast : Convert.ToInt64 (key) > kbCurr.nLast;
4160 kbCurr = (KeyBlock) rgKeyBlocks [++iBlockCurr];
4161 kbCurr.rgKeys.Add (key);
4165 // sort the blocks so we can tackle the largest ones first
4166 rgKeyBlocks.Sort ();
4168 // okay now we can start...
4169 ILGenerator ig = ec.ig;
4170 Label lblEnd = ig.DefineLabel (); // at the end ;-)
4171 Label lblDefault = ig.DefineLabel ();
4173 Type typeKeys = null;
4174 if (rgKeys.Length > 0)
4175 typeKeys = rgKeys [0].GetType (); // used for conversions
4177 for (int iBlock = rgKeyBlocks.Count - 1; iBlock >= 0; --iBlock)
4179 KeyBlock kb = ((KeyBlock) rgKeyBlocks [iBlock]);
4180 lblDefault = (iBlock == 0) ? DefaultTarget : ig.DefineLabel ();
4183 foreach (object key in kb.rgKeys)
4185 ig.Emit (OpCodes.Ldloc, val);
4186 EmitObjectInteger (ig, key);
4187 SwitchLabel sl = (SwitchLabel) Elements [key];
4188 ig.Emit (OpCodes.Beq, sl.ILLabel);
4193 // TODO: if all the keys in the block are the same and there are
4194 // no gaps/defaults then just use a range-check.
4195 if (SwitchType == TypeManager.int64_type ||
4196 SwitchType == TypeManager.uint64_type)
4198 // TODO: optimize constant/I4 cases
4200 // check block range (could be > 2^31)
4201 ig.Emit (OpCodes.Ldloc, val);
4202 EmitObjectInteger (ig, Convert.ChangeType (kb.nFirst, typeKeys));
4203 ig.Emit (OpCodes.Blt, lblDefault);
4204 ig.Emit (OpCodes.Ldloc, val);
4205 EmitObjectInteger (ig, Convert.ChangeType (kb.nFirst, typeKeys));
4206 ig.Emit (OpCodes.Bgt, lblDefault);
4209 ig.Emit (OpCodes.Ldloc, val);
4212 EmitObjectInteger (ig, Convert.ChangeType (kb.nFirst, typeKeys));
4213 ig.Emit (OpCodes.Sub);
4215 ig.Emit (OpCodes.Conv_I4); // assumes < 2^31 labels!
4220 ig.Emit (OpCodes.Ldloc, val);
4221 int nFirst = (int) kb.nFirst;
4224 IntConstant.EmitInt (ig, nFirst);
4225 ig.Emit (OpCodes.Sub);
4227 else if (nFirst < 0)
4229 IntConstant.EmitInt (ig, -nFirst);
4230 ig.Emit (OpCodes.Add);
4234 // first, build the list of labels for the switch
4236 int cJumps = kb.Length;
4237 Label [] rgLabels = new Label [cJumps];
4238 for (int iJump = 0; iJump < cJumps; iJump++)
4240 object key = kb.rgKeys [iKey];
4241 if (Convert.ToInt64 (key) == kb.nFirst + iJump)
4243 SwitchLabel sl = (SwitchLabel) Elements [key];
4244 rgLabels [iJump] = sl.ILLabel;
4248 rgLabels [iJump] = lblDefault;
4250 // emit the switch opcode
4251 ig.Emit (OpCodes.Switch, rgLabels);
4254 // mark the default for this block
4256 ig.MarkLabel (lblDefault);
4259 // TODO: find the default case and emit it here,
4260 // to prevent having to do the following jump.
4261 // make sure to mark other labels in the default section
4263 // the last default just goes to the end
4264 ig.Emit (OpCodes.Br, lblDefault);
4266 // now emit the code for the sections
4267 bool fFoundDefault = false;
4268 bool fAllReturn = true;
4269 foreach (SwitchSection ss in Sections)
4271 foreach (SwitchLabel sl in ss.Labels)
4273 ig.MarkLabel (sl.ILLabel);
4274 ig.MarkLabel (sl.ILLabelCode);
4275 if (sl.Label == null)
4277 ig.MarkLabel (lblDefault);
4278 fFoundDefault = true;
4281 bool returns = ss.Block.Emit (ec);
4282 fAllReturn &= returns;
4283 //ig.Emit (OpCodes.Br, lblEnd);
4286 if (!fFoundDefault) {
4287 ig.MarkLabel (lblDefault);
4290 ig.MarkLabel (lblEnd);
4295 // This simple emit switch works, but does not take advantage of the
4297 // TODO: remove non-string logic from here
4298 // TODO: binary search strings?
4300 bool SimpleSwitchEmit (EmitContext ec, LocalBuilder val)
4302 ILGenerator ig = ec.ig;
4303 Label end_of_switch = ig.DefineLabel ();
4304 Label next_test = ig.DefineLabel ();
4305 Label null_target = ig.DefineLabel ();
4306 bool default_found = false;
4307 bool first_test = true;
4308 bool pending_goto_end = false;
4309 bool all_return = true;
4310 bool is_string = false;
4314 // Special processing for strings: we cant compare
4317 if (SwitchType == TypeManager.string_type){
4318 ig.Emit (OpCodes.Ldloc, val);
4321 if (Elements.Contains (NullLiteral.Null)){
4322 ig.Emit (OpCodes.Brfalse, null_target);
4324 ig.Emit (OpCodes.Brfalse, default_target);
4326 ig.Emit (OpCodes.Ldloc, val);
4327 ig.Emit (OpCodes.Call, TypeManager.string_isinterneted_string);
4328 ig.Emit (OpCodes.Stloc, val);
4331 foreach (SwitchSection ss in Sections){
4332 Label sec_begin = ig.DefineLabel ();
4334 if (pending_goto_end)
4335 ig.Emit (OpCodes.Br, end_of_switch);
4337 int label_count = ss.Labels.Count;
4339 foreach (SwitchLabel sl in ss.Labels){
4340 ig.MarkLabel (sl.ILLabel);
4343 ig.MarkLabel (next_test);
4344 next_test = ig.DefineLabel ();
4347 // If we are the default target
4349 if (sl.Label == null){
4350 ig.MarkLabel (default_target);
4351 default_found = true;
4353 object lit = sl.Converted;
4355 if (lit is NullLiteral){
4357 if (label_count == 1)
4358 ig.Emit (OpCodes.Br, next_test);
4363 StringConstant str = (StringConstant) lit;
4365 ig.Emit (OpCodes.Ldloc, val);
4366 ig.Emit (OpCodes.Ldstr, str.Value);
4367 if (label_count == 1)
4368 ig.Emit (OpCodes.Bne_Un, next_test);
4370 ig.Emit (OpCodes.Beq, sec_begin);
4372 ig.Emit (OpCodes.Ldloc, val);
4373 EmitObjectInteger (ig, lit);
4374 ig.Emit (OpCodes.Ceq);
4375 if (label_count == 1)
4376 ig.Emit (OpCodes.Brfalse, next_test);
4378 ig.Emit (OpCodes.Brtrue, sec_begin);
4382 if (label_count != 1)
4383 ig.Emit (OpCodes.Br, next_test);
4386 ig.MarkLabel (null_target);
4387 ig.MarkLabel (sec_begin);
4388 foreach (SwitchLabel sl in ss.Labels)
4389 ig.MarkLabel (sl.ILLabelCode);
4391 bool returns = ss.Block.Emit (ec);
4393 pending_goto_end = false;
4396 pending_goto_end = true;
4400 if (!default_found){
4401 ig.MarkLabel (default_target);
4404 ig.MarkLabel (next_test);
4405 ig.MarkLabel (end_of_switch);
4411 public override bool Resolve (EmitContext ec)
4413 Expr = Expr.Resolve (ec);
4417 new_expr = SwitchGoverningType (ec, Expr.Type);
4418 if (new_expr == null){
4419 Report.Error (30338, loc, "'Select' expression cannot be of type '" + Expr.Type +"'");
4424 SwitchType = new_expr.Type;
4426 if (!CheckSwitch (ec))
4429 Switch old_switch = ec.Switch;
4431 ec.Switch.SwitchType = SwitchType;
4433 ec.StartFlowBranching (FlowBranchingType.SWITCH, loc);
4436 foreach (SwitchSection ss in Sections){
4438 ec.CurrentBranching.CreateSibling ();
4442 if (ss.Block.Resolve (ec) != true)
4448 ec.CurrentBranching.CreateSibling ();
4450 ec.EndFlowBranching ();
4451 ec.Switch = old_switch;
4456 protected override bool DoEmit (EmitContext ec)
4458 ILGenerator ig = ec.ig;
4460 // Setup the codegen context
4462 Label old_end = ec.LoopEnd;
4463 Switch old_switch = ec.Switch;
4465 ec.LoopEnd = ig.DefineLabel ();
4468 for (int secIndex = 0; secIndex < Sections.Count; secIndex ++) {
4469 SwitchSection section = (SwitchSection) Sections [secIndex];
4470 Label sLabel = ig.DefineLabel ();
4471 Label lLabel = ig.DefineLabel ();
4472 ArrayList Labels = section.Labels;
4473 for (int labelIndex = 0; labelIndex < Labels.Count; labelIndex ++) {
4474 SwitchLabel sl = (SwitchLabel) Labels [labelIndex];
4476 case SwitchLabel.LabelType.Range :
4477 if (labelIndex + 1 == Labels.Count) {
4478 EmitBoolExpression (ec, sl.ConditionStart, sLabel, false);
4479 EmitBoolExpression (ec, sl.ConditionEnd, sLabel, false);
4480 ig.Emit (OpCodes.Br, lLabel);
4482 Label newLabel = ig.DefineLabel ();
4483 EmitBoolExpression (ec, sl.ConditionStart, newLabel, false);
4484 EmitBoolExpression (ec, sl.ConditionEnd, newLabel, false);
4485 ig.Emit (OpCodes.Br, lLabel);
4486 ig.MarkLabel (newLabel);
4489 case SwitchLabel.LabelType.Else :
4490 // Nothing to be done here
4492 case SwitchLabel.LabelType.Operator :
4493 EmitBoolExpression (ec, sl.ConditionLabel, lLabel, true);
4494 if (labelIndex + 1 == Labels.Count)
4495 ig.Emit (OpCodes.Br, sLabel);
4497 case SwitchLabel.LabelType.Label :
4498 EmitBoolExpression (ec, sl.ConditionLabel, lLabel, true);
4499 if (labelIndex + 1 == Labels.Count)
4500 ig.Emit (OpCodes.Br, sLabel);
4505 ig.MarkLabel (lLabel);
4506 section.Block.Emit (ec);
4507 ig.MarkLabel (sLabel);
4510 // Restore context state.
4511 ig.MarkLabel (ec.LoopEnd);
4514 // Restore the previous context
4516 ec.LoopEnd = old_end;
4517 ec.Switch = old_switch;
4522 public class Lock : Statement {
4524 Statement Statement;
4526 public Lock (Expression expr, Statement stmt, Location l)
4533 public override bool Resolve (EmitContext ec)
4535 expr = expr.Resolve (ec);
4536 return Statement.Resolve (ec) && expr != null;
4539 protected override bool DoEmit (EmitContext ec)
4541 Type type = expr.Type;
4544 if (type.IsValueType){
4545 Report.Error (30582, loc, "lock statement requires the expression to be " +
4546 " a reference type (type is: `" +
4547 TypeManager.MonoBASIC_Name (type) + "'");
4551 ILGenerator ig = ec.ig;
4552 LocalBuilder temp = ig.DeclareLocal (type);
4555 ig.Emit (OpCodes.Dup);
4556 ig.Emit (OpCodes.Stloc, temp);
4557 ig.Emit (OpCodes.Call, TypeManager.void_monitor_enter_object);
4560 ig.BeginExceptionBlock ();
4561 bool old_in_try = ec.InTry;
4563 Label finish = ig.DefineLabel ();
4564 val = Statement.Emit (ec);
4565 ec.InTry = old_in_try;
4566 // ig.Emit (OpCodes.Leave, finish);
4568 ig.MarkLabel (finish);
4571 ig.BeginFinallyBlock ();
4572 ig.Emit (OpCodes.Ldloc, temp);
4573 ig.Emit (OpCodes.Call, TypeManager.void_monitor_exit_object);
4574 ig.EndExceptionBlock ();
4580 public class Unchecked : Statement {
4581 public readonly Block Block;
4583 public Unchecked (Block b)
4588 public override bool Resolve (EmitContext ec)
4590 return Block.Resolve (ec);
4593 protected override bool DoEmit (EmitContext ec)
4595 bool previous_state = ec.CheckState;
4596 bool previous_state_const = ec.ConstantCheckState;
4599 ec.CheckState = false;
4600 ec.ConstantCheckState = false;
4601 val = Block.Emit (ec);
4602 ec.CheckState = previous_state;
4603 ec.ConstantCheckState = previous_state_const;
4609 public class Checked : Statement {
4610 public readonly Block Block;
4612 public Checked (Block b)
4617 public override bool Resolve (EmitContext ec)
4619 bool previous_state = ec.CheckState;
4620 bool previous_state_const = ec.ConstantCheckState;
4622 ec.CheckState = true;
4623 ec.ConstantCheckState = true;
4624 bool ret = Block.Resolve (ec);
4625 ec.CheckState = previous_state;
4626 ec.ConstantCheckState = previous_state_const;
4631 protected override bool DoEmit (EmitContext ec)
4633 bool previous_state = ec.CheckState;
4634 bool previous_state_const = ec.ConstantCheckState;
4637 ec.CheckState = true;
4638 ec.ConstantCheckState = true;
4639 val = Block.Emit (ec);
4640 ec.CheckState = previous_state;
4641 ec.ConstantCheckState = previous_state_const;
4647 public class Unsafe : Statement {
4648 public readonly Block Block;
4650 public Unsafe (Block b)
4655 public override bool Resolve (EmitContext ec)
4657 bool previous_state = ec.InUnsafe;
4661 val = Block.Resolve (ec);
4662 ec.InUnsafe = previous_state;
4667 protected override bool DoEmit (EmitContext ec)
4669 bool previous_state = ec.InUnsafe;
4673 val = Block.Emit (ec);
4674 ec.InUnsafe = previous_state;
4683 public class Fixed : Statement {
4685 ArrayList declarators;
4686 Statement statement;
4691 public bool is_object;
4692 public VariableInfo vi;
4693 public Expression expr;
4694 public Expression converted;
4697 public Fixed (Expression type, ArrayList decls, Statement stmt, Location l)
4700 declarators = decls;
4705 public override bool Resolve (EmitContext ec)
4707 expr_type = ec.DeclSpace.ResolveType (type, false, loc);
4708 if (expr_type == null)
4711 data = new FixedData [declarators.Count];
4714 foreach (Pair p in declarators){
4715 VariableInfo vi = (VariableInfo) p.First;
4716 Expression e = (Expression) p.Second;
4721 // The rules for the possible declarators are pretty wise,
4722 // but the production on the grammar is more concise.
4724 // So we have to enforce these rules here.
4726 // We do not resolve before doing the case 1 test,
4727 // because the grammar is explicit in that the token &
4728 // is present, so we need to test for this particular case.
4732 // Case 1: & object.
4734 if (e is Unary && ((Unary) e).Oper == Unary.Operator.AddressOf){
4735 Expression child = ((Unary) e).Expr;
4738 if (child is ParameterReference || child is LocalVariableReference){
4741 "No need to use fixed statement for parameters or " +
4742 "local variable declarations (address is already " +
4751 child = ((Unary) e).Expr;
4753 if (!TypeManager.VerifyUnManaged (child.Type, loc))
4756 data [i].is_object = true;
4758 data [i].converted = null;
4772 if (e.Type.IsArray){
4773 Type array_type = e.Type.GetElementType ();
4777 // Provided that array_type is unmanaged,
4779 if (!TypeManager.VerifyUnManaged (array_type, loc))
4783 // and T* is implicitly convertible to the
4784 // pointer type given in the fixed statement.
4786 ArrayPtr array_ptr = new ArrayPtr (e, loc);
4788 Expression converted = Expression.ConvertImplicitRequired (
4789 ec, array_ptr, vi.VariableType, loc);
4790 if (converted == null)
4793 data [i].is_object = false;
4795 data [i].converted = converted;
4805 if (e.Type == TypeManager.string_type){
4806 data [i].is_object = false;
4808 data [i].converted = null;
4814 return statement.Resolve (ec);
4817 protected override bool DoEmit (EmitContext ec)
4819 ILGenerator ig = ec.ig;
4821 bool is_ret = false;
4823 for (int i = 0; i < data.Length; i++) {
4824 VariableInfo vi = data [i].vi;
4827 // Case 1: & object.
4829 if (data [i].is_object) {
4831 // Store pointer in pinned location
4833 data [i].expr.Emit (ec);
4834 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
4836 is_ret = statement.Emit (ec);
4838 // Clear the pinned variable.
4839 ig.Emit (OpCodes.Ldc_I4_0);
4840 ig.Emit (OpCodes.Conv_U);
4841 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
4849 if (data [i].expr.Type.IsArray){
4851 // Store pointer in pinned location
4853 data [i].converted.Emit (ec);
4855 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
4857 is_ret = statement.Emit (ec);
4859 // Clear the pinned variable.
4860 ig.Emit (OpCodes.Ldc_I4_0);
4861 ig.Emit (OpCodes.Conv_U);
4862 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
4870 if (data [i].expr.Type == TypeManager.string_type){
4871 LocalBuilder pinned_string = ig.DeclareLocal (TypeManager.string_type);
4872 TypeManager.MakePinned (pinned_string);
4874 data [i].expr.Emit (ec);
4875 ig.Emit (OpCodes.Stloc, pinned_string);
4877 Expression sptr = new StringPtr (pinned_string, loc);
4878 Expression converted = Expression.ConvertImplicitRequired (
4879 ec, sptr, vi.VariableType, loc);
4881 if (converted == null)
4884 converted.Emit (ec);
4885 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
4887 is_ret = statement.Emit (ec);
4889 // Clear the pinned variable
4890 ig.Emit (OpCodes.Ldnull);
4891 ig.Emit (OpCodes.Stloc, pinned_string);
4899 public class Catch {
4900 public readonly string Name;
4901 public readonly Block Block;
4902 public Expression Clause;
4903 public readonly Location Location;
4905 Expression type_expr;
4906 //Expression clus_expr;
4909 public Catch (Expression type, string name, Block block, Expression clause, Location l)
4918 public Type CatchType {
4924 public bool IsGeneral {
4926 return type_expr == null;
4930 public bool Resolve (EmitContext ec)
4932 if (type_expr != null) {
4933 type = ec.DeclSpace.ResolveType (type_expr, false, Location);
4937 if (type != TypeManager.exception_type && !type.IsSubclassOf (TypeManager.exception_type)){
4938 Report.Error (30665, Location,
4939 "The type caught or thrown must be derived " +
4940 "from System.Exception");
4946 if (Clause != null) {
4947 Clause = Statement.ResolveBoolean (ec, Clause, Location);
4948 if (Clause == null) {
4953 if (!Block.Resolve (ec))
4960 public class Try : Statement {
4961 public readonly Block Fini, Block;
4962 public readonly ArrayList Specific;
4963 public readonly Catch General;
4966 // specific, general and fini might all be null.
4968 public Try (Block block, ArrayList specific, Catch general, Block fini, Location l)
4970 if (specific == null && general == null){
4971 Console.WriteLine ("CIR.Try: Either specific or general have to be non-null");
4975 this.Specific = specific;
4976 this.General = general;
4981 public override bool Resolve (EmitContext ec)
4985 ec.StartFlowBranching (FlowBranchingType.EXCEPTION, Block.StartLocation);
4987 Report.Debug (1, "START OF TRY BLOCK", Block.StartLocation);
4989 bool old_in_try = ec.InTry;
4992 if (!Block.Resolve (ec))
4995 ec.InTry = old_in_try;
4997 FlowBranching.UsageVector vector = ec.CurrentBranching.CurrentUsageVector;
4999 Report.Debug (1, "START OF CATCH BLOCKS", vector);
5001 foreach (Catch c in Specific){
5002 ec.CurrentBranching.CreateSibling ();
5003 Report.Debug (1, "STARTED SIBLING FOR CATCH", ec.CurrentBranching);
5005 if (c.Name != null) {
5006 VariableInfo vi = c.Block.GetVariableInfo (c.Name);
5008 throw new Exception ();
5013 bool old_in_catch = ec.InCatch;
5016 if (!c.Resolve (ec))
5019 ec.InCatch = old_in_catch;
5021 FlowBranching.UsageVector current = ec.CurrentBranching.CurrentUsageVector;
5023 if (!current.AlwaysReturns && !current.AlwaysBreaks)
5024 vector.AndLocals (current);
5027 Report.Debug (1, "END OF CATCH BLOCKS", ec.CurrentBranching);
5029 if (General != null){
5030 ec.CurrentBranching.CreateSibling ();
5031 Report.Debug (1, "STARTED SIBLING FOR GENERAL", ec.CurrentBranching);
5033 bool old_in_catch = ec.InCatch;
5036 if (!General.Resolve (ec))
5039 ec.InCatch = old_in_catch;
5041 FlowBranching.UsageVector current = ec.CurrentBranching.CurrentUsageVector;
5043 if (!current.AlwaysReturns && !current.AlwaysBreaks)
5044 vector.AndLocals (current);
5047 Report.Debug (1, "END OF GENERAL CATCH BLOCKS", ec.CurrentBranching);
5050 ec.CurrentBranching.CreateSiblingForFinally ();
5051 Report.Debug (1, "STARTED SIBLING FOR FINALLY", ec.CurrentBranching, vector);
5053 bool old_in_finally = ec.InFinally;
5054 ec.InFinally = true;
5056 if (!Fini.Resolve (ec))
5059 ec.InFinally = old_in_finally;
5062 FlowReturns returns = ec.EndFlowBranching ();
5064 FlowBranching.UsageVector f_vector = ec.CurrentBranching.CurrentUsageVector;
5066 Report.Debug (1, "END OF FINALLY", ec.CurrentBranching, returns, vector, f_vector);
5067 ec.CurrentBranching.CurrentUsageVector.Or (vector);
5069 Report.Debug (1, "END OF TRY", ec.CurrentBranching);
5074 protected override bool DoEmit (EmitContext ec)
5076 ILGenerator ig = ec.ig;
5077 Label finish = ig.DefineLabel ();;
5081 ig.BeginExceptionBlock ();
5082 bool old_in_try = ec.InTry;
5084 returns = Block.Emit (ec);
5085 ec.InTry = old_in_try;
5088 // System.Reflection.Emit provides this automatically:
5089 // ig.Emit (OpCodes.Leave, finish);
5091 bool old_in_catch = ec.InCatch;
5093 //DeclSpace ds = ec.DeclSpace;
5095 foreach (Catch c in Specific){
5098 ig.BeginCatchBlock (c.CatchType);
5100 if (c.Name != null){
5101 vi = c.Block.GetVariableInfo (c.Name);
5103 throw new Exception ("Variable does not exist in this block");
5105 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
5107 ig.Emit (OpCodes.Pop);
5110 // if when clause is there
5112 if (c.Clause != null) {
5113 if (c.Clause is BoolConstant) {
5114 bool take = ((BoolConstant) c.Clause).Value;
5117 if (!c.Block.Emit (ec))
5120 EmitBoolExpression (ec, c.Clause, finish, false);
5121 if (!c.Block.Emit (ec))
5125 if (!c.Block.Emit (ec))
5129 if (General != null){
5130 ig.BeginCatchBlock (TypeManager.object_type);
5131 ig.Emit (OpCodes.Pop);
5133 if (General.Clause != null) {
5134 if (General.Clause is BoolConstant) {
5135 bool take = ((BoolConstant) General.Clause).Value;
5137 if (!General.Block.Emit (ec))
5140 EmitBoolExpression (ec, General.Clause, finish, false);
5141 if (!General.Block.Emit (ec))
5145 if (!General.Block.Emit (ec))
5149 ec.InCatch = old_in_catch;
5151 ig.MarkLabel (finish);
5153 ig.BeginFinallyBlock ();
5154 bool old_in_finally = ec.InFinally;
5155 ec.InFinally = true;
5157 ec.InFinally = old_in_finally;
5160 ig.EndExceptionBlock ();
5163 if (!returns || ec.InTry || ec.InCatch)
5166 // Unfortunately, System.Reflection.Emit automatically emits a leave
5167 // to the end of the finally block. This is a problem if `returns'
5168 // is true since we may jump to a point after the end of the method.
5169 // As a workaround, emit an explicit ret here.
5171 if (ec.ReturnType != null)
5172 ec.ig.Emit (OpCodes.Ldloc, ec.TemporaryReturn ());
5173 ec.ig.Emit (OpCodes.Ret);
5179 public class Using : Statement {
5180 object expression_or_block;
5181 Statement Statement;
5186 Expression [] converted_vars;
5187 ExpressionStatement [] assign;
5189 public Using (object expression_or_block, Statement stmt, Location l)
5191 this.expression_or_block = expression_or_block;
5197 // Resolves for the case of using using a local variable declaration.
5199 bool ResolveLocalVariableDecls (EmitContext ec)
5201 bool need_conv = false;
5202 expr_type = ec.DeclSpace.ResolveType (expr, false, loc);
5205 if (expr_type == null)
5209 // The type must be an IDisposable or an implicit conversion
5212 converted_vars = new Expression [var_list.Count];
5213 assign = new ExpressionStatement [var_list.Count];
5214 if (!TypeManager.ImplementsInterface (expr_type, TypeManager.idisposable_type)){
5215 foreach (DictionaryEntry e in var_list){
5216 Expression var = (Expression) e.Key;
5218 var = var.ResolveLValue (ec, new EmptyExpression ());
5222 converted_vars [i] = Expression.ConvertImplicitRequired (
5223 ec, var, TypeManager.idisposable_type, loc);
5225 if (converted_vars [i] == null)
5233 foreach (DictionaryEntry e in var_list){
5234 LocalVariableReference var = (LocalVariableReference) e.Key;
5235 Expression new_expr = (Expression) e.Value;
5238 a = new Assign (var, new_expr, loc);
5244 converted_vars [i] = var;
5245 assign [i] = (ExpressionStatement) a;
5252 bool ResolveExpression (EmitContext ec)
5254 if (!TypeManager.ImplementsInterface (expr_type, TypeManager.idisposable_type)){
5255 conv = Expression.ConvertImplicitRequired (
5256 ec, expr, TypeManager.idisposable_type, loc);
5266 // Emits the code for the case of using using a local variable declaration.
5268 bool EmitLocalVariableDecls (EmitContext ec)
5270 ILGenerator ig = ec.ig;
5273 bool old_in_try = ec.InTry;
5275 for (i = 0; i < assign.Length; i++) {
5276 assign [i].EmitStatement (ec);
5278 ig.BeginExceptionBlock ();
5280 Statement.Emit (ec);
5281 ec.InTry = old_in_try;
5283 bool old_in_finally = ec.InFinally;
5284 ec.InFinally = true;
5285 var_list.Reverse ();
5286 foreach (DictionaryEntry e in var_list){
5287 LocalVariableReference var = (LocalVariableReference) e.Key;
5288 Label skip = ig.DefineLabel ();
5291 ig.BeginFinallyBlock ();
5294 ig.Emit (OpCodes.Brfalse, skip);
5295 converted_vars [i].Emit (ec);
5296 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
5297 ig.MarkLabel (skip);
5298 ig.EndExceptionBlock ();
5300 ec.InFinally = old_in_finally;
5305 bool EmitExpression (EmitContext ec)
5308 // Make a copy of the expression and operate on that.
5310 ILGenerator ig = ec.ig;
5311 LocalBuilder local_copy = ig.DeclareLocal (expr_type);
5316 ig.Emit (OpCodes.Stloc, local_copy);
5318 bool old_in_try = ec.InTry;
5320 ig.BeginExceptionBlock ();
5321 Statement.Emit (ec);
5322 ec.InTry = old_in_try;
5324 Label skip = ig.DefineLabel ();
5325 bool old_in_finally = ec.InFinally;
5326 ig.BeginFinallyBlock ();
5327 ig.Emit (OpCodes.Ldloc, local_copy);
5328 ig.Emit (OpCodes.Brfalse, skip);
5329 ig.Emit (OpCodes.Ldloc, local_copy);
5330 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
5331 ig.MarkLabel (skip);
5332 ec.InFinally = old_in_finally;
5333 ig.EndExceptionBlock ();
5338 public override bool Resolve (EmitContext ec)
5340 if (expression_or_block is DictionaryEntry){
5341 expr = (Expression) ((DictionaryEntry) expression_or_block).Key;
5342 var_list = (ArrayList)((DictionaryEntry)expression_or_block).Value;
5344 if (!ResolveLocalVariableDecls (ec))
5347 } else if (expression_or_block is Expression){
5348 expr = (Expression) expression_or_block;
5350 expr = expr.Resolve (ec);
5354 expr_type = expr.Type;
5356 if (!ResolveExpression (ec))
5360 return Statement.Resolve (ec);
5363 protected override bool DoEmit (EmitContext ec)
5365 if (expression_or_block is DictionaryEntry)
5366 return EmitLocalVariableDecls (ec);
5367 else if (expression_or_block is Expression)
5368 return EmitExpression (ec);
5375 /// Implementation of the for each statement
5377 public class Foreach : Statement {
5379 LocalVariableReference variable;
5381 Statement statement;
5382 ForeachHelperMethods hm;
5383 Expression empty, conv;
5384 Type array_type, element_type;
5387 public Foreach (Expression type, LocalVariableReference var, Expression expr,
5388 Statement stmt, Location l)
5395 VariableInfo vi = var.VariableInfo;
5396 this.type = vi.Type;
5398 this.variable = var;
5404 public override bool Resolve (EmitContext ec)
5406 expr = expr.Resolve (ec);
5410 var_type = ec.DeclSpace.ResolveType (type, false, loc);
5411 if (var_type == null)
5415 // We need an instance variable. Not sure this is the best
5416 // way of doing this.
5418 // FIXME: When we implement propertyaccess, will those turn
5419 // out to return values in ExprClass? I think they should.
5421 if (!(expr.eclass == ExprClass.Variable || expr.eclass == ExprClass.Value ||
5422 expr.eclass == ExprClass.PropertyAccess || expr.eclass == ExprClass.IndexerAccess)){
5423 error1579 (expr.Type);
5427 if (expr.Type.IsArray) {
5428 array_type = expr.Type;
5429 element_type = array_type.GetElementType ();
5431 empty = new EmptyExpression (element_type);
5433 hm = ProbeCollectionType (ec, expr.Type);
5435 error1579 (expr.Type);
5439 array_type = expr.Type;
5440 element_type = hm.element_type;
5442 empty = new EmptyExpression (hm.element_type);
5445 ec.StartFlowBranching (FlowBranchingType.LOOP_BLOCK, loc);
5446 ec.CurrentBranching.CreateSibling ();
5450 // FIXME: maybe we can apply the same trick we do in the
5451 // array handling to avoid creating empty and conv in some cases.
5453 // Although it is not as important in this case, as the type
5454 // will not likely be object (what the enumerator will return).
5456 conv = Expression.ConvertExplicit (ec, empty, var_type, false, loc);
5460 if (variable.ResolveLValue (ec, empty) == null)
5463 if (!statement.Resolve (ec))
5466 FlowReturns returns = ec.EndFlowBranching ();
5471 // Retrieves a `public bool MoveNext ()' method from the Type `t'
5473 static MethodInfo FetchMethodMoveNext (Type t)
5475 MemberList move_next_list;
5477 move_next_list = TypeContainer.FindMembers (
5478 t, MemberTypes.Method,
5479 BindingFlags.Public | BindingFlags.Instance,
5480 Type.FilterName, "MoveNext");
5481 if (move_next_list.Count == 0)
5484 foreach (MemberInfo m in move_next_list){
5485 MethodInfo mi = (MethodInfo) m;
5488 args = TypeManager.GetArgumentTypes (mi);
5489 if (args != null && args.Length == 0){
5490 if (mi.ReturnType == TypeManager.bool_type)
5498 // Retrieves a `public T get_Current ()' method from the Type `t'
5500 static MethodInfo FetchMethodGetCurrent (Type t)
5502 MemberList move_next_list;
5504 move_next_list = TypeContainer.FindMembers (
5505 t, MemberTypes.Method,
5506 BindingFlags.Public | BindingFlags.Instance,
5507 Type.FilterName, "get_Current");
5508 if (move_next_list.Count == 0)
5511 foreach (MemberInfo m in move_next_list){
5512 MethodInfo mi = (MethodInfo) m;
5515 args = TypeManager.GetArgumentTypes (mi);
5516 if (args != null && args.Length == 0)
5523 // This struct records the helper methods used by the Foreach construct
5525 class ForeachHelperMethods {
5526 public EmitContext ec;
5527 public MethodInfo get_enumerator;
5528 public MethodInfo move_next;
5529 public MethodInfo get_current;
5530 public Type element_type;
5531 public Type enumerator_type;
5532 public bool is_disposable;
5534 public ForeachHelperMethods (EmitContext ec)
5537 this.element_type = TypeManager.object_type;
5538 this.enumerator_type = TypeManager.ienumerator_type;
5539 this.is_disposable = true;
5543 static bool GetEnumeratorFilter (MemberInfo m, object criteria)
5548 if (!(m is MethodInfo))
5551 if (m.Name != "GetEnumerator")
5554 MethodInfo mi = (MethodInfo) m;
5555 Type [] args = TypeManager.GetArgumentTypes (mi);
5557 if (args.Length != 0)
5560 ForeachHelperMethods hm = (ForeachHelperMethods) criteria;
5561 EmitContext ec = hm.ec;
5564 // Check whether GetEnumerator is accessible to us
5566 MethodAttributes prot = mi.Attributes & MethodAttributes.MemberAccessMask;
5568 Type declaring = mi.DeclaringType;
5569 if (prot == MethodAttributes.Private){
5570 if (declaring != ec.ContainerType)
5572 } else if (prot == MethodAttributes.FamANDAssem){
5573 // If from a different assembly, false
5574 if (!(mi is MethodBuilder))
5577 // Are we being invoked from the same class, or from a derived method?
5579 if (ec.ContainerType != declaring){
5580 if (!ec.ContainerType.IsSubclassOf (declaring))
5583 } else if (prot == MethodAttributes.FamORAssem){
5584 if (!(mi is MethodBuilder ||
5585 ec.ContainerType == declaring ||
5586 ec.ContainerType.IsSubclassOf (declaring)))
5588 } if (prot == MethodAttributes.Family){
5589 if (!(ec.ContainerType == declaring ||
5590 ec.ContainerType.IsSubclassOf (declaring)))
5595 // Ok, we can access it, now make sure that we can do something
5596 // with this `GetEnumerator'
5599 if (mi.ReturnType == TypeManager.ienumerator_type ||
5600 TypeManager.ienumerator_type.IsAssignableFrom (mi.ReturnType) ||
5601 (!RootContext.StdLib && TypeManager.ImplementsInterface (mi.ReturnType, TypeManager.ienumerator_type))) {
5602 hm.move_next = TypeManager.bool_movenext_void;
5603 hm.get_current = TypeManager.object_getcurrent_void;
5608 // Ok, so they dont return an IEnumerable, we will have to
5609 // find if they support the GetEnumerator pattern.
5611 Type return_type = mi.ReturnType;
5613 hm.move_next = FetchMethodMoveNext (return_type);
5614 if (hm.move_next == null)
5616 hm.get_current = FetchMethodGetCurrent (return_type);
5617 if (hm.get_current == null)
5620 hm.element_type = hm.get_current.ReturnType;
5621 hm.enumerator_type = return_type;
5622 hm.is_disposable = TypeManager.ImplementsInterface (
5623 hm.enumerator_type, TypeManager.idisposable_type);
5629 /// This filter is used to find the GetEnumerator method
5630 /// on which IEnumerator operates
5632 static MemberFilter FilterEnumerator;
5636 FilterEnumerator = new MemberFilter (GetEnumeratorFilter);
5639 void error1579 (Type t)
5641 Report.Error (1579, loc,
5642 "foreach statement cannot operate on variables of type `" +
5643 t.FullName + "' because that class does not provide a " +
5644 " GetEnumerator method or it is inaccessible");
5647 static bool TryType (Type t, ForeachHelperMethods hm)
5651 mi = TypeContainer.FindMembers (t, MemberTypes.Method,
5652 BindingFlags.Public | BindingFlags.NonPublic |
5653 BindingFlags.Instance,
5654 FilterEnumerator, hm);
5659 hm.get_enumerator = (MethodInfo) mi [0];
5664 // Looks for a usable GetEnumerator in the Type, and if found returns
5665 // the three methods that participate: GetEnumerator, MoveNext and get_Current
5667 ForeachHelperMethods ProbeCollectionType (EmitContext ec, Type t)
5669 ForeachHelperMethods hm = new ForeachHelperMethods (ec);
5671 if (TryType (t, hm))
5675 // Now try to find the method in the interfaces
5678 Type [] ifaces = t.GetInterfaces ();
5680 foreach (Type i in ifaces){
5681 if (TryType (i, hm))
5686 // Since TypeBuilder.GetInterfaces only returns the interface
5687 // types for this type, we have to keep looping, but once
5688 // we hit a non-TypeBuilder (ie, a Type), then we know we are
5689 // done, because it returns all the types
5691 if ((t is TypeBuilder))
5701 // FIXME: possible optimization.
5702 // We might be able to avoid creating `empty' if the type is the sam
5704 bool EmitCollectionForeach (EmitContext ec)
5706 ILGenerator ig = ec.ig;
5707 LocalBuilder enumerator, disposable;
5709 enumerator = ig.DeclareLocal (hm.enumerator_type);
5710 if (hm.is_disposable)
5711 disposable = ig.DeclareLocal (TypeManager.idisposable_type);
5716 // Instantiate the enumerator
5718 if (expr.Type.IsValueType){
5719 if (expr is IMemoryLocation){
5720 IMemoryLocation ml = (IMemoryLocation) expr;
5722 ml.AddressOf (ec, AddressOp.Load);
5724 throw new Exception ("Expr " + expr + " of type " + expr.Type +
5725 " does not implement IMemoryLocation");
5726 ig.Emit (OpCodes.Call, hm.get_enumerator);
5729 ig.Emit (OpCodes.Callvirt, hm.get_enumerator);
5731 ig.Emit (OpCodes.Stloc, enumerator);
5734 // Protect the code in a try/finalize block, so that
5735 // if the beast implement IDisposable, we get rid of it
5737 bool old_in_try = ec.InTry;
5739 if (hm.is_disposable) {
5740 ig.BeginExceptionBlock ();
5744 Label end_try = ig.DefineLabel ();
5746 ig.MarkLabel (ec.LoopBegin);
5747 ig.Emit (OpCodes.Ldloc, enumerator);
5748 ig.Emit (OpCodes.Callvirt, hm.move_next);
5749 ig.Emit (OpCodes.Brfalse, end_try);
5750 ig.Emit (OpCodes.Ldloc, enumerator);
5751 ig.Emit (OpCodes.Callvirt, hm.get_current);
5752 variable.EmitAssign (ec, conv);
5753 statement.Emit (ec);
5754 ig.Emit (OpCodes.Br, ec.LoopBegin);
5755 ig.MarkLabel (end_try);
5756 ec.InTry = old_in_try;
5758 // The runtime provides this for us.
5759 // ig.Emit (OpCodes.Leave, end);
5762 // Now the finally block
5764 if (hm.is_disposable) {
5765 Label end_finally = ig.DefineLabel ();
5766 bool old_in_finally = ec.InFinally;
5767 ec.InFinally = true;
5768 ig.BeginFinallyBlock ();
5770 ig.Emit (OpCodes.Ldloc, enumerator);
5771 ig.Emit (OpCodes.Isinst, TypeManager.idisposable_type);
5772 ig.Emit (OpCodes.Stloc, disposable);
5773 ig.Emit (OpCodes.Ldloc, disposable);
5774 ig.Emit (OpCodes.Brfalse, end_finally);
5775 ig.Emit (OpCodes.Ldloc, disposable);
5776 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
5777 ig.MarkLabel (end_finally);
5778 ec.InFinally = old_in_finally;
5780 // The runtime generates this anyways.
5781 // ig.Emit (OpCodes.Endfinally);
5783 ig.EndExceptionBlock ();
5786 ig.MarkLabel (ec.LoopEnd);
5791 // FIXME: possible optimization.
5792 // We might be able to avoid creating `empty' if the type is the sam
5794 bool EmitArrayForeach (EmitContext ec)
5796 int rank = array_type.GetArrayRank ();
5797 ILGenerator ig = ec.ig;
5799 LocalBuilder copy = ig.DeclareLocal (array_type);
5802 // Make our copy of the array
5805 ig.Emit (OpCodes.Stloc, copy);
5808 LocalBuilder counter = ig.DeclareLocal (TypeManager.int32_type);
5812 ig.Emit (OpCodes.Ldc_I4_0);
5813 ig.Emit (OpCodes.Stloc, counter);
5814 test = ig.DefineLabel ();
5815 ig.Emit (OpCodes.Br, test);
5817 loop = ig.DefineLabel ();
5818 ig.MarkLabel (loop);
5820 ig.Emit (OpCodes.Ldloc, copy);
5821 ig.Emit (OpCodes.Ldloc, counter);
5822 ArrayAccess.EmitLoadOpcode (ig, var_type);
5824 variable.EmitAssign (ec, conv);
5826 statement.Emit (ec);
5828 ig.MarkLabel (ec.LoopBegin);
5829 ig.Emit (OpCodes.Ldloc, counter);
5830 ig.Emit (OpCodes.Ldc_I4_1);
5831 ig.Emit (OpCodes.Add);
5832 ig.Emit (OpCodes.Stloc, counter);
5834 ig.MarkLabel (test);
5835 ig.Emit (OpCodes.Ldloc, counter);
5836 ig.Emit (OpCodes.Ldloc, copy);
5837 ig.Emit (OpCodes.Ldlen);
5838 ig.Emit (OpCodes.Conv_I4);
5839 ig.Emit (OpCodes.Blt, loop);
5841 LocalBuilder [] dim_len = new LocalBuilder [rank];
5842 LocalBuilder [] dim_count = new LocalBuilder [rank];
5843 Label [] loop = new Label [rank];
5844 Label [] test = new Label [rank];
5847 for (dim = 0; dim < rank; dim++){
5848 dim_len [dim] = ig.DeclareLocal (TypeManager.int32_type);
5849 dim_count [dim] = ig.DeclareLocal (TypeManager.int32_type);
5850 test [dim] = ig.DefineLabel ();
5851 loop [dim] = ig.DefineLabel ();
5854 for (dim = 0; dim < rank; dim++){
5855 ig.Emit (OpCodes.Ldloc, copy);
5856 IntLiteral.EmitInt (ig, dim);
5857 ig.Emit (OpCodes.Callvirt, TypeManager.int_getlength_int);
5858 ig.Emit (OpCodes.Stloc, dim_len [dim]);
5861 for (dim = 0; dim < rank; dim++){
5862 ig.Emit (OpCodes.Ldc_I4_0);
5863 ig.Emit (OpCodes.Stloc, dim_count [dim]);
5864 ig.Emit (OpCodes.Br, test [dim]);
5865 ig.MarkLabel (loop [dim]);
5868 ig.Emit (OpCodes.Ldloc, copy);
5869 for (dim = 0; dim < rank; dim++)
5870 ig.Emit (OpCodes.Ldloc, dim_count [dim]);
5873 // FIXME: Maybe we can cache the computation of `get'?
5875 Type [] args = new Type [rank];
5878 for (int i = 0; i < rank; i++)
5879 args [i] = TypeManager.int32_type;
5881 ModuleBuilder mb = CodeGen.ModuleBuilder;
5882 get = mb.GetArrayMethod (
5884 CallingConventions.HasThis| CallingConventions.Standard,
5886 ig.Emit (OpCodes.Call, get);
5887 variable.EmitAssign (ec, conv);
5888 statement.Emit (ec);
5889 ig.MarkLabel (ec.LoopBegin);
5890 for (dim = rank - 1; dim >= 0; dim--){
5891 ig.Emit (OpCodes.Ldloc, dim_count [dim]);
5892 ig.Emit (OpCodes.Ldc_I4_1);
5893 ig.Emit (OpCodes.Add);
5894 ig.Emit (OpCodes.Stloc, dim_count [dim]);
5896 ig.MarkLabel (test [dim]);
5897 ig.Emit (OpCodes.Ldloc, dim_count [dim]);
5898 ig.Emit (OpCodes.Ldloc, dim_len [dim]);
5899 ig.Emit (OpCodes.Blt, loop [dim]);
5902 ig.MarkLabel (ec.LoopEnd);
5907 protected override bool DoEmit (EmitContext ec)
5911 ILGenerator ig = ec.ig;
5913 Label old_begin = ec.LoopBegin, old_end = ec.LoopEnd;
5914 bool old_inloop = ec.InLoop;
5915 int old_loop_begin_try_catch_level = ec.LoopBeginTryCatchLevel;
5916 ec.LoopBegin = ig.DefineLabel ();
5917 ec.LoopEnd = ig.DefineLabel ();
5919 ec.LoopBeginTryCatchLevel = ec.TryCatchLevel;
5922 ret_val = EmitCollectionForeach (ec);
5924 ret_val = EmitArrayForeach (ec);
5926 ec.LoopBegin = old_begin;
5927 ec.LoopEnd = old_end;
5928 ec.InLoop = old_inloop;
5929 ec.LoopBeginTryCatchLevel = old_loop_begin_try_catch_level;
5936 /// AddHandler statement
5938 public class AddHandler : Statement {
5940 Expression EvtHandler;
5943 // keeps track whether EvtId is already resolved
5947 public AddHandler (Expression evt_id, Expression evt_handler, Location l)
5950 EvtHandler = evt_handler;
5953 //Console.WriteLine ("Adding handler '" + evt_handler + "' for Event '" + evt_id +"'");
5956 public override bool Resolve (EmitContext ec)
5959 // if EvetId is of EventExpr type that means
5960 // this is already resolved
5962 if (EvtId is EventExpr) {
5967 EvtId = EvtId.Resolve(ec);
5968 EvtHandler = EvtHandler.Resolve(ec,ResolveFlags.MethodGroup);
5969 if (EvtId == null || (!(EvtId is EventExpr))) {
5970 Report.Error (30676, "Need an event designator.");
5974 if (EvtHandler == null)
5976 Report.Error (999, "'AddHandler' statement needs an event handler.");
5983 protected override bool DoEmit (EmitContext ec)
5986 // Already resolved and emitted don't do anything
5992 ArrayList args = new ArrayList();
5993 Argument arg = new Argument (EvtHandler, Argument.AType.Expression);
5998 // The even type was already resolved to a delegate, so
5999 // we must un-resolve its name to generate a type expression
6000 string ts = (EvtId.Type.ToString()).Replace ('+','.');
6001 Expression dtype = Mono.MonoBASIC.Parser.DecomposeQI (ts, Location.Null);
6003 // which we can use to declare a new event handler
6005 d = new New (dtype, args, Location.Null);
6007 e = new CompoundAssign(Binary.Operator.Addition, EvtId, d, Location.Null);
6009 // we resolve it all and emit the code
6022 /// RemoveHandler statement
6024 public class RemoveHandler : Statement
\r
6027 Expression EvtHandler;
6029 public RemoveHandler (Expression evt_id, Expression evt_handler, Location l)
6032 EvtHandler = evt_handler;
6036 public override bool Resolve (EmitContext ec)
6038 EvtId = EvtId.Resolve(ec);
6039 EvtHandler = EvtHandler.Resolve(ec,ResolveFlags.MethodGroup);
6040 if (EvtId == null || (!(EvtId is EventExpr)))
\r
6042 Report.Error (30676, "Need an event designator.");
6046 if (EvtHandler == null)
6048 Report.Error (999, "'AddHandler' statement needs an event handler.");
6054 protected override bool DoEmit (EmitContext ec)
6057 ArrayList args = new ArrayList();
6058 Argument arg = new Argument (EvtHandler, Argument.AType.Expression);
6061 // The even type was already resolved to a delegate, so
6062 // we must un-resolve its name to generate a type expression
6063 string ts = (EvtId.Type.ToString()).Replace ('+','.');
6064 Expression dtype = Mono.MonoBASIC.Parser.DecomposeQI (ts, Location.Null);
6066 // which we can use to declare a new event handler
6068 d = new New (dtype, args, Location.Null);
6071 e = new CompoundAssign(Binary.Operator.Subtraction, EvtId, d, Location.Null);
6073 // we resolve it all and emit the code
6085 public class RedimClause {
6086 public Expression Expr;
6087 public ArrayList NewIndexes;
6089 public RedimClause (Expression e, ArrayList args)
6096 public class ReDim : Statement {
6097 ArrayList RedimTargets;
6101 private StatementExpression ReDimExpr;
6103 public ReDim (ArrayList targets, bool opt_preserve, Location l)
6106 RedimTargets = targets;
6107 Preserve = opt_preserve;
6110 public override bool Resolve (EmitContext ec)
6112 Expression RedimTarget;
6113 ArrayList NewIndexes;
6115 foreach (RedimClause rc in RedimTargets) {
6116 RedimTarget = rc.Expr;
6117 NewIndexes = rc.NewIndexes;
6119 RedimTarget = RedimTarget.Resolve (ec);
6120 if (!RedimTarget.Type.IsArray)
6121 Report.Error (49, "'ReDim' statement requires an array");
6123 ArrayList args = new ArrayList();
6124 foreach (Argument a in NewIndexes) {
6125 if (a.Resolve(ec, loc))
6129 for (int x = 0; x < args.Count; x++) {
6130 args[x] = new Binary (Binary.Operator.Addition,
6131 (Expression) args[x], new IntLiteral (1), Location.Null);
6135 if (RedimTarget.Type.GetArrayRank() != args.Count)
6136 Report.Error (30415, "'ReDim' cannot change the number of dimensions of an array.");
6138 BaseType = RedimTarget.Type.GetElementType();
6139 Expression BaseTypeExpr = MonoBASIC.Parser.DecomposeQI(BaseType.FullName.ToString(), Location.Null);
6140 ArrayCreation acExpr = new ArrayCreation (BaseTypeExpr, NewIndexes, "", null, Location.Null);
6141 // TODO: we are in a foreach we probably can't reuse ReDimExpr, must turn it into an array(list)
6144 ExpressionStatement PreserveExpr = (ExpressionStatement) new Preserve(RedimTarget, acExpr, loc);
6145 ReDimExpr = (StatementExpression) new StatementExpression ((ExpressionStatement) new Assign (RedimTarget, PreserveExpr, loc), loc);
6148 ReDimExpr = (StatementExpression) new StatementExpression ((ExpressionStatement) new Assign (RedimTarget, acExpr, loc), loc);
6149 ReDimExpr.Resolve(ec);
6154 protected override bool DoEmit (EmitContext ec)
6162 public class Erase : Statement {
6163 Expression EraseTarget;
6165 private StatementExpression EraseExpr;
6167 public Erase (Expression expr, Location l)
6173 public override bool Resolve (EmitContext ec)
6175 EraseTarget = EraseTarget.Resolve (ec);
6176 if (!EraseTarget.Type.IsArray)
6177 Report.Error (49, "'Erase' statement requires an array");
6179 EraseExpr = (StatementExpression) new StatementExpression ((ExpressionStatement) new Assign (EraseTarget, NullLiteral.Null, loc), loc);
6180 EraseExpr.Resolve(ec);
6185 protected override bool DoEmit (EmitContext ec)