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 if (ec.InTry || ec.InCatch)
924 ec.ig.Emit (OpCodes.Leave, l);
926 ec.ig.Emit (OpCodes.Br, l);
932 public class LabeledStatement : Statement {
933 public readonly Location Location;
941 public LabeledStatement (string label_name, Location l)
943 //this.label_name = label_name;
947 public Label LabelTarget (EmitContext ec)
951 label = ec.ig.DefineLabel ();
957 public bool IsDefined {
963 public bool HasBeenReferenced {
969 public void AddUsageVector (FlowBranching.UsageVector vector)
972 vectors = new ArrayList ();
974 vectors.Add (vector.Clone ());
977 public override bool Resolve (EmitContext ec)
980 ec.CurrentBranching.CurrentUsageVector.MergeJumpOrigins (vectors);
982 ec.CurrentBranching.CurrentUsageVector.Breaks = FlowReturns.NEVER;
983 ec.CurrentBranching.CurrentUsageVector.Returns = FlowReturns.NEVER;
991 protected override bool DoEmit (EmitContext ec)
994 ec.ig.MarkLabel (label);
1002 /// `goto default' statement
1004 public class GotoDefault : Statement {
1006 public GotoDefault (Location l)
1011 public override bool Resolve (EmitContext ec)
1013 ec.CurrentBranching.CurrentUsageVector.Breaks = FlowReturns.UNREACHABLE;
1017 protected override bool DoEmit (EmitContext ec)
1019 if (ec.Switch == null){
1020 Report.Error (153, loc, "goto default is only valid in a switch statement");
1024 if (!ec.Switch.GotDefault){
1025 Report.Error (30132, loc, "No default target on switch statement");
1028 ec.ig.Emit (OpCodes.Br, ec.Switch.DefaultTarget);
1034 /// `goto case' statement
1036 public class GotoCase : Statement {
1040 public GotoCase (Expression e, Location l)
1046 public override bool Resolve (EmitContext ec)
1048 if (ec.Switch == null){
1049 Report.Error (153, loc, "goto case is only valid in a switch statement");
1053 expr = expr.Resolve (ec);
1057 if (!(expr is Constant)){
1058 Report.Error (30132, loc, "Target expression for goto case is not constant");
1062 object val = Expression.ConvertIntLiteral (
1063 (Constant) expr, ec.Switch.SwitchType, loc);
1068 SwitchLabel sl = (SwitchLabel) ec.Switch.Elements [val];
1073 "No such label 'case " + val + "': for the goto case");
1076 label = sl.ILLabelCode;
1078 ec.CurrentBranching.CurrentUsageVector.Breaks = FlowReturns.UNREACHABLE;
1082 protected override bool DoEmit (EmitContext ec)
1084 ec.ig.Emit (OpCodes.Br, label);
1089 public class Throw : Statement {
1092 public Throw (Expression expr, Location l)
1098 public override bool Resolve (EmitContext ec)
1101 expr = expr.Resolve (ec);
1105 ExprClass eclass = expr.eclass;
1107 if (!(eclass == ExprClass.Variable || eclass == ExprClass.PropertyAccess ||
1108 eclass == ExprClass.Value || eclass == ExprClass.IndexerAccess)) {
1109 expr.Error118 ("value, variable, property or indexer access ");
1115 if ((t != TypeManager.exception_type) &&
1116 !t.IsSubclassOf (TypeManager.exception_type) &&
1117 !(expr is NullLiteral)) {
1118 Report.Error (30665, loc,
1119 "The type caught or thrown must be derived " +
1120 "from System.Exception");
1125 ec.CurrentBranching.CurrentUsageVector.Returns = FlowReturns.EXCEPTION;
1126 ec.CurrentBranching.CurrentUsageVector.Breaks = FlowReturns.EXCEPTION;
1130 protected override bool DoEmit (EmitContext ec)
1134 ec.ig.Emit (OpCodes.Rethrow);
1138 "A throw statement with no argument is only " +
1139 "allowed in a catch clause");
1146 ec.ig.Emit (OpCodes.Throw);
1152 // Support 'End' Statement which terminates execution immediately
1154 public class End : Statement {
1156 public End (Location l)
1161 public override bool Resolve (EmitContext ec)
1166 protected override bool DoEmit (EmitContext ec)
1168 Expression e = null;
1169 Expression tmp = Mono.MonoBASIC.Parser.DecomposeQI (
1170 "Microsoft.VisualBasic.CompilerServices.ProjectData.EndApp",
1173 e = new Invocation (tmp, null, loc);
1185 public class Break : Statement {
1187 public Break (Location l)
1192 public override bool Resolve (EmitContext ec)
1194 ec.CurrentBranching.MayLeaveLoop = true;
1195 ec.CurrentBranching.CurrentUsageVector.Breaks = FlowReturns.ALWAYS;
1199 protected override bool DoEmit (EmitContext ec)
1201 ILGenerator ig = ec.ig;
1203 if (ec.InLoop == false && ec.Switch == null){
1204 Report.Error (139, loc, "No enclosing loop or switch to continue to");
1208 if (ec.InTry || ec.InCatch)
1209 ig.Emit (OpCodes.Leave, ec.LoopEnd);
1211 ig.Emit (OpCodes.Br, ec.LoopEnd);
1217 public enum ExitType {
1228 public class Exit : Statement {
1229 public readonly ExitType type;
1230 public Exit (ExitType t, Location l)
1236 public override bool Resolve (EmitContext ec)
1238 ec.CurrentBranching.MayLeaveLoop = true;
1239 ec.CurrentBranching.CurrentUsageVector.Breaks = FlowReturns.ALWAYS;
1243 protected override bool DoEmit (EmitContext ec)
1245 ILGenerator ig = ec.ig;
1247 if (type != ExitType.SUB && type != ExitType.FUNCTION &&
1248 type != ExitType.PROPERTY && type != ExitType.TRY) {
1249 if (ec.InLoop == false && ec.Switch == null){
1250 if (type == ExitType.FOR)
1251 Report.Error (30096, loc, "No enclosing FOR loop to exit from");
1252 if (type == ExitType.WHILE)
1253 Report.Error (30097, loc, "No enclosing WHILE loop to exit from");
1254 if (type == ExitType.DO)
1255 Report.Error (30089, loc, "No enclosing DO loop to exit from");
1256 if (type == ExitType.SELECT)
1257 Report.Error (30099, loc, "No enclosing SELECT to exit from");
1262 if (ec.InTry || ec.InCatch)
1263 ig.Emit (OpCodes.Leave, ec.LoopEnd);
1265 ig.Emit (OpCodes.Br, ec.LoopEnd);
1268 Report.Error (30393, loc,
1269 "Control can not leave the body of the finally block");
1273 if (ec.InTry || ec.InCatch) {
1274 if (!ec.HasReturnLabel) {
1275 ec.ReturnLabel = ec.ig.DefineLabel ();
1276 ec.HasReturnLabel = true;
1278 ec.ig.Emit (OpCodes.Leave, ec.ReturnLabel);
1280 if(type == ExitType.SUB) {
1281 ec.ig.Emit (OpCodes.Ret);
1283 ec.ig.Emit (OpCodes.Ldloc_0);
1284 ec.ig.Emit (OpCodes.Ret);
1296 public class Continue : Statement {
1298 public Continue (Location l)
1303 public override bool Resolve (EmitContext ec)
1305 ec.CurrentBranching.CurrentUsageVector.Breaks = FlowReturns.ALWAYS;
1309 protected override bool DoEmit (EmitContext ec)
1311 Label begin = ec.LoopBegin;
1314 Report.Error (139, loc, "No enclosing loop to continue to");
1319 // UGH: Non trivial. This Br might cross a try/catch boundary
1323 // try { ... } catch { continue; }
1327 // try {} catch { while () { continue; }}
1329 if (ec.TryCatchLevel > ec.LoopBeginTryCatchLevel)
1330 ec.ig.Emit (OpCodes.Leave, begin);
1331 else if (ec.TryCatchLevel < ec.LoopBeginTryCatchLevel)
1332 throw new Exception ("Should never happen");
1334 ec.ig.Emit (OpCodes.Br, begin);
1340 // This is used in the control flow analysis code to specify whether the
1341 // current code block may return to its enclosing block before reaching
1344 public enum FlowReturns {
1345 // It can never return.
1348 // This means that the block contains a conditional return statement
1352 // The code always returns, ie. there's an unconditional return / break
1356 // The code always throws an exception.
1359 // The current code block is unreachable. This happens if it's immediately
1360 // following a FlowReturns.ALWAYS block.
1365 // This is a special bit vector which can inherit from another bit vector doing a
1366 // copy-on-write strategy. The inherited vector may have a smaller size than the
1369 public class MyBitVector {
1370 public readonly int Count;
1371 public readonly MyBitVector InheritsFrom;
1376 public MyBitVector (int Count)
1377 : this (null, Count)
1380 public MyBitVector (MyBitVector InheritsFrom, int Count)
1382 this.InheritsFrom = InheritsFrom;
1387 // Checks whether this bit vector has been modified. After setting this to true,
1388 // we won't use the inherited vector anymore, but our own copy of it.
1390 public bool IsDirty {
1397 initialize_vector ();
1402 // Get/set bit `index' in the bit vector.
1404 public bool this [int index]
1408 throw new ArgumentOutOfRangeException ();
1410 // We're doing a "copy-on-write" strategy here; as long
1411 // as nobody writes to the array, we can use our parent's
1412 // copy instead of duplicating the vector.
1415 return vector [index];
1416 else if (InheritsFrom != null) {
1417 BitArray inherited = InheritsFrom.Vector;
1419 if (index < inherited.Count)
1420 return inherited [index];
1429 throw new ArgumentOutOfRangeException ();
1431 // Only copy the vector if we're actually modifying it.
1433 if (this [index] != value) {
1434 initialize_vector ();
1436 vector [index] = value;
1442 // If you explicitly convert the MyBitVector to a BitArray, you will get a deep
1443 // copy of the bit vector.
1445 public static explicit operator BitArray (MyBitVector vector)
1447 vector.initialize_vector ();
1448 return vector.Vector;
1452 // Performs an `or' operation on the bit vector. The `new_vector' may have a
1453 // different size than the current one.
1455 public void Or (MyBitVector new_vector)
1457 BitArray new_array = new_vector.Vector;
1459 initialize_vector ();
1462 if (vector.Count < new_array.Count)
1463 upper = vector.Count;
1465 upper = new_array.Count;
1467 for (int i = 0; i < upper; i++)
1468 vector [i] = vector [i] | new_array [i];
1472 // Perfonrms an `and' operation on the bit vector. The `new_vector' may have
1473 // a different size than the current one.
1475 public void And (MyBitVector new_vector)
1477 BitArray new_array = new_vector.Vector;
1479 initialize_vector ();
1482 if (vector.Count < new_array.Count)
1483 lower = upper = vector.Count;
1485 lower = new_array.Count;
1486 upper = vector.Count;
1489 for (int i = 0; i < lower; i++)
1490 vector [i] = vector [i] & new_array [i];
1492 for (int i = lower; i < upper; i++)
1497 // This does a deep copy of the bit vector.
1499 public MyBitVector Clone ()
1501 MyBitVector retval = new MyBitVector (Count);
1503 retval.Vector = Vector;
1512 else if (!is_dirty && (InheritsFrom != null))
1513 return InheritsFrom.Vector;
1515 initialize_vector ();
1521 initialize_vector ();
1523 for (int i = 0; i < System.Math.Min (vector.Count, value.Count); i++)
1524 vector [i] = value [i];
1528 void initialize_vector ()
1533 vector = new BitArray (Count, false);
1534 if (InheritsFrom != null)
1535 Vector = InheritsFrom.Vector;
1540 public override string ToString ()
1542 StringBuilder sb = new StringBuilder ("MyBitVector (");
1544 BitArray vector = Vector;
1548 sb.Append ("INHERITED - ");
1549 for (int i = 0; i < vector.Count; i++) {
1552 sb.Append (vector [i]);
1556 return sb.ToString ();
1561 // The type of a FlowBranching.
1563 public enum FlowBranchingType {
1564 // Normal (conditional or toplevel) block.
1581 // A new instance of this class is created every time a new block is resolved
1582 // and if there's branching in the block's control flow.
1584 public class FlowBranching {
1586 // The type of this flow branching.
1588 public readonly FlowBranchingType Type;
1591 // The block this branching is contained in. This may be null if it's not
1592 // a top-level block and it doesn't declare any local variables.
1594 public readonly Block Block;
1597 // The parent of this branching or null if this is the top-block.
1599 public readonly FlowBranching Parent;
1602 // Start-Location of this flow branching.
1604 public readonly Location Location;
1607 // A list of UsageVectors. A new vector is added each time control flow may
1608 // take a different path.
1610 public ArrayList Siblings;
1613 // If this is an infinite loop.
1615 public bool Infinite;
1618 // If we may leave the current loop.
1620 public bool MayLeaveLoop;
1625 InternalParameters param_info;
1627 MyStructInfo[] struct_params;
1629 ArrayList finally_vectors;
1631 static int next_id = 0;
1635 // Performs an `And' operation on the FlowReturns status
1636 // (for instance, a block only returns ALWAYS if all its siblings
1639 public static FlowReturns AndFlowReturns (FlowReturns a, FlowReturns b)
1641 if (b == FlowReturns.UNREACHABLE)
1645 case FlowReturns.NEVER:
1646 if (b == FlowReturns.NEVER)
1647 return FlowReturns.NEVER;
1649 return FlowReturns.SOMETIMES;
1651 case FlowReturns.SOMETIMES:
1652 return FlowReturns.SOMETIMES;
1654 case FlowReturns.ALWAYS:
1655 if ((b == FlowReturns.ALWAYS) || (b == FlowReturns.EXCEPTION))
1656 return FlowReturns.ALWAYS;
1658 return FlowReturns.SOMETIMES;
1660 case FlowReturns.EXCEPTION:
1661 if (b == FlowReturns.EXCEPTION)
1662 return FlowReturns.EXCEPTION;
1663 else if (b == FlowReturns.ALWAYS)
1664 return FlowReturns.ALWAYS;
1666 return FlowReturns.SOMETIMES;
1673 // The vector contains a BitArray with information about which local variables
1674 // and parameters are already initialized at the current code position.
1676 public class UsageVector {
1678 // If this is true, then the usage vector has been modified and must be
1679 // merged when we're done with this branching.
1681 public bool IsDirty;
1684 // The number of parameters in this block.
1686 public readonly int CountParameters;
1689 // The number of locals in this block.
1691 public readonly int CountLocals;
1694 // If not null, then we inherit our state from this vector and do a
1695 // copy-on-write. If null, then we're the first sibling in a top-level
1696 // block and inherit from the empty vector.
1698 public readonly UsageVector InheritsFrom;
1703 MyBitVector locals, parameters;
1704 FlowReturns real_returns, real_breaks;
1707 static int next_id = 0;
1711 // Normally, you should not use any of these constructors.
1713 public UsageVector (UsageVector parent, int num_params, int num_locals)
1715 this.InheritsFrom = parent;
1716 this.CountParameters = num_params;
1717 this.CountLocals = num_locals;
1718 this.real_returns = FlowReturns.NEVER;
1719 this.real_breaks = FlowReturns.NEVER;
1721 if (parent != null) {
1722 locals = new MyBitVector (parent.locals, CountLocals);
1724 parameters = new MyBitVector (parent.parameters, num_params);
1725 real_returns = parent.Returns;
1726 real_breaks = parent.Breaks;
1728 locals = new MyBitVector (null, CountLocals);
1730 parameters = new MyBitVector (null, num_params);
1736 public UsageVector (UsageVector parent)
1737 : this (parent, parent.CountParameters, parent.CountLocals)
1741 // This does a deep copy of the usage vector.
1743 public UsageVector Clone ()
1745 UsageVector retval = new UsageVector (null, CountParameters, CountLocals);
1747 retval.locals = locals.Clone ();
1748 if (parameters != null)
1749 retval.parameters = parameters.Clone ();
1750 retval.real_returns = real_returns;
1751 retval.real_breaks = real_breaks;
1757 // State of parameter `number'.
1759 public bool this [int number]
1764 else if (number == 0)
1765 throw new ArgumentException ();
1767 return parameters [number - 1];
1773 else if (number == 0)
1774 throw new ArgumentException ();
1776 parameters [number - 1] = value;
1781 // State of the local variable `vi'.
1782 // If the local variable is a struct, use a non-zero `field_idx'
1783 // to check an individual field in it.
1785 public bool this [VariableInfo vi, int field_idx]
1788 if (vi.Number == -1)
1790 else if (vi.Number == 0)
1791 throw new ArgumentException ();
1793 return locals [vi.Number + field_idx - 1];
1797 if (vi.Number == -1)
1799 else if (vi.Number == 0)
1800 throw new ArgumentException ();
1802 locals [vi.Number + field_idx - 1] = value;
1807 // Specifies when the current block returns.
1808 // If this is FlowReturns.UNREACHABLE, then control can never reach the
1809 // end of the method (so that we don't need to emit a return statement).
1810 // The same applies for FlowReturns.EXCEPTION, but in this case the return
1811 // value will never be used.
1813 public FlowReturns Returns {
1815 return real_returns;
1819 real_returns = value;
1824 // Specifies whether control may return to our containing block
1825 // before reaching the end of this block. This happens if there
1826 // is a break/continue/goto/return in it.
1827 // This can also be used to find out whether the statement immediately
1828 // following the current block may be reached or not.
1830 public FlowReturns Breaks {
1836 real_breaks = value;
1840 public bool AlwaysBreaks {
1842 return (Breaks == FlowReturns.ALWAYS) ||
1843 (Breaks == FlowReturns.EXCEPTION) ||
1844 (Breaks == FlowReturns.UNREACHABLE);
1848 public bool MayBreak {
1850 return Breaks != FlowReturns.NEVER;
1854 public bool AlwaysReturns {
1856 return (Returns == FlowReturns.ALWAYS) ||
1857 (Returns == FlowReturns.EXCEPTION);
1861 public bool MayReturn {
1863 return (Returns == FlowReturns.SOMETIMES) ||
1864 (Returns == FlowReturns.ALWAYS);
1869 // Merge a child branching.
1871 public FlowReturns MergeChildren (FlowBranching branching, ICollection children)
1873 MyBitVector new_locals = null;
1874 MyBitVector new_params = null;
1876 FlowReturns new_returns = FlowReturns.NEVER;
1877 FlowReturns new_breaks = FlowReturns.NEVER;
1878 bool new_returns_set = false, new_breaks_set = false;
1880 Report.Debug (2, "MERGING CHILDREN", branching, branching.Type,
1881 this, children.Count);
1883 foreach (UsageVector child in children) {
1884 Report.Debug (2, " MERGING CHILD", child, child.is_finally);
1886 if (!child.is_finally) {
1887 if (child.Breaks != FlowReturns.UNREACHABLE) {
1888 // If Returns is already set, perform an
1889 // `And' operation on it, otherwise just set just.
1890 if (!new_returns_set) {
1891 new_returns = child.Returns;
1892 new_returns_set = true;
1894 new_returns = AndFlowReturns (
1895 new_returns, child.Returns);
1898 // If Breaks is already set, perform an
1899 // `And' operation on it, otherwise just set just.
1900 if (!new_breaks_set) {
1901 new_breaks = child.Breaks;
1902 new_breaks_set = true;
1904 new_breaks = AndFlowReturns (
1905 new_breaks, child.Breaks);
1908 // Ignore unreachable children.
1909 if (child.Returns == FlowReturns.UNREACHABLE)
1912 // A local variable is initialized after a flow branching if it
1913 // has been initialized in all its branches which do neither
1914 // always return or always throw an exception.
1916 // If a branch may return, but does not always return, then we
1917 // can treat it like a never-returning branch here: control will
1918 // only reach the code position after the branching if we did not
1921 // It's important to distinguish between always and sometimes
1922 // returning branches here:
1925 // 2 if (something) {
1929 // 6 Console.WriteLine (a);
1931 // The if block in lines 3-4 always returns, so we must not look
1932 // at the initialization of `a' in line 4 - thus it'll still be
1933 // uninitialized in line 6.
1935 // On the other hand, the following is allowed:
1942 // 6 Console.WriteLine (a);
1944 // Here, `a' is initialized in line 3 and we must not look at
1945 // line 5 since it always returns.
1947 if (child.is_finally) {
1948 if (new_locals == null)
1949 new_locals = locals.Clone ();
1950 new_locals.Or (child.locals);
1952 if (parameters != null) {
1953 if (new_params == null)
1954 new_params = parameters.Clone ();
1955 new_params.Or (child.parameters);
1959 if (!child.AlwaysReturns && !child.AlwaysBreaks) {
1960 if (new_locals != null)
1961 new_locals.And (child.locals);
1963 new_locals = locals.Clone ();
1964 new_locals.Or (child.locals);
1966 } else if (children.Count == 1) {
1967 new_locals = locals.Clone ();
1968 new_locals.Or (child.locals);
1971 // An `out' parameter must be assigned in all branches which do
1972 // not always throw an exception.
1973 if (parameters != null) {
1974 if (child.Breaks != FlowReturns.EXCEPTION) {
1975 if (new_params != null)
1976 new_params.And (child.parameters);
1978 new_params = parameters.Clone ();
1979 new_params.Or (child.parameters);
1981 } else if (children.Count == 1) {
1982 new_params = parameters.Clone ();
1983 new_params.Or (child.parameters);
1989 Returns = new_returns;
1990 if ((branching.Type == FlowBranchingType.BLOCK) ||
1991 (branching.Type == FlowBranchingType.EXCEPTION) ||
1992 (new_breaks == FlowReturns.UNREACHABLE) ||
1993 (new_breaks == FlowReturns.EXCEPTION))
1994 Breaks = new_breaks;
1995 else if (branching.Type == FlowBranchingType.SWITCH_SECTION)
1996 Breaks = new_returns;
1997 else if (branching.Type == FlowBranchingType.SWITCH){
1998 if (new_breaks == FlowReturns.ALWAYS)
1999 Breaks = FlowReturns.ALWAYS;
2003 // We've now either reached the point after the branching or we will
2004 // never get there since we always return or always throw an exception.
2006 // If we can reach the point after the branching, mark all locals and
2007 // parameters as initialized which have been initialized in all branches
2008 // we need to look at (see above).
2011 if (((new_breaks != FlowReturns.ALWAYS) &&
2012 (new_breaks != FlowReturns.EXCEPTION) &&
2013 (new_breaks != FlowReturns.UNREACHABLE)) ||
2014 (children.Count == 1)) {
2015 if (new_locals != null)
2016 locals.Or (new_locals);
2018 if (new_params != null)
2019 parameters.Or (new_params);
2022 Report.Debug (2, "MERGING CHILDREN DONE", branching.Type,
2023 new_params, new_locals, new_returns, new_breaks,
2024 branching.Infinite, branching.MayLeaveLoop, this);
2026 if (branching.Type == FlowBranchingType.SWITCH_SECTION) {
2027 if ((new_breaks != FlowReturns.ALWAYS) &&
2028 (new_breaks != FlowReturns.EXCEPTION) &&
2029 (new_breaks != FlowReturns.UNREACHABLE))
2030 Report.Error (163, branching.Location,
2031 "Control cannot fall through from one " +
2032 "case label to another");
2035 if (branching.Infinite && !branching.MayLeaveLoop) {
2036 Report.Debug (1, "INFINITE", new_returns, new_breaks,
2037 Returns, Breaks, this);
2039 // We're actually infinite.
2040 if (new_returns == FlowReturns.NEVER) {
2041 Breaks = FlowReturns.UNREACHABLE;
2042 return FlowReturns.UNREACHABLE;
2045 // If we're an infinite loop and do not break, the code after
2046 // the loop can never be reached. However, if we may return
2047 // from the loop, then we do always return (or stay in the loop
2049 if ((new_returns == FlowReturns.SOMETIMES) ||
2050 (new_returns == FlowReturns.ALWAYS)) {
2051 Returns = FlowReturns.ALWAYS;
2052 return FlowReturns.ALWAYS;
2060 // Tells control flow analysis that the current code position may be reached with
2061 // a forward jump from any of the origins listed in `origin_vectors' which is a
2062 // list of UsageVectors.
2064 // This is used when resolving forward gotos - in the following example, the
2065 // variable `a' is uninitialized in line 8 becase this line may be reached via
2066 // the goto in line 4:
2076 // 8 Console.WriteLine (a);
2079 public void MergeJumpOrigins (ICollection origin_vectors)
2081 Report.Debug (1, "MERGING JUMP ORIGIN", this);
2083 real_breaks = FlowReturns.NEVER;
2084 real_returns = FlowReturns.NEVER;
2086 foreach (UsageVector vector in origin_vectors) {
2087 Report.Debug (1, " MERGING JUMP ORIGIN", vector);
2089 locals.And (vector.locals);
2090 if (parameters != null)
2091 parameters.And (vector.parameters);
2092 Breaks = AndFlowReturns (Breaks, vector.Breaks);
2093 Returns = AndFlowReturns (Returns, vector.Returns);
2096 Report.Debug (1, "MERGING JUMP ORIGIN DONE", this);
2100 // This is used at the beginning of a finally block if there were
2101 // any return statements in the try block or one of the catch blocks.
2103 public void MergeFinallyOrigins (ICollection finally_vectors)
2105 Report.Debug (1, "MERGING FINALLY ORIGIN", this);
2107 real_breaks = FlowReturns.NEVER;
2109 foreach (UsageVector vector in finally_vectors) {
2110 Report.Debug (1, " MERGING FINALLY ORIGIN", vector);
2112 if (parameters != null)
2113 parameters.And (vector.parameters);
2114 Breaks = AndFlowReturns (Breaks, vector.Breaks);
2119 Report.Debug (1, "MERGING FINALLY ORIGIN DONE", this);
2122 // Performs an `or' operation on the locals and the parameters.
2124 public void Or (UsageVector new_vector)
2126 locals.Or (new_vector.locals);
2127 if (parameters != null)
2128 parameters.Or (new_vector.parameters);
2132 // Performs an `and' operation on the locals.
2134 public void AndLocals (UsageVector new_vector)
2136 locals.And (new_vector.locals);
2140 // Returns a deep copy of the parameters.
2142 public MyBitVector Parameters {
2144 if (parameters != null)
2145 return parameters.Clone ();
2152 // Returns a deep copy of the locals.
2154 public MyBitVector Locals {
2156 return locals.Clone ();
2164 public override string ToString ()
2166 StringBuilder sb = new StringBuilder ();
2168 sb.Append ("Vector (");
2171 sb.Append (Returns);
2174 if (parameters != null) {
2176 sb.Append (parameters);
2182 return sb.ToString ();
2186 FlowBranching (FlowBranchingType type, Location loc)
2188 this.Siblings = new ArrayList ();
2190 this.Location = loc;
2196 // Creates a new flow branching for `block'.
2197 // This is used from Block.Resolve to create the top-level branching of
2200 public FlowBranching (Block block, InternalParameters ip, Location loc)
2201 : this (FlowBranchingType.BLOCK, loc)
2206 int count = (ip != null) ? ip.Count : 0;
2209 param_map = new int [count];
2210 struct_params = new MyStructInfo [count];
2213 for (int i = 0; i < count; i++) {
2214 //Parameter.Modifier mod = param_info.ParameterModifier (i);
2216 // if ((mod & Parameter.Modifier.OUT) == 0)
2219 param_map [i] = ++num_params;
2221 Type param_type = param_info.ParameterType (i);
2223 struct_params [i] = MyStructInfo.GetStructInfo (param_type);
2224 if (struct_params [i] != null)
2225 num_params += struct_params [i].Count;
2228 Siblings = new ArrayList ();
2229 Siblings.Add (new UsageVector (null, num_params, block.CountVariables));
2233 // Creates a new flow branching which is contained in `parent'.
2234 // You should only pass non-null for the `block' argument if this block
2235 // introduces any new variables - in this case, we need to create a new
2236 // usage vector with a different size than our parent's one.
2238 public FlowBranching (FlowBranching parent, FlowBranchingType type,
2239 Block block, Location loc)
2245 if (parent != null) {
2246 param_info = parent.param_info;
2247 param_map = parent.param_map;
2248 struct_params = parent.struct_params;
2249 num_params = parent.num_params;
2254 vector = new UsageVector (parent.CurrentUsageVector, num_params,
2255 Block.CountVariables);
2257 vector = new UsageVector (Parent.CurrentUsageVector);
2259 Siblings.Add (vector);
2262 case FlowBranchingType.EXCEPTION:
2263 finally_vectors = new ArrayList ();
2272 // Returns the branching's current usage vector.
2274 public UsageVector CurrentUsageVector
2277 return (UsageVector) Siblings [Siblings.Count - 1];
2282 // Creates a sibling of the current usage vector.
2284 public void CreateSibling ()
2286 Siblings.Add (new UsageVector (Parent.CurrentUsageVector));
2288 Report.Debug (1, "CREATED SIBLING", CurrentUsageVector);
2292 // Creates a sibling for a `finally' block.
2294 public void CreateSiblingForFinally ()
2296 if (Type != FlowBranchingType.EXCEPTION)
2297 throw new NotSupportedException ();
2301 CurrentUsageVector.MergeFinallyOrigins (finally_vectors);
2306 // Merge a child branching.
2308 public FlowReturns MergeChild (FlowBranching child)
2310 FlowReturns returns = CurrentUsageVector.MergeChildren (child, child.Siblings);
2312 if (child.Type != FlowBranchingType.LOOP_BLOCK)
2313 MayLeaveLoop |= child.MayLeaveLoop;
2315 MayLeaveLoop = false;
2321 // Does the toplevel merging.
2323 public FlowReturns MergeTopBlock ()
2325 if ((Type != FlowBranchingType.BLOCK) || (Block == null))
2326 throw new NotSupportedException ();
2328 UsageVector vector = new UsageVector (null, num_params, Block.CountVariables);
2330 Report.Debug (1, "MERGING TOP BLOCK", Location, vector);
2332 vector.MergeChildren (this, Siblings);
2335 Siblings.Add (vector);
2337 Report.Debug (1, "MERGING TOP BLOCK DONE", Location, vector);
2339 if (vector.Breaks != FlowReturns.EXCEPTION) {
2340 return vector.AlwaysBreaks ? FlowReturns.ALWAYS : vector.Returns;
2342 return FlowReturns.EXCEPTION;
2345 public bool InTryBlock ()
2347 if (finally_vectors != null)
2349 else if (Parent != null)
2350 return Parent.InTryBlock ();
2355 public void AddFinallyVector (UsageVector vector)
2357 if (finally_vectors != null) {
2358 finally_vectors.Add (vector.Clone ());
2363 Parent.AddFinallyVector (vector);
2365 throw new NotSupportedException ();
2368 public bool IsVariableAssigned (VariableInfo vi)
2370 if (CurrentUsageVector.AlwaysBreaks)
2373 return CurrentUsageVector [vi, 0];
2376 public bool IsVariableAssigned (VariableInfo vi, int field_idx)
2378 if (CurrentUsageVector.AlwaysBreaks)
2381 return CurrentUsageVector [vi, field_idx];
2384 public void SetVariableAssigned (VariableInfo vi)
2386 if (CurrentUsageVector.AlwaysBreaks)
2389 CurrentUsageVector [vi, 0] = true;
2392 public void SetVariableAssigned (VariableInfo vi, int field_idx)
2394 if (CurrentUsageVector.AlwaysBreaks)
2397 CurrentUsageVector [vi, field_idx] = true;
2400 public bool IsParameterAssigned (int number)
2402 int index = param_map [number];
2407 if (CurrentUsageVector [index])
2410 // Parameter is not assigned, so check whether it's a struct.
2411 // If it's either not a struct or a struct which non-public
2412 // fields, return false.
2413 MyStructInfo struct_info = struct_params [number];
2414 if ((struct_info == null) || struct_info.HasNonPublicFields)
2417 // Ok, so each field must be assigned.
2418 for (int i = 0; i < struct_info.Count; i++)
2419 if (!CurrentUsageVector [index + i])
2425 public bool IsParameterAssigned (int number, string field_name)
2427 int index = param_map [number];
2432 MyStructInfo info = (MyStructInfo) struct_params [number];
2436 int field_idx = info [field_name];
2438 return CurrentUsageVector [index + field_idx];
2441 public void SetParameterAssigned (int number)
2443 if (param_map [number] == 0)
2446 if (!CurrentUsageVector.AlwaysBreaks)
2447 CurrentUsageVector [param_map [number]] = true;
2450 public void SetParameterAssigned (int number, string field_name)
2452 int index = param_map [number];
2457 MyStructInfo info = (MyStructInfo) struct_params [number];
2461 int field_idx = info [field_name];
2463 if (!CurrentUsageVector.AlwaysBreaks)
2464 CurrentUsageVector [index + field_idx] = true;
2467 public bool IsReachable ()
2472 case FlowBranchingType.SWITCH_SECTION:
2473 // The code following a switch block is reachable unless the switch
2474 // block always returns.
2475 reachable = !CurrentUsageVector.AlwaysReturns;
2478 case FlowBranchingType.LOOP_BLOCK:
2479 // The code following a loop is reachable unless the loop always
2480 // returns or it's an infinite loop without any `break's in it.
2481 reachable = !CurrentUsageVector.AlwaysReturns &&
2482 (CurrentUsageVector.Breaks != FlowReturns.UNREACHABLE);
2486 // The code following a block or exception is reachable unless the
2487 // block either always returns or always breaks.
2488 reachable = !CurrentUsageVector.AlwaysBreaks &&
2489 !CurrentUsageVector.AlwaysReturns;
2493 Report.Debug (1, "REACHABLE", Type, CurrentUsageVector.Returns,
2494 CurrentUsageVector.Breaks, CurrentUsageVector, reachable);
2499 public override string ToString ()
2501 StringBuilder sb = new StringBuilder ("FlowBranching (");
2506 if (Block != null) {
2508 sb.Append (Block.ID);
2510 sb.Append (Block.StartLocation);
2513 sb.Append (Siblings.Count);
2515 sb.Append (CurrentUsageVector);
2517 return sb.ToString ();
2521 public class MyStructInfo {
2522 public readonly Type Type;
2523 public readonly FieldInfo[] Fields;
2524 public readonly FieldInfo[] NonPublicFields;
2525 public readonly int Count;
2526 public readonly int CountNonPublic;
2527 public readonly bool HasNonPublicFields;
2529 private static Hashtable field_type_hash = new Hashtable ();
2530 private Hashtable field_hash;
2532 // Private constructor. To save memory usage, we only need to create one instance
2533 // of this class per struct type.
2534 private MyStructInfo (Type type)
2538 if (type is TypeBuilder) {
2539 TypeContainer tc = TypeManager.LookupTypeContainer (type);
2541 ArrayList fields = tc.Fields;
2542 if (fields != null) {
2543 foreach (Field field in fields) {
2544 if ((field.ModFlags & Modifiers.STATIC) != 0)
2546 if ((field.ModFlags & Modifiers.PUBLIC) != 0)
2553 Fields = new FieldInfo [Count];
2554 NonPublicFields = new FieldInfo [CountNonPublic];
2556 Count = CountNonPublic = 0;
2557 if (fields != null) {
2558 foreach (Field field in fields) {
2559 if ((field.ModFlags & Modifiers.STATIC) != 0)
2561 if ((field.ModFlags & Modifiers.PUBLIC) != 0)
2562 Fields [Count++] = field.FieldBuilder;
2564 NonPublicFields [CountNonPublic++] =
2570 Fields = type.GetFields (BindingFlags.Instance|BindingFlags.Public);
2571 Count = Fields.Length;
2573 NonPublicFields = type.GetFields (BindingFlags.Instance|BindingFlags.NonPublic);
2574 CountNonPublic = NonPublicFields.Length;
2577 Count += NonPublicFields.Length;
2580 field_hash = new Hashtable ();
2581 foreach (FieldInfo field in Fields)
2582 field_hash.Add (field.Name, ++number);
2584 if (NonPublicFields.Length != 0)
2585 HasNonPublicFields = true;
2587 foreach (FieldInfo field in NonPublicFields)
2588 field_hash.Add (field.Name, ++number);
2591 public int this [string name] {
2593 if (field_hash.Contains (name))
2594 return (int) field_hash [name];
2600 public FieldInfo this [int index] {
2602 if (index >= Fields.Length)
2603 return NonPublicFields [index - Fields.Length];
2605 return Fields [index];
2609 public static MyStructInfo GetStructInfo (Type type)
2611 if (!TypeManager.IsValueType (type) || TypeManager.IsEnumType (type))
2614 if (!(type is TypeBuilder) && TypeManager.IsBuiltinType (type))
2617 MyStructInfo info = (MyStructInfo) field_type_hash [type];
2621 info = new MyStructInfo (type);
2622 field_type_hash.Add (type, info);
2626 public static MyStructInfo GetStructInfo (TypeContainer tc)
2628 MyStructInfo info = (MyStructInfo) field_type_hash [tc.TypeBuilder];
2632 info = new MyStructInfo (tc.TypeBuilder);
2633 field_type_hash.Add (tc.TypeBuilder, info);
2638 public class VariableInfo : IVariable {
2639 public Expression Type;
2640 public LocalBuilder LocalBuilder;
2641 public Type VariableType;
2642 public readonly string Name;
2643 public readonly Location Location;
2644 public readonly int Block;
2649 public bool Assigned;
2650 public bool ReadOnly;
2652 public VariableInfo (Expression type, string name, int block, Location l)
2657 LocalBuilder = null;
2661 public VariableInfo (TypeContainer tc, int block, Location l)
2663 VariableType = tc.TypeBuilder;
2664 struct_info = MyStructInfo.GetStructInfo (tc);
2666 LocalBuilder = null;
2670 MyStructInfo struct_info;
2671 public MyStructInfo StructInfo {
2677 public bool IsAssigned (EmitContext ec, Location loc)
2678 {/* FIXME: we shouldn't just skip this!!!
2679 if (!ec.DoFlowAnalysis || ec.CurrentBranching.IsVariableAssigned (this))
2682 MyStructInfo struct_info = StructInfo;
2683 if ((struct_info == null) || (struct_info.HasNonPublicFields && (Name != null))) {
2684 Report.Error (165, loc, "Use of unassigned local variable `" + Name + "'");
2685 ec.CurrentBranching.SetVariableAssigned (this);
2689 int count = struct_info.Count;
2691 for (int i = 0; i < count; i++) {
2692 if (!ec.CurrentBranching.IsVariableAssigned (this, i+1)) {
2694 Report.Error (165, loc,
2695 "Use of unassigned local variable `" +
2697 ec.CurrentBranching.SetVariableAssigned (this);
2701 FieldInfo field = struct_info [i];
2702 Report.Error (171, loc,
2703 "Field `" + TypeManager.MonoBASIC_Name (VariableType) +
2704 "." + field.Name + "' must be fully initialized " +
2705 "before control leaves the constructor");
2713 public bool IsFieldAssigned (EmitContext ec, string name, Location loc)
2715 if (!ec.DoFlowAnalysis || ec.CurrentBranching.IsVariableAssigned (this) ||
2716 (struct_info == null))
2719 int field_idx = StructInfo [name];
2723 if (!ec.CurrentBranching.IsVariableAssigned (this, field_idx)) {
2724 Report.Error (170, loc,
2725 "Use of possibly unassigned field `" + name + "'");
2726 ec.CurrentBranching.SetVariableAssigned (this, field_idx);
2733 public void SetAssigned (EmitContext ec)
2735 if (ec.DoFlowAnalysis)
2736 ec.CurrentBranching.SetVariableAssigned (this);
2739 public void SetFieldAssigned (EmitContext ec, string name)
2741 if (ec.DoFlowAnalysis && (struct_info != null))
2742 ec.CurrentBranching.SetVariableAssigned (this, StructInfo [name]);
2745 public bool Resolve (DeclSpace decl)
2747 if (struct_info != null)
2750 if (VariableType == null)
2751 VariableType = decl.ResolveType (Type, false, Location);
2753 if (VariableType == null)
2756 struct_info = MyStructInfo.GetStructInfo (VariableType);
2761 public void MakePinned ()
2763 TypeManager.MakePinned (LocalBuilder);
2766 public override string ToString ()
2768 return "VariableInfo (" + Number + "," + Type + "," + Location + ")";
2773 /// Block represents a C# block.
2777 /// This class is used in a number of places: either to represent
2778 /// explicit blocks that the programmer places or implicit blocks.
2780 /// Implicit blocks are used as labels or to introduce variable
2783 public class Block : Statement {
2784 public readonly Block Parent;
2785 public readonly bool Implicit;
2786 public readonly Location StartLocation;
2787 public Location EndLocation;
2790 // The statements in this block
2792 public ArrayList statements;
2795 // An array of Blocks. We keep track of children just
2796 // to generate the local variable declarations.
2798 // Statements and child statements are handled through the
2804 // Labels. (label, block) pairs.
2806 CaseInsensitiveHashtable labels;
2809 // Keeps track of (name, type) pairs
2811 CaseInsensitiveHashtable variables;
2814 // Keeps track of constants
2815 CaseInsensitiveHashtable constants;
2818 // Maps variable names to ILGenerator.LocalBuilders
2820 //CaseInsensitiveHashtable local_builders;
2822 // to hold names of variables required for late binding
2823 public const string lateBindingArgs = "1_LBArgs";
2824 public const string lateBindingArgNames = "1_LBArgsNames";
2825 public const string lateBindingCopyBack = "1_LBCopyBack";
2827 bool isLateBindingRequired = false;
2835 public Block (Block parent)
2836 : this (parent, false, Location.Null, Location.Null)
2839 public Block (Block parent, bool implicit_block)
2840 : this (parent, implicit_block, Location.Null, Location.Null)
2843 public Block (Block parent, bool implicit_block, Parameters parameters)
2844 : this (parent, implicit_block, parameters, Location.Null, Location.Null)
2847 public Block (Block parent, Location start, Location end)
2848 : this (parent, false, start, end)
2851 public Block (Block parent, Parameters parameters, Location start, Location end)
2852 : this (parent, false, parameters, start, end)
2855 public Block (Block parent, bool implicit_block, Location start, Location end)
2856 : this (parent, implicit_block, Parameters.EmptyReadOnlyParameters,
2860 public Block (Block parent, bool implicit_block, Parameters parameters,
2861 Location start, Location end)
2864 parent.AddChild (this);
2867 // Add variables that may be required for late binding
2868 variables = new CaseInsensitiveHashtable ();
2869 ArrayList rank_specifier = new ArrayList ();
2870 ArrayList element = new ArrayList ();
2871 element.Add (new EmptyExpression ());
2872 rank_specifier.Add (element);
2873 Expression e = Mono.MonoBASIC.Parser.DecomposeQI ("System.Object[]", start);
2874 AddVariable (e, Block.lateBindingArgs, null, start);
2875 e = Mono.MonoBASIC.Parser.DecomposeQI ("System.String[]", start);
2876 AddVariable (e, Block.lateBindingArgNames, null, start);
2877 e = Mono.MonoBASIC.Parser.DecomposeQI ("System.Boolean[]", start);
2878 AddVariable (e, Block.lateBindingCopyBack, null, start);
2881 this.Parent = parent;
2882 this.Implicit = implicit_block;
2883 this.parameters = parameters;
2884 this.StartLocation = start;
2885 this.EndLocation = end;
2888 statements = new ArrayList ();
2891 public bool IsLateBindingRequired {
2893 return isLateBindingRequired;
2896 isLateBindingRequired = value;
2906 void AddChild (Block b)
2908 if (children == null)
2909 children = new ArrayList ();
2914 public void SetEndLocation (Location loc)
2920 /// Adds a label to the current block.
2924 /// false if the name already exists in this block. true
2928 public bool AddLabel (string name, LabeledStatement target)
2931 labels = new CaseInsensitiveHashtable ();
2932 if (labels.Contains (name))
2935 labels.Add (name, target);
2939 public LabeledStatement LookupLabel (string name)
2941 if (labels != null){
2942 if (labels.Contains (name))
2943 return ((LabeledStatement) labels [name]);
2947 return Parent.LookupLabel (name);
2952 VariableInfo this_variable = null;
2955 // Returns the "this" instance variable of this block.
2956 // See AddThisVariable() for more information.
2958 public VariableInfo ThisVariable {
2960 if (this_variable != null)
2961 return this_variable;
2962 else if (Parent != null)
2963 return Parent.ThisVariable;
2969 Hashtable child_variable_names;
2972 // Marks a variable with name @name as being used in a child block.
2973 // If a variable name has been used in a child block, it's illegal to
2974 // declare a variable with the same name in the current block.
2976 public void AddChildVariableName (string name)
2978 if (child_variable_names == null)
2979 child_variable_names = new CaseInsensitiveHashtable ();
2981 if (!child_variable_names.Contains (name))
2982 child_variable_names.Add (name, true);
2986 // Marks all variables from block @block and all its children as being
2987 // used in a child block.
2989 public void AddChildVariableNames (Block block)
2991 if (block.Variables != null) {
2992 foreach (string name in block.Variables.Keys)
2993 AddChildVariableName (name);
2996 foreach (Block child in block.children) {
2997 if (child.Variables != null) {
2998 foreach (string name in child.Variables.Keys)
2999 AddChildVariableName (name);
3005 // Checks whether a variable name has already been used in a child block.
3007 public bool IsVariableNameUsedInChildBlock (string name)
3009 if (child_variable_names == null)
3012 return child_variable_names.Contains (name);
3016 // This is used by non-static `struct' constructors which do not have an
3017 // initializer - in this case, the constructor must initialize all of the
3018 // struct's fields. To do this, we add a "this" variable and use the flow
3019 // analysis code to ensure that it's been fully initialized before control
3020 // leaves the constructor.
3022 public VariableInfo AddThisVariable (TypeContainer tc, Location l)
3024 if (this_variable != null)
3025 return this_variable;
3027 this_variable = new VariableInfo (tc, ID, l);
3029 if (variables == null)
3030 variables = new CaseInsensitiveHashtable ();
3031 variables.Add ("this", this_variable);
3033 return this_variable;
3036 public VariableInfo AddVariable (Expression type, string name, Parameters pars, Location l)
3038 if (variables == null)
3039 variables = new CaseInsensitiveHashtable ();
3041 VariableInfo vi = GetVariableInfo (name);
3044 Report.Error (30616, l, "A local variable named `" + name + "' " +
3045 "cannot be declared in this scope since it would " +
3046 "give a different meaning to `" + name + "', which " +
3047 "is already used in a `parent or current' scope to " +
3048 "denote something else");
3050 Report.Error (30290, l, "A local variable `" + name + "' is already " +
3051 "defined in this scope");
3055 if (IsVariableNameUsedInChildBlock (name)) {
3056 Report.Error (136, l, "A local variable named `" + name + "' " +
3057 "cannot be declared in this scope since it would " +
3058 "give a different meaning to `" + name + "', which " +
3059 "is already used in a `child' scope to denote something " +
3066 Parameter p = pars.GetParameterByName (name, out idx);
3068 Report.Error (30616, l, "A local variable named `" + name + "' " +
3069 "cannot be declared in this scope since it would " +
3070 "give a different meaning to `" + name + "', which " +
3071 "is already used in a `parent or current' scope to " +
3072 "denote something else");
3077 vi = new VariableInfo (type, name, ID, l);
3079 variables.Add (name, vi);
3081 if (variables_initialized)
3082 throw new Exception ();
3084 // Console.WriteLine ("Adding {0} to {1}", name, ID);
3088 public bool AddConstant (Expression type, string name, Expression value, Parameters pars, Location l)
3090 if (AddVariable (type, name, pars, l) == null)
3093 if (constants == null)
3094 constants = new CaseInsensitiveHashtable ();
3096 constants.Add (name, value);
3100 public Hashtable Variables {
3106 public VariableInfo GetVariableInfo (string name)
3108 if (variables != null) {
3110 temp = variables [name];
3113 return (VariableInfo) temp;
3118 return Parent.GetVariableInfo (name);
3123 public Expression GetVariableType (string name)
3125 VariableInfo vi = GetVariableInfo (name);
3133 public Expression GetConstantExpression (string name)
3135 if (constants != null) {
3137 temp = constants [name];
3140 return (Expression) temp;
3144 return Parent.GetConstantExpression (name);
3150 /// True if the variable named @name has been defined
3153 public bool IsVariableDefined (string name)
3155 // Console.WriteLine ("Looking up {0} in {1}", name, ID);
3156 if (variables != null) {
3157 if (variables.Contains (name))
3162 return Parent.IsVariableDefined (name);
3168 /// True if the variable named @name is a constant
3170 public bool IsConstant (string name)
3172 Expression e = null;
3174 e = GetConstantExpression (name);
3180 /// Use to fetch the statement associated with this label
3182 public Statement this [string name] {
3184 return (Statement) labels [name];
3188 Parameters parameters = null;
3189 public Parameters Parameters {
3192 return Parent.Parameters;
3199 /// A list of labels that were not used within this block
3201 public string [] GetUnreferenced ()
3203 // FIXME: Implement me
3207 public void AddStatement (Statement s)
3224 bool variables_initialized = false;
3225 int count_variables = 0, first_variable = 0;
3227 void UpdateVariableInfo (EmitContext ec)
3229 DeclSpace ds = ec.DeclSpace;
3234 first_variable += Parent.CountVariables;
3236 count_variables = first_variable;
3237 if (variables != null) {
3238 foreach (VariableInfo vi in variables.Values) {
3239 if (!vi.Resolve (ds)) {
3244 vi.Number = ++count_variables;
3246 if (vi.StructInfo != null)
3247 count_variables += vi.StructInfo.Count;
3251 variables_initialized = true;
3256 // The number of local variables in this block
3258 public int CountVariables
3261 if (!variables_initialized)
3262 throw new Exception ();
3264 return count_variables;
3269 /// Emits the variable declarations and labels.
3272 /// tc: is our typecontainer (to resolve type references)
3273 /// ig: is the code generator:
3274 /// toplevel: the toplevel block. This is used for checking
3275 /// that no two labels with the same name are used.
3277 public void EmitMeta (EmitContext ec, Block toplevel)
3279 //DeclSpace ds = ec.DeclSpace;
3280 ILGenerator ig = ec.ig;
3282 if (!variables_initialized)
3283 UpdateVariableInfo (ec);
3286 // Process this block variables
3288 if (variables != null){
3289 //local_builders = new CaseInsensitiveHashtable ();
3291 foreach (DictionaryEntry de in variables){
3292 string name = (string) de.Key;
3294 if (!isLateBindingRequired) {
3295 if (name.Equals (Block.lateBindingArgs) ||
3296 name.Equals (Block.lateBindingArgNames) ||
3297 name.Equals (Block.lateBindingCopyBack))
3301 VariableInfo vi = (VariableInfo) de.Value;
3303 if (vi.VariableType == null)
3306 vi.LocalBuilder = ig.DeclareLocal (vi.VariableType);
3308 if (CodeGen.SymbolWriter != null)
3309 vi.LocalBuilder.SetLocalSymInfo (name);
3311 if (constants == null)
3314 Expression cv = (Expression) constants [name];
3318 Expression e = cv.Resolve (ec);
3322 if (!(e is Constant)){
3323 Report.Error (133, vi.Location,
3324 "The expression being assigned to `" +
3325 name + "' must be constant (" + e + ")");
3329 constants.Remove (name);
3330 constants.Add (name, e);
3335 // Now, handle the children
3337 if (children != null){
3338 foreach (Block b in children)
3339 b.EmitMeta (ec, toplevel);
3343 public void UsageWarning ()
3347 if (variables != null){
3348 foreach (DictionaryEntry de in variables){
3349 VariableInfo vi = (VariableInfo) de.Value;
3354 name = (string) de.Key;
3358 219, vi.Location, "The variable `" + name +
3359 "' is assigned but its value is never used");
3362 168, vi.Location, "The variable `" +
3364 "' is declared but never used");
3369 if (children != null)
3370 foreach (Block b in children)
3374 bool has_ret = false;
3376 public override bool Resolve (EmitContext ec)
3378 Block prev_block = ec.CurrentBlock;
3381 ec.CurrentBlock = this;
3383 if (!variables_initialized)
3384 UpdateVariableInfo (ec);
3386 ec.StartFlowBranching (this);
3388 Report.Debug (1, "RESOLVE BLOCK", StartLocation, ec.CurrentBranching);
3390 ArrayList new_statements = new ArrayList ();
3391 bool unreachable = false, warning_shown = false;
3393 foreach (Statement s in statements){
3394 if (unreachable && !(s is LabeledStatement)) {
3395 if (!warning_shown && !(s is EmptyStatement)) {
3396 warning_shown = true;
3397 Warning_DeadCodeFound (s.loc);
3402 if (s.Resolve (ec) == false) {
3407 if (s is LabeledStatement)
3408 unreachable = false;
3410 unreachable = ! ec.CurrentBranching.IsReachable ();
3412 new_statements.Add (s);
3415 statements = new_statements;
3417 Report.Debug (1, "RESOLVE BLOCK DONE", StartLocation, ec.CurrentBranching);
3419 FlowReturns returns = ec.EndFlowBranching ();
3420 ec.CurrentBlock = prev_block;
3422 // If we're a non-static `struct' constructor which doesn't have an
3423 // initializer, then we must initialize all of the struct's fields.
3424 if ((this_variable != null) && (returns != FlowReturns.EXCEPTION) &&
3425 !this_variable.IsAssigned (ec, loc))
3428 if ((labels != null) && (RootContext.WarningLevel >= 2)) {
3429 foreach (LabeledStatement label in labels.Values)
3430 if (!label.HasBeenReferenced)
3431 Report.Warning (164, label.Location,
3432 "This label has not been referenced");
3435 if ((returns == FlowReturns.ALWAYS) ||
3436 (returns == FlowReturns.EXCEPTION) ||
3437 (returns == FlowReturns.UNREACHABLE))
3443 protected override bool DoEmit (EmitContext ec)
3445 Block prev_block = ec.CurrentBlock;
3447 ec.CurrentBlock = this;
3449 ec.Mark (StartLocation);
3450 foreach (Statement s in statements)
3453 ec.Mark (EndLocation);
3455 ec.CurrentBlock = prev_block;
3460 public class StatementSequence : Expression {
3462 ArrayList args, originalArgs;
3464 bool isRetValRequired;
3465 bool isLeftHandSide;
3466 bool isIndexerAccess;
3468 Expression type_expr;
3470 public StatementSequence (Block parent, Location loc, Expression expr)
3471 : this (parent, loc, expr, null)
3474 public StatementSequence (Block parent, Location loc, Expression expr, string name,
3475 Expression type_expr, ArrayList a, bool isRetValRequired,
3476 bool isLeftHandSide)
3477 : this (parent, loc, expr, a)
3479 this.memberName = name;
3480 this.type_expr = type_expr;
3481 this.isRetValRequired = isRetValRequired;
3482 this.isLeftHandSide = isLeftHandSide;
3485 public StatementSequence (Block parent, Location loc, Expression expr, ArrayList a,
3486 bool isRetValRequired, bool isLeftHandSide)
3487 : this (parent, loc, expr, a)
3489 this.isRetValRequired = isRetValRequired;
3490 this.isLeftHandSide = isLeftHandSide;
3491 if (expr is MemberAccess) {
3492 this.expr = ((MemberAccess)expr).Expr;
3493 this.memberName = ((MemberAccess)expr).Identifier;
3494 this.isIndexerAccess = false;
3495 } else if (expr is IndexerAccess) {
3496 this.expr = ((IndexerAccess) expr).Instance;
3497 this.memberName = "";
3498 this.isIndexerAccess = true;
3502 public StatementSequence (Block parent, Location loc, Expression expr, ArrayList a)
3504 stmtBlock = new Block (parent);
3506 originalArgs = new ArrayList ();
3508 for (int index = 0; index < a.Count; index ++) {
3509 Argument argument = (Argument) args [index];
3510 originalArgs.Add (new Argument (argument.Expr, argument.ArgType));
3515 stmtBlock.IsLateBindingRequired = true;
3517 this.isRetValRequired = this.isLeftHandSide = false;
3518 this.memberName = "";
3519 this.type_expr = null;
3522 public ArrayList Arguments {
3531 public bool IsLeftHandSide {
3533 isLeftHandSide = value;
3537 public Block StmtBlock {
3543 public override Expression DoResolve (EmitContext ec)
3545 if (!stmtBlock.Resolve (ec))
3547 eclass = ExprClass.Value;
3548 type = TypeManager.object_type;
3552 public bool ResolveArguments (EmitContext ec) {
3554 bool argNamesFound = false;
3555 if (Arguments != null)
3557 for (int index = 0; index < Arguments.Count; index ++)
3559 Argument a = (Argument) Arguments [index];
3560 if (a.ParamName == null || a.ParamName == "") {
3561 if (argNamesFound) {
3562 Report.Error (30241, loc, "Named Argument expected");
3566 argNamesFound = true;
3567 if (a.ArgType == Argument.AType.NoArg)
3568 a = new Argument (Parser.DecomposeQI ("System.Reflection.Missing.Value", loc), Argument.AType.Expression);
3569 if (!a.Resolve (ec, loc))
3571 Arguments [index] = a;
3577 public void GenerateLateBindingStatements ()
3580 ArrayList arrayInitializers = new ArrayList ();
3581 ArrayList ArgumentNames = null;
3583 //arrayInitializers = new ArrayList ();
3584 argCount = args.Count;
3585 for (int index = 0; index < args.Count; index ++) {
3586 Argument a = (Argument) args [index];
3587 Expression argument = a.Expr;
3588 arrayInitializers.Add (argument);
3589 if (a.ParamName != null && a.ParamName != "") {
3590 if (ArgumentNames == null)
3591 ArgumentNames = new ArrayList ();
3592 ArgumentNames.Add (new StringLiteral (a.ParamName));
3597 // __LateBindingArgs = new Object () {arg1, arg2 ...}
3598 ArrayCreation new_expr = new ArrayCreation (Parser.DecomposeQI ("System.Object", loc), "[]", arrayInitializers, loc);
3599 Assign assign_stmt = null;
3601 LocalVariableReference v1 = new LocalVariableReference (stmtBlock, Block.lateBindingArgs, loc);
3602 assign_stmt = new Assign (v1, new_expr, loc);
3603 stmtBlock.AddStatement (new StatementExpression ((ExpressionStatement) assign_stmt, loc));
3604 // __LateBindingArgNames = new string () { argument names}
3605 LocalVariableReference v2 = null;
3606 if (ArgumentNames != null && ArgumentNames.Count > 0) {
3607 new_expr = new ArrayCreation (Parser.DecomposeQI ("System.String", loc), "[]", ArgumentNames, loc);
3608 v2 = new LocalVariableReference (stmtBlock, Block.lateBindingArgNames, loc);
3609 assign_stmt = new Assign (v2, new_expr, loc);
3610 stmtBlock.AddStatement (new StatementExpression ((ExpressionStatement) assign_stmt, loc));
3613 //string memName = "";
3614 //bool isIndexerAccess = true;
3616 ArrayList invocationArgs = new ArrayList ();
3617 if (isIndexerAccess || memberName == "") {
3618 invocationArgs.Add (new Argument (expr, Argument.AType.Expression));
3619 invocationArgs.Add (new Argument (v1, Argument.AType.Expression));
3620 invocationArgs.Add (new Argument (NullLiteral.Null, Argument.AType.Expression));
3621 Expression tmp = null;
3622 if (!isLeftHandSide)
3623 tmp = Parser.DecomposeQI ("Microsoft.VisualBasic.CompilerServices.LateBinding.LateIndexGet", loc);
3625 tmp = Parser.DecomposeQI ("Microsoft.VisualBasic.CompilerServices.LateBinding.LateIndexSet", loc);
3626 Invocation invStmt = new Invocation (tmp, invocationArgs, Location.Null);
3627 invStmt.IsLateBinding = true;
3628 stmtBlock.AddStatement (new StatementExpression ((ExpressionStatement) invStmt, loc));
3633 invocationArgs.Add (new Argument (expr, Argument.AType.Expression));
3635 invocationArgs.Add (new Argument (NullLiteral.Null, Argument.AType.Expression));
3636 if (type_expr != null)
3637 invocationArgs.Add (new Argument (type_expr, Argument.AType.Expression));
3639 invocationArgs.Add (new Argument (NullLiteral.Null, Argument.AType.Expression));
3640 invocationArgs.Add (new Argument (new StringLiteral (memberName), Argument.AType.Expression));
3641 invocationArgs.Add (new Argument (v1, Argument.AType.Expression));
3642 if (ArgumentNames != null && ArgumentNames.Count > 0)
3643 invocationArgs.Add (new Argument (v2, Argument.AType.Expression));
3645 invocationArgs.Add (new Argument (NullLiteral.Null, Argument.AType.Expression));
3647 // __LateBindingCopyBack = new Boolean (no_of_args) {}
3648 bool isCopyBackRequired = false;
3649 if (!isLeftHandSide) {
3650 for (int i = 0; i < argCount; i++) {
3651 Argument origArg = (Argument) Arguments [i];
3652 Expression origExpr = origArg.Expr;
3653 if (!(origExpr is Constant || origArg.ArgType == Argument.AType.NoArg))
3654 isCopyBackRequired = true;
3658 LocalVariableReference v3 = new LocalVariableReference (stmtBlock, Block.lateBindingCopyBack, loc);
3659 if (isCopyBackRequired) {
3660 ArrayList rank_specifier = new ArrayList ();
3661 rank_specifier.Add (new IntLiteral (argCount));
3662 arrayInitializers = new ArrayList ();
3663 for (int i = 0; i < argCount; i++) {
3664 Argument a = (Argument) Arguments [i];
3665 Expression origExpr = a.Expr;
3666 if (origExpr is Constant || a.ArgType == Argument.AType.NoArg || origExpr is New)
3667 arrayInitializers.Add (new BoolLiteral (false));
3669 arrayInitializers.Add (new BoolLiteral (true));
3672 new_expr = new ArrayCreation (Parser.DecomposeQI ("System.Boolean", loc), "[]", arrayInitializers, loc);
3673 assign_stmt = new Assign (v3, new_expr, loc);
3674 stmtBlock.AddStatement (new StatementExpression ((ExpressionStatement) assign_stmt, loc));
3675 invocationArgs.Add (new Argument (v3, Argument.AType.Expression));
3676 } else if (! isLeftHandSide) {
3677 invocationArgs.Add (new Argument (NullLiteral.Null, Argument.AType.Expression));
3680 Expression etmp = null;
3681 if (isLeftHandSide) {
3683 etmp = Parser.DecomposeQI ("Microsoft.VisualBasic.CompilerServices.LateBinding.LateSet", loc);
3684 } else if (isRetValRequired) {
3686 etmp = Parser.DecomposeQI ("Microsoft.VisualBasic.CompilerServices.LateBinding.LateGet", loc);
3688 etmp = Parser.DecomposeQI ("Microsoft.VisualBasic.CompilerServices.LateBinding.LateCall", loc);
3691 Invocation inv_stmt = new Invocation (etmp, invocationArgs, Location.Null);
3692 inv_stmt.IsLateBinding = true;
3693 stmtBlock.AddStatement (new StatementExpression ((ExpressionStatement) inv_stmt, loc));
3695 if (! isCopyBackRequired)
3698 for (int i = argCount - 1; i >= 0; i --) {
3699 Argument arg = (Argument) originalArgs [i];
3700 Expression origExpr = (Expression) arg.Expr;
3701 if (arg.ArgType == Argument.AType.NoArg)
3703 if (origExpr is Constant)
3705 if (origExpr is New)
3708 Expression intExpr = new IntLiteral (i);
3709 ArrayList argsLocal = new ArrayList ();
3710 argsLocal.Add (new Argument (intExpr, Argument.AType.Expression));
3711 Expression indexExpr = new Invocation (new SimpleName (Block.lateBindingCopyBack, loc), argsLocal, loc);
3712 Expression value = new Invocation (new SimpleName (Block.lateBindingArgs, loc), argsLocal, loc);
3713 assign_stmt = new Assign (origExpr, value, loc);
3714 Expression boolExpr = new Binary (Binary.Operator.Inequality, indexExpr, new BoolLiteral (false), loc);
3715 Statement ifStmt = new If (boolExpr, new StatementExpression ((ExpressionStatement) assign_stmt, loc), loc);
3716 stmtBlock.AddStatement (ifStmt);
3720 public override void Emit (EmitContext ec)
3722 stmtBlock.Emit (ec);
3726 public class SwitchLabel {
3727 public enum LabelType : byte {
3728 Operator, Range, Label, Else
3731 Expression label, start, end;
3732 LabelType label_type;
3733 Expression label_condition, start_condition, end_condition;
3734 Binary.Operator oper;
3735 public Location loc;
3736 public Label ILLabel;
3737 public Label ILLabelCode;
3740 // if expr == null, then it is the default case.
3742 public SwitchLabel (Expression start, Expression end, LabelType ltype, Binary.Operator oper, Location l) {
3745 this.label_type = ltype;
3748 label_condition = start_condition = end_condition = null;
3751 public SwitchLabel (Expression expr, LabelType ltype, Binary.Operator oper, Location l)
3755 label_condition = start_condition = end_condition = null;
3757 this.label_type = ltype;
3761 public Expression Label {
3767 public LabelType Type {
3773 public Expression ConditionStart {
3775 return start_condition;
3779 public Expression ConditionEnd {
3781 return end_condition;
3785 public Expression ConditionLabel {
3787 return label_condition;
3792 // Resolves the expression, reduces it to a literal if possible
3793 // and then converts it to the requested type.
3795 public bool ResolveAndReduce (EmitContext ec, Expression expr)
3797 ILLabel = ec.ig.DefineLabel ();
3798 ILLabelCode = ec.ig.DefineLabel ();
3800 Expression e = null;
3801 switch (label_type) {
3802 case LabelType.Label :
3805 e = label.Resolve (ec);
3807 e = Expression.ConvertImplicit (ec, e, expr.Type, loc);
3810 label_condition = new Binary (Binary.Operator.Equality, expr, e, loc);
3811 if ((label_condition = label_condition.DoResolve (ec)) == null)
3814 case LabelType.Operator :
3815 e = label.Resolve (ec);
3816 label_condition = new Binary (oper, expr, e, loc);
3817 if ((label_condition = label_condition.DoResolve (ec)) == null)
3820 case LabelType.Range :
3821 if (start == null || end == null)
3823 e = start.Resolve (ec);
3825 e = Expression.ConvertImplicit (ec, e, expr.Type, loc);
3828 start_condition = new Binary (Binary.Operator.GreaterThanOrEqual, expr, e, loc);
3829 start_condition = start_condition.Resolve (ec);
3830 e = end.Resolve (ec);
3832 e = Expression.ConvertImplicit (ec, e, expr.Type, loc);
3835 end_condition = new Binary (Binary.Operator.LessThanOrEqual, expr, e, loc);
3836 end_condition = end_condition.Resolve (ec);
3837 if (start_condition == null || end_condition == null)
3841 case LabelType.Else :
3848 public class SwitchSection {
3849 // An array of SwitchLabels.
3850 public readonly ArrayList Labels;
3851 public readonly Block Block;
3853 public SwitchSection (ArrayList labels, Block block)
3860 public class Switch : Statement {
3861 public readonly ArrayList Sections;
3862 public Expression Expr;
3865 /// Maps constants whose type type SwitchType to their SwitchLabels.
3867 public Hashtable Elements;
3870 /// The governing switch type
3872 public Type SwitchType;
3878 Label default_target;
3879 Expression new_expr;
3882 // The types allowed to be implicitly cast from
3883 // on the governing type
3885 //static Type [] allowed_types;
3887 public Switch (Expression e, ArrayList sects, Location l)
3894 public bool GotDefault {
3900 public Label DefaultTarget {
3902 return default_target;
3907 // Determines the governing type for a switch. The returned
3908 // expression might be the expression from the switch, or an
3909 // expression that includes any potential conversions to the
3910 // integral types or to string.
3912 Expression SwitchGoverningType (EmitContext ec, Type t)
3914 if (t == TypeManager.byte_type ||
3915 t == TypeManager.short_type ||
3916 t == TypeManager.int32_type ||
3917 t == TypeManager.int64_type ||
3918 t == TypeManager.decimal_type ||
3919 t == TypeManager.float_type ||
3920 t == TypeManager.double_type ||
3921 t == TypeManager.date_type ||
3922 t == TypeManager.char_type ||
3923 t == TypeManager.object_type ||
3924 t == TypeManager.string_type ||
3925 t == TypeManager.bool_type ||
3926 t.IsSubclassOf (TypeManager.enum_type))
3929 if (allowed_types == null){
3930 allowed_types = new Type [] {
3931 TypeManager.sbyte_type,
3932 TypeManager.byte_type,
3933 TypeManager.short_type,
3934 TypeManager.ushort_type,
3935 TypeManager.int32_type,
3936 TypeManager.uint32_type,
3937 TypeManager.int64_type,
3938 TypeManager.uint64_type,
3939 TypeManager.char_type,
3940 TypeManager.bool_type,
3941 TypeManager.string_type
3946 // Try to find a *user* defined implicit conversion.
3948 // If there is no implicit conversion, or if there are multiple
3949 // conversions, we have to report an error
3951 Expression converted = null;
3952 foreach (Type tt in allowed_types){
3955 e = Expression.ImplicitUserConversion (ec, Expr, tt, loc);
3959 if (converted != null){
3960 Report.Error (-12, loc, "More than one conversion to an integral " +
3961 " type exists for type `" +
3962 TypeManager.MonoBASIC_Name (Expr.Type)+"'");
3972 void error152 (string n)
3975 152, "The label `" + n + ":' " +
3976 "is already present on this switch statement");
3980 // Performs the basic sanity checks on the switch statement
3981 // (looks for duplicate keys and non-constant expressions).
3983 // It also returns a hashtable with the keys that we will later
3984 // use to compute the switch tables
3986 bool CheckSwitch (EmitContext ec)
3988 //Type compare_type;
3990 Elements = new CaseInsensitiveHashtable ();
3992 got_default = false;
3995 if (TypeManager.IsEnumType (SwitchType)){
3996 compare_type = TypeManager.EnumToUnderlying (SwitchType);
3998 compare_type = SwitchType;
4001 for (int secIndex = 0; secIndex < Sections.Count; secIndex ++) {
4002 SwitchSection ss = (SwitchSection) Sections [secIndex];
4003 for (int labelIndex = 0; labelIndex < ss.Labels.Count; labelIndex ++) {
4004 SwitchLabel sl = (SwitchLabel) ss.Labels [labelIndex];
4005 if (!sl.ResolveAndReduce (ec, Expr)){
4010 if (sl.Type == SwitchLabel.LabelType.Else){
4012 error152 ("default");
4026 void EmitObjectInteger (ILGenerator ig, object k)
4029 IntConstant.EmitInt (ig, (int) k);
4030 else if (k is Constant) {
4031 EmitObjectInteger (ig, ((Constant) k).GetValue ());
4034 IntConstant.EmitInt (ig, unchecked ((int) (uint) k));
4037 if ((long) k >= int.MinValue && (long) k <= int.MaxValue)
4039 IntConstant.EmitInt (ig, (int) (long) k);
4040 ig.Emit (OpCodes.Conv_I8);
4043 LongConstant.EmitLong (ig, (long) k);
4045 else if (k is ulong)
4047 if ((ulong) k < (1L<<32))
4049 IntConstant.EmitInt (ig, (int) (long) k);
4050 ig.Emit (OpCodes.Conv_U8);
4054 LongConstant.EmitLong (ig, unchecked ((long) (ulong) k));
4058 IntConstant.EmitInt (ig, (int) ((char) k));
4059 else if (k is sbyte)
4060 IntConstant.EmitInt (ig, (int) ((sbyte) k));
4062 IntConstant.EmitInt (ig, (int) ((byte) k));
4063 else if (k is short)
4064 IntConstant.EmitInt (ig, (int) ((short) k));
4065 else if (k is ushort)
4066 IntConstant.EmitInt (ig, (int) ((ushort) k));
4068 IntConstant.EmitInt (ig, ((bool) k) ? 1 : 0);
4070 throw new Exception ("Unhandled case");
4073 // structure used to hold blocks of keys while calculating table switch
4074 class KeyBlock : IComparable
4076 public KeyBlock (long _nFirst)
4078 nFirst = nLast = _nFirst;
4082 public ArrayList rgKeys = null;
4085 get { return (int) (nLast - nFirst + 1); }
4087 public static long TotalLength (KeyBlock kbFirst, KeyBlock kbLast)
4089 return kbLast.nLast - kbFirst.nFirst + 1;
4091 public int CompareTo (object obj)
4093 KeyBlock kb = (KeyBlock) obj;
4094 int nLength = Length;
4095 int nLengthOther = kb.Length;
4096 if (nLengthOther == nLength)
4097 return (int) (kb.nFirst - nFirst);
4098 return nLength - nLengthOther;
4104 /// This method emits code for a lookup-based switch statement (non-string)
4105 /// Basically it groups the cases into blocks that are at least half full,
4106 /// and then spits out individual lookup opcodes for each block.
4107 /// It emits the longest blocks first, and short blocks are just
4108 /// handled with direct compares.
4110 /// <param name="ec"></param>
4111 /// <param name="val"></param>
4112 /// <returns></returns>
4113 bool TableSwitchEmit (EmitContext ec, LocalBuilder val)
4115 int cElements = Elements.Count;
4116 object [] rgKeys = new object [cElements];
4117 Elements.Keys.CopyTo (rgKeys, 0);
4118 Array.Sort (rgKeys);
4120 // initialize the block list with one element per key
4121 ArrayList rgKeyBlocks = new ArrayList ();
4122 foreach (object key in rgKeys)
4123 rgKeyBlocks.Add (new KeyBlock (Convert.ToInt64 (key)));
4126 // iteratively merge the blocks while they are at least half full
4127 // there's probably a really cool way to do this with a tree...
4128 while (rgKeyBlocks.Count > 1)
4130 ArrayList rgKeyBlocksNew = new ArrayList ();
4131 kbCurr = (KeyBlock) rgKeyBlocks [0];
4132 for (int ikb = 1; ikb < rgKeyBlocks.Count; ikb++)
4134 KeyBlock kb = (KeyBlock) rgKeyBlocks [ikb];
4135 if ((kbCurr.Length + kb.Length) * 2 >= KeyBlock.TotalLength (kbCurr, kb))
4138 kbCurr.nLast = kb.nLast;
4142 // start a new block
4143 rgKeyBlocksNew.Add (kbCurr);
4147 rgKeyBlocksNew.Add (kbCurr);
4148 if (rgKeyBlocks.Count == rgKeyBlocksNew.Count)
4150 rgKeyBlocks = rgKeyBlocksNew;
4153 // initialize the key lists
4154 foreach (KeyBlock kb in rgKeyBlocks)
4155 kb.rgKeys = new ArrayList ();
4157 // fill the key lists
4159 if (rgKeyBlocks.Count > 0) {
4160 kbCurr = (KeyBlock) rgKeyBlocks [0];
4161 foreach (object key in rgKeys)
4163 bool fNextBlock = (key is UInt64) ? (ulong) key > (ulong) kbCurr.nLast : Convert.ToInt64 (key) > kbCurr.nLast;
4165 kbCurr = (KeyBlock) rgKeyBlocks [++iBlockCurr];
4166 kbCurr.rgKeys.Add (key);
4170 // sort the blocks so we can tackle the largest ones first
4171 rgKeyBlocks.Sort ();
4173 // okay now we can start...
4174 ILGenerator ig = ec.ig;
4175 Label lblEnd = ig.DefineLabel (); // at the end ;-)
4176 Label lblDefault = ig.DefineLabel ();
4178 Type typeKeys = null;
4179 if (rgKeys.Length > 0)
4180 typeKeys = rgKeys [0].GetType (); // used for conversions
4182 for (int iBlock = rgKeyBlocks.Count - 1; iBlock >= 0; --iBlock)
4184 KeyBlock kb = ((KeyBlock) rgKeyBlocks [iBlock]);
4185 lblDefault = (iBlock == 0) ? DefaultTarget : ig.DefineLabel ();
4188 foreach (object key in kb.rgKeys)
4190 ig.Emit (OpCodes.Ldloc, val);
4191 EmitObjectInteger (ig, key);
4192 SwitchLabel sl = (SwitchLabel) Elements [key];
4193 ig.Emit (OpCodes.Beq, sl.ILLabel);
4198 // TODO: if all the keys in the block are the same and there are
4199 // no gaps/defaults then just use a range-check.
4200 if (SwitchType == TypeManager.int64_type ||
4201 SwitchType == TypeManager.uint64_type)
4203 // TODO: optimize constant/I4 cases
4205 // check block range (could be > 2^31)
4206 ig.Emit (OpCodes.Ldloc, val);
4207 EmitObjectInteger (ig, Convert.ChangeType (kb.nFirst, typeKeys));
4208 ig.Emit (OpCodes.Blt, lblDefault);
4209 ig.Emit (OpCodes.Ldloc, val);
4210 EmitObjectInteger (ig, Convert.ChangeType (kb.nFirst, typeKeys));
4211 ig.Emit (OpCodes.Bgt, lblDefault);
4214 ig.Emit (OpCodes.Ldloc, val);
4217 EmitObjectInteger (ig, Convert.ChangeType (kb.nFirst, typeKeys));
4218 ig.Emit (OpCodes.Sub);
4220 ig.Emit (OpCodes.Conv_I4); // assumes < 2^31 labels!
4225 ig.Emit (OpCodes.Ldloc, val);
4226 int nFirst = (int) kb.nFirst;
4229 IntConstant.EmitInt (ig, nFirst);
4230 ig.Emit (OpCodes.Sub);
4232 else if (nFirst < 0)
4234 IntConstant.EmitInt (ig, -nFirst);
4235 ig.Emit (OpCodes.Add);
4239 // first, build the list of labels for the switch
4241 int cJumps = kb.Length;
4242 Label [] rgLabels = new Label [cJumps];
4243 for (int iJump = 0; iJump < cJumps; iJump++)
4245 object key = kb.rgKeys [iKey];
4246 if (Convert.ToInt64 (key) == kb.nFirst + iJump)
4248 SwitchLabel sl = (SwitchLabel) Elements [key];
4249 rgLabels [iJump] = sl.ILLabel;
4253 rgLabels [iJump] = lblDefault;
4255 // emit the switch opcode
4256 ig.Emit (OpCodes.Switch, rgLabels);
4259 // mark the default for this block
4261 ig.MarkLabel (lblDefault);
4264 // TODO: find the default case and emit it here,
4265 // to prevent having to do the following jump.
4266 // make sure to mark other labels in the default section
4268 // the last default just goes to the end
4269 ig.Emit (OpCodes.Br, lblDefault);
4271 // now emit the code for the sections
4272 bool fFoundDefault = false;
4273 bool fAllReturn = true;
4274 foreach (SwitchSection ss in Sections)
4276 foreach (SwitchLabel sl in ss.Labels)
4278 ig.MarkLabel (sl.ILLabel);
4279 ig.MarkLabel (sl.ILLabelCode);
4280 if (sl.Label == null)
4282 ig.MarkLabel (lblDefault);
4283 fFoundDefault = true;
4286 bool returns = ss.Block.Emit (ec);
4287 fAllReturn &= returns;
4288 //ig.Emit (OpCodes.Br, lblEnd);
4291 if (!fFoundDefault) {
4292 ig.MarkLabel (lblDefault);
4295 ig.MarkLabel (lblEnd);
4300 // This simple emit switch works, but does not take advantage of the
4302 // TODO: remove non-string logic from here
4303 // TODO: binary search strings?
4305 bool SimpleSwitchEmit (EmitContext ec, LocalBuilder val)
4307 ILGenerator ig = ec.ig;
4308 Label end_of_switch = ig.DefineLabel ();
4309 Label next_test = ig.DefineLabel ();
4310 Label null_target = ig.DefineLabel ();
4311 bool default_found = false;
4312 bool first_test = true;
4313 bool pending_goto_end = false;
4314 bool all_return = true;
4315 bool is_string = false;
4319 // Special processing for strings: we cant compare
4322 if (SwitchType == TypeManager.string_type){
4323 ig.Emit (OpCodes.Ldloc, val);
4326 if (Elements.Contains (NullLiteral.Null)){
4327 ig.Emit (OpCodes.Brfalse, null_target);
4329 ig.Emit (OpCodes.Brfalse, default_target);
4331 ig.Emit (OpCodes.Ldloc, val);
4332 ig.Emit (OpCodes.Call, TypeManager.string_isinterneted_string);
4333 ig.Emit (OpCodes.Stloc, val);
4336 foreach (SwitchSection ss in Sections){
4337 Label sec_begin = ig.DefineLabel ();
4339 if (pending_goto_end)
4340 ig.Emit (OpCodes.Br, end_of_switch);
4342 int label_count = ss.Labels.Count;
4344 foreach (SwitchLabel sl in ss.Labels){
4345 ig.MarkLabel (sl.ILLabel);
4348 ig.MarkLabel (next_test);
4349 next_test = ig.DefineLabel ();
4352 // If we are the default target
4354 if (sl.Label == null){
4355 ig.MarkLabel (default_target);
4356 default_found = true;
4358 object lit = sl.Converted;
4360 if (lit is NullLiteral){
4362 if (label_count == 1)
4363 ig.Emit (OpCodes.Br, next_test);
4368 StringConstant str = (StringConstant) lit;
4370 ig.Emit (OpCodes.Ldloc, val);
4371 ig.Emit (OpCodes.Ldstr, str.Value);
4372 if (label_count == 1)
4373 ig.Emit (OpCodes.Bne_Un, next_test);
4375 ig.Emit (OpCodes.Beq, sec_begin);
4377 ig.Emit (OpCodes.Ldloc, val);
4378 EmitObjectInteger (ig, lit);
4379 ig.Emit (OpCodes.Ceq);
4380 if (label_count == 1)
4381 ig.Emit (OpCodes.Brfalse, next_test);
4383 ig.Emit (OpCodes.Brtrue, sec_begin);
4387 if (label_count != 1)
4388 ig.Emit (OpCodes.Br, next_test);
4391 ig.MarkLabel (null_target);
4392 ig.MarkLabel (sec_begin);
4393 foreach (SwitchLabel sl in ss.Labels)
4394 ig.MarkLabel (sl.ILLabelCode);
4396 bool returns = ss.Block.Emit (ec);
4398 pending_goto_end = false;
4401 pending_goto_end = true;
4405 if (!default_found){
4406 ig.MarkLabel (default_target);
4409 ig.MarkLabel (next_test);
4410 ig.MarkLabel (end_of_switch);
4416 public override bool Resolve (EmitContext ec)
4418 Expr = Expr.Resolve (ec);
4422 new_expr = SwitchGoverningType (ec, Expr.Type);
4423 if (new_expr == null){
4424 Report.Error (30338, loc, "'Select' expression cannot be of type '" + Expr.Type +"'");
4429 SwitchType = new_expr.Type;
4431 if (!CheckSwitch (ec))
4434 Switch old_switch = ec.Switch;
4436 ec.Switch.SwitchType = SwitchType;
4438 ec.StartFlowBranching (FlowBranchingType.SWITCH, loc);
4441 foreach (SwitchSection ss in Sections){
4443 ec.CurrentBranching.CreateSibling ();
4447 if (ss.Block.Resolve (ec) != true)
4453 ec.CurrentBranching.CreateSibling ();
4455 ec.EndFlowBranching ();
4456 ec.Switch = old_switch;
4461 protected override bool DoEmit (EmitContext ec)
4463 ILGenerator ig = ec.ig;
4465 // Setup the codegen context
4467 Label old_end = ec.LoopEnd;
4468 Switch old_switch = ec.Switch;
4470 ec.LoopEnd = ig.DefineLabel ();
4473 for (int secIndex = 0; secIndex < Sections.Count; secIndex ++) {
4474 SwitchSection section = (SwitchSection) Sections [secIndex];
4475 Label sLabel = ig.DefineLabel ();
4476 Label lLabel = ig.DefineLabel ();
4477 ArrayList Labels = section.Labels;
4478 for (int labelIndex = 0; labelIndex < Labels.Count; labelIndex ++) {
4479 SwitchLabel sl = (SwitchLabel) Labels [labelIndex];
4481 case SwitchLabel.LabelType.Range :
4482 if (labelIndex + 1 == Labels.Count) {
4483 EmitBoolExpression (ec, sl.ConditionStart, sLabel, false);
4484 EmitBoolExpression (ec, sl.ConditionEnd, sLabel, false);
4485 ig.Emit (OpCodes.Br, lLabel);
4487 Label newLabel = ig.DefineLabel ();
4488 EmitBoolExpression (ec, sl.ConditionStart, newLabel, false);
4489 EmitBoolExpression (ec, sl.ConditionEnd, newLabel, false);
4490 ig.Emit (OpCodes.Br, lLabel);
4491 ig.MarkLabel (newLabel);
4494 case SwitchLabel.LabelType.Else :
4495 // Nothing to be done here
4497 case SwitchLabel.LabelType.Operator :
4498 EmitBoolExpression (ec, sl.ConditionLabel, lLabel, true);
4499 if (labelIndex + 1 == Labels.Count)
4500 ig.Emit (OpCodes.Br, sLabel);
4502 case SwitchLabel.LabelType.Label :
4503 EmitBoolExpression (ec, sl.ConditionLabel, lLabel, true);
4504 if (labelIndex + 1 == Labels.Count)
4505 ig.Emit (OpCodes.Br, sLabel);
4510 ig.MarkLabel (lLabel);
4511 section.Block.Emit (ec);
4512 ig.MarkLabel (sLabel);
4515 // Restore context state.
4516 ig.MarkLabel (ec.LoopEnd);
4519 // Restore the previous context
4521 ec.LoopEnd = old_end;
4522 ec.Switch = old_switch;
4527 public class Lock : Statement {
4529 Statement Statement;
4531 public Lock (Expression expr, Statement stmt, Location l)
4538 public override bool Resolve (EmitContext ec)
4540 expr = expr.Resolve (ec);
4541 return Statement.Resolve (ec) && expr != null;
4544 protected override bool DoEmit (EmitContext ec)
4546 Type type = expr.Type;
4549 if (type.IsValueType){
4550 Report.Error (30582, loc, "lock statement requires the expression to be " +
4551 " a reference type (type is: `" +
4552 TypeManager.MonoBASIC_Name (type) + "'");
4556 ILGenerator ig = ec.ig;
4557 LocalBuilder temp = ig.DeclareLocal (type);
4560 ig.Emit (OpCodes.Dup);
4561 ig.Emit (OpCodes.Stloc, temp);
4562 ig.Emit (OpCodes.Call, TypeManager.void_monitor_enter_object);
4565 ig.BeginExceptionBlock ();
4566 bool old_in_try = ec.InTry;
4568 Label finish = ig.DefineLabel ();
4569 val = Statement.Emit (ec);
4570 ec.InTry = old_in_try;
4571 // ig.Emit (OpCodes.Leave, finish);
4573 ig.MarkLabel (finish);
4576 ig.BeginFinallyBlock ();
4577 ig.Emit (OpCodes.Ldloc, temp);
4578 ig.Emit (OpCodes.Call, TypeManager.void_monitor_exit_object);
4579 ig.EndExceptionBlock ();
4585 public class Unchecked : Statement {
4586 public readonly Block Block;
4588 public Unchecked (Block b)
4593 public override bool Resolve (EmitContext ec)
4595 return Block.Resolve (ec);
4598 protected override bool DoEmit (EmitContext ec)
4600 bool previous_state = ec.CheckState;
4601 bool previous_state_const = ec.ConstantCheckState;
4604 ec.CheckState = false;
4605 ec.ConstantCheckState = false;
4606 val = Block.Emit (ec);
4607 ec.CheckState = previous_state;
4608 ec.ConstantCheckState = previous_state_const;
4614 public class Checked : Statement {
4615 public readonly Block Block;
4617 public Checked (Block b)
4622 public override bool Resolve (EmitContext ec)
4624 bool previous_state = ec.CheckState;
4625 bool previous_state_const = ec.ConstantCheckState;
4627 ec.CheckState = true;
4628 ec.ConstantCheckState = true;
4629 bool ret = Block.Resolve (ec);
4630 ec.CheckState = previous_state;
4631 ec.ConstantCheckState = previous_state_const;
4636 protected override bool DoEmit (EmitContext ec)
4638 bool previous_state = ec.CheckState;
4639 bool previous_state_const = ec.ConstantCheckState;
4642 ec.CheckState = true;
4643 ec.ConstantCheckState = true;
4644 val = Block.Emit (ec);
4645 ec.CheckState = previous_state;
4646 ec.ConstantCheckState = previous_state_const;
4652 public class Unsafe : Statement {
4653 public readonly Block Block;
4655 public Unsafe (Block b)
4660 public override bool Resolve (EmitContext ec)
4662 bool previous_state = ec.InUnsafe;
4666 val = Block.Resolve (ec);
4667 ec.InUnsafe = previous_state;
4672 protected override bool DoEmit (EmitContext ec)
4674 bool previous_state = ec.InUnsafe;
4678 val = Block.Emit (ec);
4679 ec.InUnsafe = previous_state;
4688 public class Fixed : Statement {
4690 ArrayList declarators;
4691 Statement statement;
4696 public bool is_object;
4697 public VariableInfo vi;
4698 public Expression expr;
4699 public Expression converted;
4702 public Fixed (Expression type, ArrayList decls, Statement stmt, Location l)
4705 declarators = decls;
4710 public override bool Resolve (EmitContext ec)
4712 expr_type = ec.DeclSpace.ResolveType (type, false, loc);
4713 if (expr_type == null)
4716 data = new FixedData [declarators.Count];
4719 foreach (Pair p in declarators){
4720 VariableInfo vi = (VariableInfo) p.First;
4721 Expression e = (Expression) p.Second;
4726 // The rules for the possible declarators are pretty wise,
4727 // but the production on the grammar is more concise.
4729 // So we have to enforce these rules here.
4731 // We do not resolve before doing the case 1 test,
4732 // because the grammar is explicit in that the token &
4733 // is present, so we need to test for this particular case.
4737 // Case 1: & object.
4739 if (e is Unary && ((Unary) e).Oper == Unary.Operator.AddressOf){
4740 Expression child = ((Unary) e).Expr;
4743 if (child is ParameterReference || child is LocalVariableReference){
4746 "No need to use fixed statement for parameters or " +
4747 "local variable declarations (address is already " +
4756 child = ((Unary) e).Expr;
4758 if (!TypeManager.VerifyUnManaged (child.Type, loc))
4761 data [i].is_object = true;
4763 data [i].converted = null;
4777 if (e.Type.IsArray){
4778 Type array_type = e.Type.GetElementType ();
4782 // Provided that array_type is unmanaged,
4784 if (!TypeManager.VerifyUnManaged (array_type, loc))
4788 // and T* is implicitly convertible to the
4789 // pointer type given in the fixed statement.
4791 ArrayPtr array_ptr = new ArrayPtr (e, loc);
4793 Expression converted = Expression.ConvertImplicitRequired (
4794 ec, array_ptr, vi.VariableType, loc);
4795 if (converted == null)
4798 data [i].is_object = false;
4800 data [i].converted = converted;
4810 if (e.Type == TypeManager.string_type){
4811 data [i].is_object = false;
4813 data [i].converted = null;
4819 return statement.Resolve (ec);
4822 protected override bool DoEmit (EmitContext ec)
4824 ILGenerator ig = ec.ig;
4826 bool is_ret = false;
4828 for (int i = 0; i < data.Length; i++) {
4829 VariableInfo vi = data [i].vi;
4832 // Case 1: & object.
4834 if (data [i].is_object) {
4836 // Store pointer in pinned location
4838 data [i].expr.Emit (ec);
4839 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
4841 is_ret = statement.Emit (ec);
4843 // Clear the pinned variable.
4844 ig.Emit (OpCodes.Ldc_I4_0);
4845 ig.Emit (OpCodes.Conv_U);
4846 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
4854 if (data [i].expr.Type.IsArray){
4856 // Store pointer in pinned location
4858 data [i].converted.Emit (ec);
4860 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
4862 is_ret = statement.Emit (ec);
4864 // Clear the pinned variable.
4865 ig.Emit (OpCodes.Ldc_I4_0);
4866 ig.Emit (OpCodes.Conv_U);
4867 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
4875 if (data [i].expr.Type == TypeManager.string_type){
4876 LocalBuilder pinned_string = ig.DeclareLocal (TypeManager.string_type);
4877 TypeManager.MakePinned (pinned_string);
4879 data [i].expr.Emit (ec);
4880 ig.Emit (OpCodes.Stloc, pinned_string);
4882 Expression sptr = new StringPtr (pinned_string, loc);
4883 Expression converted = Expression.ConvertImplicitRequired (
4884 ec, sptr, vi.VariableType, loc);
4886 if (converted == null)
4889 converted.Emit (ec);
4890 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
4892 is_ret = statement.Emit (ec);
4894 // Clear the pinned variable
4895 ig.Emit (OpCodes.Ldnull);
4896 ig.Emit (OpCodes.Stloc, pinned_string);
4904 public class Catch {
4905 public readonly string Name;
4906 public readonly Block Block;
4907 public Expression Clause;
4908 public readonly Location Location;
4910 Expression type_expr;
4911 //Expression clus_expr;
4914 public Catch (Expression type, string name, Block block, Expression clause, Location l)
4923 public Type CatchType {
4929 public bool IsGeneral {
4931 return type_expr == null;
4935 public bool Resolve (EmitContext ec)
4937 if (type_expr != null) {
4938 type = ec.DeclSpace.ResolveType (type_expr, false, Location);
4942 if (type != TypeManager.exception_type && !type.IsSubclassOf (TypeManager.exception_type)){
4943 Report.Error (30665, Location,
4944 "The type caught or thrown must be derived " +
4945 "from System.Exception");
4951 if (Clause != null) {
4952 Clause = Statement.ResolveBoolean (ec, Clause, Location);
4953 if (Clause == null) {
4958 if (!Block.Resolve (ec))
4965 public class Try : Statement {
4966 public readonly Block Fini, Block;
4967 public readonly ArrayList Specific;
4968 public readonly Catch General;
4971 // specific, general and fini might all be null.
4973 public Try (Block block, ArrayList specific, Catch general, Block fini, Location l)
4975 if (specific == null && general == null){
4976 Console.WriteLine ("CIR.Try: Either specific or general have to be non-null");
4980 this.Specific = specific;
4981 this.General = general;
4986 public override bool Resolve (EmitContext ec)
4990 ec.StartFlowBranching (FlowBranchingType.EXCEPTION, Block.StartLocation);
4992 Report.Debug (1, "START OF TRY BLOCK", Block.StartLocation);
4994 bool old_in_try = ec.InTry;
4997 if (!Block.Resolve (ec))
5000 ec.InTry = old_in_try;
5002 FlowBranching.UsageVector vector = ec.CurrentBranching.CurrentUsageVector;
5004 Report.Debug (1, "START OF CATCH BLOCKS", vector);
5006 foreach (Catch c in Specific){
5007 ec.CurrentBranching.CreateSibling ();
5008 Report.Debug (1, "STARTED SIBLING FOR CATCH", ec.CurrentBranching);
5010 if (c.Name != null) {
5011 VariableInfo vi = c.Block.GetVariableInfo (c.Name);
5013 throw new Exception ();
5018 bool old_in_catch = ec.InCatch;
5021 if (!c.Resolve (ec))
5024 ec.InCatch = old_in_catch;
5026 FlowBranching.UsageVector current = ec.CurrentBranching.CurrentUsageVector;
5028 if (!current.AlwaysReturns && !current.AlwaysBreaks)
5029 vector.AndLocals (current);
5032 Report.Debug (1, "END OF CATCH BLOCKS", ec.CurrentBranching);
5034 if (General != null){
5035 ec.CurrentBranching.CreateSibling ();
5036 Report.Debug (1, "STARTED SIBLING FOR GENERAL", ec.CurrentBranching);
5038 bool old_in_catch = ec.InCatch;
5041 if (!General.Resolve (ec))
5044 ec.InCatch = old_in_catch;
5046 FlowBranching.UsageVector current = ec.CurrentBranching.CurrentUsageVector;
5048 if (!current.AlwaysReturns && !current.AlwaysBreaks)
5049 vector.AndLocals (current);
5052 Report.Debug (1, "END OF GENERAL CATCH BLOCKS", ec.CurrentBranching);
5055 ec.CurrentBranching.CreateSiblingForFinally ();
5056 Report.Debug (1, "STARTED SIBLING FOR FINALLY", ec.CurrentBranching, vector);
5058 bool old_in_finally = ec.InFinally;
5059 ec.InFinally = true;
5061 if (!Fini.Resolve (ec))
5064 ec.InFinally = old_in_finally;
5067 FlowReturns returns = ec.EndFlowBranching ();
5069 FlowBranching.UsageVector f_vector = ec.CurrentBranching.CurrentUsageVector;
5071 Report.Debug (1, "END OF FINALLY", ec.CurrentBranching, returns, vector, f_vector);
5072 ec.CurrentBranching.CurrentUsageVector.Or (vector);
5074 Report.Debug (1, "END OF TRY", ec.CurrentBranching);
5079 protected override bool DoEmit (EmitContext ec)
5081 ILGenerator ig = ec.ig;
5082 Label finish = ig.DefineLabel ();;
5086 ig.BeginExceptionBlock ();
5087 bool old_in_try = ec.InTry;
5089 returns = Block.Emit (ec);
5090 ec.InTry = old_in_try;
5093 // System.Reflection.Emit provides this automatically:
5094 // ig.Emit (OpCodes.Leave, finish);
5096 bool old_in_catch = ec.InCatch;
5098 //DeclSpace ds = ec.DeclSpace;
5100 foreach (Catch c in Specific){
5103 ig.BeginCatchBlock (c.CatchType);
5105 if (c.Name != null){
5106 vi = c.Block.GetVariableInfo (c.Name);
5108 throw new Exception ("Variable does not exist in this block");
5110 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
5112 ig.Emit (OpCodes.Pop);
5115 // if when clause is there
5117 if (c.Clause != null) {
5118 if (c.Clause is BoolConstant) {
5119 bool take = ((BoolConstant) c.Clause).Value;
5122 if (!c.Block.Emit (ec))
5125 EmitBoolExpression (ec, c.Clause, finish, false);
5126 if (!c.Block.Emit (ec))
5130 if (!c.Block.Emit (ec))
5134 if (General != null){
5135 ig.BeginCatchBlock (TypeManager.object_type);
5136 ig.Emit (OpCodes.Pop);
5138 if (General.Clause != null) {
5139 if (General.Clause is BoolConstant) {
5140 bool take = ((BoolConstant) General.Clause).Value;
5142 if (!General.Block.Emit (ec))
5145 EmitBoolExpression (ec, General.Clause, finish, false);
5146 if (!General.Block.Emit (ec))
5150 if (!General.Block.Emit (ec))
5154 ec.InCatch = old_in_catch;
5156 ig.MarkLabel (finish);
5158 ig.BeginFinallyBlock ();
5159 bool old_in_finally = ec.InFinally;
5160 ec.InFinally = true;
5162 ec.InFinally = old_in_finally;
5165 ig.EndExceptionBlock ();
5168 if (!returns || ec.InTry || ec.InCatch)
5171 // Unfortunately, System.Reflection.Emit automatically emits a leave
5172 // to the end of the finally block. This is a problem if `returns'
5173 // is true since we may jump to a point after the end of the method.
5174 // As a workaround, emit an explicit ret here.
5176 if (ec.ReturnType != null)
5177 ec.ig.Emit (OpCodes.Ldloc, ec.TemporaryReturn ());
5178 ec.ig.Emit (OpCodes.Ret);
5184 public class Using : Statement {
5185 object expression_or_block;
5186 Statement Statement;
5191 Expression [] converted_vars;
5192 ExpressionStatement [] assign;
5194 public Using (object expression_or_block, Statement stmt, Location l)
5196 this.expression_or_block = expression_or_block;
5202 // Resolves for the case of using using a local variable declaration.
5204 bool ResolveLocalVariableDecls (EmitContext ec)
5206 bool need_conv = false;
5207 expr_type = ec.DeclSpace.ResolveType (expr, false, loc);
5210 if (expr_type == null)
5214 // The type must be an IDisposable or an implicit conversion
5217 converted_vars = new Expression [var_list.Count];
5218 assign = new ExpressionStatement [var_list.Count];
5219 if (!TypeManager.ImplementsInterface (expr_type, TypeManager.idisposable_type)){
5220 foreach (DictionaryEntry e in var_list){
5221 Expression var = (Expression) e.Key;
5223 var = var.ResolveLValue (ec, new EmptyExpression ());
5227 converted_vars [i] = Expression.ConvertImplicitRequired (
5228 ec, var, TypeManager.idisposable_type, loc);
5230 if (converted_vars [i] == null)
5238 foreach (DictionaryEntry e in var_list){
5239 LocalVariableReference var = (LocalVariableReference) e.Key;
5240 Expression new_expr = (Expression) e.Value;
5243 a = new Assign (var, new_expr, loc);
5249 converted_vars [i] = var;
5250 assign [i] = (ExpressionStatement) a;
5257 bool ResolveExpression (EmitContext ec)
5259 if (!TypeManager.ImplementsInterface (expr_type, TypeManager.idisposable_type)){
5260 conv = Expression.ConvertImplicitRequired (
5261 ec, expr, TypeManager.idisposable_type, loc);
5271 // Emits the code for the case of using using a local variable declaration.
5273 bool EmitLocalVariableDecls (EmitContext ec)
5275 ILGenerator ig = ec.ig;
5278 bool old_in_try = ec.InTry;
5280 for (i = 0; i < assign.Length; i++) {
5281 assign [i].EmitStatement (ec);
5283 ig.BeginExceptionBlock ();
5285 Statement.Emit (ec);
5286 ec.InTry = old_in_try;
5288 bool old_in_finally = ec.InFinally;
5289 ec.InFinally = true;
5290 var_list.Reverse ();
5291 foreach (DictionaryEntry e in var_list){
5292 LocalVariableReference var = (LocalVariableReference) e.Key;
5293 Label skip = ig.DefineLabel ();
5296 ig.BeginFinallyBlock ();
5299 ig.Emit (OpCodes.Brfalse, skip);
5300 converted_vars [i].Emit (ec);
5301 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
5302 ig.MarkLabel (skip);
5303 ig.EndExceptionBlock ();
5305 ec.InFinally = old_in_finally;
5310 bool EmitExpression (EmitContext ec)
5313 // Make a copy of the expression and operate on that.
5315 ILGenerator ig = ec.ig;
5316 LocalBuilder local_copy = ig.DeclareLocal (expr_type);
5321 ig.Emit (OpCodes.Stloc, local_copy);
5323 bool old_in_try = ec.InTry;
5325 ig.BeginExceptionBlock ();
5326 Statement.Emit (ec);
5327 ec.InTry = old_in_try;
5329 Label skip = ig.DefineLabel ();
5330 bool old_in_finally = ec.InFinally;
5331 ig.BeginFinallyBlock ();
5332 ig.Emit (OpCodes.Ldloc, local_copy);
5333 ig.Emit (OpCodes.Brfalse, skip);
5334 ig.Emit (OpCodes.Ldloc, local_copy);
5335 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
5336 ig.MarkLabel (skip);
5337 ec.InFinally = old_in_finally;
5338 ig.EndExceptionBlock ();
5343 public override bool Resolve (EmitContext ec)
5345 if (expression_or_block is DictionaryEntry){
5346 expr = (Expression) ((DictionaryEntry) expression_or_block).Key;
5347 var_list = (ArrayList)((DictionaryEntry)expression_or_block).Value;
5349 if (!ResolveLocalVariableDecls (ec))
5352 } else if (expression_or_block is Expression){
5353 expr = (Expression) expression_or_block;
5355 expr = expr.Resolve (ec);
5359 expr_type = expr.Type;
5361 if (!ResolveExpression (ec))
5365 return Statement.Resolve (ec);
5368 protected override bool DoEmit (EmitContext ec)
5370 if (expression_or_block is DictionaryEntry)
5371 return EmitLocalVariableDecls (ec);
5372 else if (expression_or_block is Expression)
5373 return EmitExpression (ec);
5380 /// Implementation of the for each statement
5382 public class Foreach : Statement {
5384 LocalVariableReference variable;
5386 Statement statement;
5387 ForeachHelperMethods hm;
5388 Expression empty, conv;
5389 Type array_type, element_type;
5392 public Foreach (Expression type, LocalVariableReference var, Expression expr,
5393 Statement stmt, Location l)
5400 VariableInfo vi = var.VariableInfo;
5401 this.type = vi.Type;
5403 this.variable = var;
5409 public override bool Resolve (EmitContext ec)
5411 expr = expr.Resolve (ec);
5415 var_type = ec.DeclSpace.ResolveType (type, false, loc);
5416 if (var_type == null)
5420 // We need an instance variable. Not sure this is the best
5421 // way of doing this.
5423 // FIXME: When we implement propertyaccess, will those turn
5424 // out to return values in ExprClass? I think they should.
5426 if (!(expr.eclass == ExprClass.Variable || expr.eclass == ExprClass.Value ||
5427 expr.eclass == ExprClass.PropertyAccess || expr.eclass == ExprClass.IndexerAccess)){
5428 error1579 (expr.Type);
5432 if (expr.Type.IsArray) {
5433 array_type = expr.Type;
5434 element_type = array_type.GetElementType ();
5436 empty = new EmptyExpression (element_type);
5438 hm = ProbeCollectionType (ec, expr.Type);
5440 error1579 (expr.Type);
5444 array_type = expr.Type;
5445 element_type = hm.element_type;
5447 empty = new EmptyExpression (hm.element_type);
5450 ec.StartFlowBranching (FlowBranchingType.LOOP_BLOCK, loc);
5451 ec.CurrentBranching.CreateSibling ();
5455 // FIXME: maybe we can apply the same trick we do in the
5456 // array handling to avoid creating empty and conv in some cases.
5458 // Although it is not as important in this case, as the type
5459 // will not likely be object (what the enumerator will return).
5461 conv = Expression.ConvertExplicit (ec, empty, var_type, false, loc);
5465 if (variable.ResolveLValue (ec, empty) == null)
5468 if (!statement.Resolve (ec))
5471 //FlowReturns returns = ec.EndFlowBranching ();
5472 ec.EndFlowBranching ();
5477 // Retrieves a `public bool MoveNext ()' method from the Type `t'
5479 static MethodInfo FetchMethodMoveNext (Type t)
5481 MemberList move_next_list;
5483 move_next_list = TypeContainer.FindMembers (
5484 t, MemberTypes.Method,
5485 BindingFlags.Public | BindingFlags.Instance,
5486 Type.FilterName, "MoveNext");
5487 if (move_next_list.Count == 0)
5490 foreach (MemberInfo m in move_next_list){
5491 MethodInfo mi = (MethodInfo) m;
5494 args = TypeManager.GetArgumentTypes (mi);
5495 if (args != null && args.Length == 0){
5496 if (mi.ReturnType == TypeManager.bool_type)
5504 // Retrieves a `public T get_Current ()' method from the Type `t'
5506 static MethodInfo FetchMethodGetCurrent (Type t)
5508 MemberList move_next_list;
5510 move_next_list = TypeContainer.FindMembers (
5511 t, MemberTypes.Method,
5512 BindingFlags.Public | BindingFlags.Instance,
5513 Type.FilterName, "get_Current");
5514 if (move_next_list.Count == 0)
5517 foreach (MemberInfo m in move_next_list){
5518 MethodInfo mi = (MethodInfo) m;
5521 args = TypeManager.GetArgumentTypes (mi);
5522 if (args != null && args.Length == 0)
5529 // This struct records the helper methods used by the Foreach construct
5531 class ForeachHelperMethods {
5532 public EmitContext ec;
5533 public MethodInfo get_enumerator;
5534 public MethodInfo move_next;
5535 public MethodInfo get_current;
5536 public Type element_type;
5537 public Type enumerator_type;
5538 public bool is_disposable;
5540 public ForeachHelperMethods (EmitContext ec)
5543 this.element_type = TypeManager.object_type;
5544 this.enumerator_type = TypeManager.ienumerator_type;
5545 this.is_disposable = true;
5549 static bool GetEnumeratorFilter (MemberInfo m, object criteria)
5554 if (!(m is MethodInfo))
5557 if (m.Name != "GetEnumerator")
5560 MethodInfo mi = (MethodInfo) m;
5561 Type [] args = TypeManager.GetArgumentTypes (mi);
5563 if (args.Length != 0)
5566 ForeachHelperMethods hm = (ForeachHelperMethods) criteria;
5567 EmitContext ec = hm.ec;
5570 // Check whether GetEnumerator is accessible to us
5572 MethodAttributes prot = mi.Attributes & MethodAttributes.MemberAccessMask;
5574 Type declaring = mi.DeclaringType;
5575 if (prot == MethodAttributes.Private){
5576 if (declaring != ec.ContainerType)
5578 } else if (prot == MethodAttributes.FamANDAssem){
5579 // If from a different assembly, false
5580 if (!(mi is MethodBuilder))
5583 // Are we being invoked from the same class, or from a derived method?
5585 if (ec.ContainerType != declaring){
5586 if (!ec.ContainerType.IsSubclassOf (declaring))
5589 } else if (prot == MethodAttributes.FamORAssem){
5590 if (!(mi is MethodBuilder ||
5591 ec.ContainerType == declaring ||
5592 ec.ContainerType.IsSubclassOf (declaring)))
5594 } if (prot == MethodAttributes.Family){
5595 if (!(ec.ContainerType == declaring ||
5596 ec.ContainerType.IsSubclassOf (declaring)))
5601 // Ok, we can access it, now make sure that we can do something
5602 // with this `GetEnumerator'
5605 if (mi.ReturnType == TypeManager.ienumerator_type ||
5606 TypeManager.ienumerator_type.IsAssignableFrom (mi.ReturnType) ||
5607 (!RootContext.StdLib && TypeManager.ImplementsInterface (mi.ReturnType, TypeManager.ienumerator_type))) {
5608 hm.move_next = TypeManager.bool_movenext_void;
5609 hm.get_current = TypeManager.object_getcurrent_void;
5614 // Ok, so they dont return an IEnumerable, we will have to
5615 // find if they support the GetEnumerator pattern.
5617 Type return_type = mi.ReturnType;
5619 hm.move_next = FetchMethodMoveNext (return_type);
5620 if (hm.move_next == null)
5622 hm.get_current = FetchMethodGetCurrent (return_type);
5623 if (hm.get_current == null)
5626 hm.element_type = hm.get_current.ReturnType;
5627 hm.enumerator_type = return_type;
5628 hm.is_disposable = TypeManager.ImplementsInterface (
5629 hm.enumerator_type, TypeManager.idisposable_type);
5635 /// This filter is used to find the GetEnumerator method
5636 /// on which IEnumerator operates
5638 static MemberFilter FilterEnumerator;
5642 FilterEnumerator = new MemberFilter (GetEnumeratorFilter);
5645 void error1579 (Type t)
5647 Report.Error (1579, loc,
5648 "foreach statement cannot operate on variables of type `" +
5649 t.FullName + "' because that class does not provide a " +
5650 " GetEnumerator method or it is inaccessible");
5653 static bool TryType (Type t, ForeachHelperMethods hm)
5657 mi = TypeContainer.FindMembers (t, MemberTypes.Method,
5658 BindingFlags.Public | BindingFlags.NonPublic |
5659 BindingFlags.Instance,
5660 FilterEnumerator, hm);
5665 hm.get_enumerator = (MethodInfo) mi [0];
5670 // Looks for a usable GetEnumerator in the Type, and if found returns
5671 // the three methods that participate: GetEnumerator, MoveNext and get_Current
5673 ForeachHelperMethods ProbeCollectionType (EmitContext ec, Type t)
5675 ForeachHelperMethods hm = new ForeachHelperMethods (ec);
5677 if (TryType (t, hm))
5681 // Now try to find the method in the interfaces
5684 Type [] ifaces = t.GetInterfaces ();
5686 foreach (Type i in ifaces){
5687 if (TryType (i, hm))
5692 // Since TypeBuilder.GetInterfaces only returns the interface
5693 // types for this type, we have to keep looping, but once
5694 // we hit a non-TypeBuilder (ie, a Type), then we know we are
5695 // done, because it returns all the types
5697 if ((t is TypeBuilder))
5707 // FIXME: possible optimization.
5708 // We might be able to avoid creating `empty' if the type is the sam
5710 bool EmitCollectionForeach (EmitContext ec)
5712 ILGenerator ig = ec.ig;
5713 LocalBuilder enumerator, disposable;
5715 enumerator = ig.DeclareLocal (hm.enumerator_type);
5716 if (hm.is_disposable)
5717 disposable = ig.DeclareLocal (TypeManager.idisposable_type);
5722 // Instantiate the enumerator
5724 if (expr.Type.IsValueType){
5725 if (expr is IMemoryLocation){
5726 IMemoryLocation ml = (IMemoryLocation) expr;
5728 ml.AddressOf (ec, AddressOp.Load);
5730 throw new Exception ("Expr " + expr + " of type " + expr.Type +
5731 " does not implement IMemoryLocation");
5732 ig.Emit (OpCodes.Call, hm.get_enumerator);
5735 ig.Emit (OpCodes.Callvirt, hm.get_enumerator);
5737 ig.Emit (OpCodes.Stloc, enumerator);
5740 // Protect the code in a try/finalize block, so that
5741 // if the beast implement IDisposable, we get rid of it
5743 bool old_in_try = ec.InTry;
5745 if (hm.is_disposable) {
5746 ig.BeginExceptionBlock ();
5750 Label end_try = ig.DefineLabel ();
5752 ig.MarkLabel (ec.LoopBegin);
5753 ig.Emit (OpCodes.Ldloc, enumerator);
5754 ig.Emit (OpCodes.Callvirt, hm.move_next);
5755 ig.Emit (OpCodes.Brfalse, end_try);
5756 ig.Emit (OpCodes.Ldloc, enumerator);
5757 ig.Emit (OpCodes.Callvirt, hm.get_current);
5758 variable.EmitAssign (ec, conv);
5759 statement.Emit (ec);
5760 ig.Emit (OpCodes.Br, ec.LoopBegin);
5761 ig.MarkLabel (end_try);
5762 ec.InTry = old_in_try;
5764 // The runtime provides this for us.
5765 // ig.Emit (OpCodes.Leave, end);
5768 // Now the finally block
5770 if (hm.is_disposable) {
5771 Label end_finally = ig.DefineLabel ();
5772 bool old_in_finally = ec.InFinally;
5773 ec.InFinally = true;
5774 ig.BeginFinallyBlock ();
5776 ig.Emit (OpCodes.Ldloc, enumerator);
5777 ig.Emit (OpCodes.Isinst, TypeManager.idisposable_type);
5778 ig.Emit (OpCodes.Stloc, disposable);
5779 ig.Emit (OpCodes.Ldloc, disposable);
5780 ig.Emit (OpCodes.Brfalse, end_finally);
5781 ig.Emit (OpCodes.Ldloc, disposable);
5782 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
5783 ig.MarkLabel (end_finally);
5784 ec.InFinally = old_in_finally;
5786 // The runtime generates this anyways.
5787 // ig.Emit (OpCodes.Endfinally);
5789 ig.EndExceptionBlock ();
5792 ig.MarkLabel (ec.LoopEnd);
5797 // FIXME: possible optimization.
5798 // We might be able to avoid creating `empty' if the type is the sam
5800 bool EmitArrayForeach (EmitContext ec)
5802 int rank = array_type.GetArrayRank ();
5803 ILGenerator ig = ec.ig;
5805 LocalBuilder copy = ig.DeclareLocal (array_type);
5808 // Make our copy of the array
5811 ig.Emit (OpCodes.Stloc, copy);
5814 LocalBuilder counter = ig.DeclareLocal (TypeManager.int32_type);
5818 ig.Emit (OpCodes.Ldc_I4_0);
5819 ig.Emit (OpCodes.Stloc, counter);
5820 test = ig.DefineLabel ();
5821 ig.Emit (OpCodes.Br, test);
5823 loop = ig.DefineLabel ();
5824 ig.MarkLabel (loop);
5826 ig.Emit (OpCodes.Ldloc, copy);
5827 ig.Emit (OpCodes.Ldloc, counter);
5828 ArrayAccess.EmitLoadOpcode (ig, var_type);
5830 variable.EmitAssign (ec, conv);
5832 statement.Emit (ec);
5834 ig.MarkLabel (ec.LoopBegin);
5835 ig.Emit (OpCodes.Ldloc, counter);
5836 ig.Emit (OpCodes.Ldc_I4_1);
5837 ig.Emit (OpCodes.Add);
5838 ig.Emit (OpCodes.Stloc, counter);
5840 ig.MarkLabel (test);
5841 ig.Emit (OpCodes.Ldloc, counter);
5842 ig.Emit (OpCodes.Ldloc, copy);
5843 ig.Emit (OpCodes.Ldlen);
5844 ig.Emit (OpCodes.Conv_I4);
5845 ig.Emit (OpCodes.Blt, loop);
5847 LocalBuilder [] dim_len = new LocalBuilder [rank];
5848 LocalBuilder [] dim_count = new LocalBuilder [rank];
5849 Label [] loop = new Label [rank];
5850 Label [] test = new Label [rank];
5853 for (dim = 0; dim < rank; dim++){
5854 dim_len [dim] = ig.DeclareLocal (TypeManager.int32_type);
5855 dim_count [dim] = ig.DeclareLocal (TypeManager.int32_type);
5856 test [dim] = ig.DefineLabel ();
5857 loop [dim] = ig.DefineLabel ();
5860 for (dim = 0; dim < rank; dim++){
5861 ig.Emit (OpCodes.Ldloc, copy);
5862 IntLiteral.EmitInt (ig, dim);
5863 ig.Emit (OpCodes.Callvirt, TypeManager.int_getlength_int);
5864 ig.Emit (OpCodes.Stloc, dim_len [dim]);
5867 for (dim = 0; dim < rank; dim++){
5868 ig.Emit (OpCodes.Ldc_I4_0);
5869 ig.Emit (OpCodes.Stloc, dim_count [dim]);
5870 ig.Emit (OpCodes.Br, test [dim]);
5871 ig.MarkLabel (loop [dim]);
5874 ig.Emit (OpCodes.Ldloc, copy);
5875 for (dim = 0; dim < rank; dim++)
5876 ig.Emit (OpCodes.Ldloc, dim_count [dim]);
5879 // FIXME: Maybe we can cache the computation of `get'?
5881 Type [] args = new Type [rank];
5884 for (int i = 0; i < rank; i++)
5885 args [i] = TypeManager.int32_type;
5887 ModuleBuilder mb = CodeGen.ModuleBuilder;
5888 get = mb.GetArrayMethod (
5890 CallingConventions.HasThis| CallingConventions.Standard,
5892 ig.Emit (OpCodes.Call, get);
5893 variable.EmitAssign (ec, conv);
5894 statement.Emit (ec);
5895 ig.MarkLabel (ec.LoopBegin);
5896 for (dim = rank - 1; dim >= 0; dim--){
5897 ig.Emit (OpCodes.Ldloc, dim_count [dim]);
5898 ig.Emit (OpCodes.Ldc_I4_1);
5899 ig.Emit (OpCodes.Add);
5900 ig.Emit (OpCodes.Stloc, dim_count [dim]);
5902 ig.MarkLabel (test [dim]);
5903 ig.Emit (OpCodes.Ldloc, dim_count [dim]);
5904 ig.Emit (OpCodes.Ldloc, dim_len [dim]);
5905 ig.Emit (OpCodes.Blt, loop [dim]);
5908 ig.MarkLabel (ec.LoopEnd);
5913 protected override bool DoEmit (EmitContext ec)
5917 ILGenerator ig = ec.ig;
5919 Label old_begin = ec.LoopBegin, old_end = ec.LoopEnd;
5920 bool old_inloop = ec.InLoop;
5921 int old_loop_begin_try_catch_level = ec.LoopBeginTryCatchLevel;
5922 ec.LoopBegin = ig.DefineLabel ();
5923 ec.LoopEnd = ig.DefineLabel ();
5925 ec.LoopBeginTryCatchLevel = ec.TryCatchLevel;
5928 ret_val = EmitCollectionForeach (ec);
5930 ret_val = EmitArrayForeach (ec);
5932 ec.LoopBegin = old_begin;
5933 ec.LoopEnd = old_end;
5934 ec.InLoop = old_inloop;
5935 ec.LoopBeginTryCatchLevel = old_loop_begin_try_catch_level;
5942 /// AddHandler statement
5944 public class AddHandler : Statement {
5946 Expression EvtHandler;
5949 // keeps track whether EvtId is already resolved
5953 public AddHandler (Expression evt_id, Expression evt_handler, Location l)
5956 EvtHandler = evt_handler;
5959 //Console.WriteLine ("Adding handler '" + evt_handler + "' for Event '" + evt_id +"'");
5962 public override bool Resolve (EmitContext ec)
5965 // if EvetId is of EventExpr type that means
5966 // this is already resolved
5968 if (EvtId is EventExpr) {
5973 EvtId = EvtId.Resolve(ec);
5974 EvtHandler = EvtHandler.Resolve(ec,ResolveFlags.MethodGroup);
5975 if (EvtId == null || (!(EvtId is EventExpr))) {
5976 Report.Error (30676, "Need an event designator.");
5980 if (EvtHandler == null)
5982 Report.Error (999, "'AddHandler' statement needs an event handler.");
5989 protected override bool DoEmit (EmitContext ec)
5992 // Already resolved and emitted don't do anything
5998 ArrayList args = new ArrayList();
5999 Argument arg = new Argument (EvtHandler, Argument.AType.Expression);
6004 // The even type was already resolved to a delegate, so
6005 // we must un-resolve its name to generate a type expression
6006 string ts = (EvtId.Type.ToString()).Replace ('+','.');
6007 Expression dtype = Mono.MonoBASIC.Parser.DecomposeQI (ts, Location.Null);
6009 // which we can use to declare a new event handler
6011 d = new New (dtype, args, Location.Null);
6013 e = new CompoundAssign(Binary.Operator.Addition, EvtId, d, Location.Null);
6015 // we resolve it all and emit the code
6028 /// RemoveHandler statement
6030 public class RemoveHandler : Statement
\r
6033 Expression EvtHandler;
6035 public RemoveHandler (Expression evt_id, Expression evt_handler, Location l)
6038 EvtHandler = evt_handler;
6042 public override bool Resolve (EmitContext ec)
6044 EvtId = EvtId.Resolve(ec);
6045 EvtHandler = EvtHandler.Resolve(ec,ResolveFlags.MethodGroup);
6046 if (EvtId == null || (!(EvtId is EventExpr)))
\r
6048 Report.Error (30676, "Need an event designator.");
6052 if (EvtHandler == null)
6054 Report.Error (999, "'AddHandler' statement needs an event handler.");
6060 protected override bool DoEmit (EmitContext ec)
6063 ArrayList args = new ArrayList();
6064 Argument arg = new Argument (EvtHandler, Argument.AType.Expression);
6067 // The even type was already resolved to a delegate, so
6068 // we must un-resolve its name to generate a type expression
6069 string ts = (EvtId.Type.ToString()).Replace ('+','.');
6070 Expression dtype = Mono.MonoBASIC.Parser.DecomposeQI (ts, Location.Null);
6072 // which we can use to declare a new event handler
6074 d = new New (dtype, args, Location.Null);
6077 e = new CompoundAssign(Binary.Operator.Subtraction, EvtId, d, Location.Null);
6079 // we resolve it all and emit the code
6091 public class RedimClause {
6092 public Expression Expr;
6093 public ArrayList NewIndexes;
6095 public RedimClause (Expression e, ArrayList args)
6102 public class ReDim : Statement {
6103 ArrayList RedimTargets;
6107 private StatementExpression ReDimExpr;
6109 public ReDim (ArrayList targets, bool opt_preserve, Location l)
6112 RedimTargets = targets;
6113 Preserve = opt_preserve;
6116 public override bool Resolve (EmitContext ec)
6118 Expression RedimTarget;
6119 ArrayList NewIndexes;
6121 foreach (RedimClause rc in RedimTargets) {
6122 RedimTarget = rc.Expr;
6123 NewIndexes = rc.NewIndexes;
6125 RedimTarget = RedimTarget.Resolve (ec);
6126 if (!RedimTarget.Type.IsArray)
6127 Report.Error (49, "'ReDim' statement requires an array");
6129 ArrayList args = new ArrayList();
6130 foreach (Argument a in NewIndexes) {
6131 if (a.Resolve(ec, loc))
6135 for (int x = 0; x < args.Count; x++) {
6136 args[x] = new Binary (Binary.Operator.Addition,
6137 (Expression) args[x], new IntLiteral (1), Location.Null);
6141 if (RedimTarget.Type.GetArrayRank() != args.Count)
6142 Report.Error (30415, "'ReDim' cannot change the number of dimensions of an array.");
6144 BaseType = RedimTarget.Type.GetElementType();
6145 Expression BaseTypeExpr = MonoBASIC.Parser.DecomposeQI(BaseType.FullName.ToString(), Location.Null);
6146 ArrayCreation acExpr = new ArrayCreation (BaseTypeExpr, NewIndexes, "", null, Location.Null);
6147 // TODO: we are in a foreach we probably can't reuse ReDimExpr, must turn it into an array(list)
6150 ExpressionStatement PreserveExpr = (ExpressionStatement) new Preserve(RedimTarget, acExpr, loc);
6151 ReDimExpr = (StatementExpression) new StatementExpression ((ExpressionStatement) new Assign (RedimTarget, PreserveExpr, loc), loc);
6154 ReDimExpr = (StatementExpression) new StatementExpression ((ExpressionStatement) new Assign (RedimTarget, acExpr, loc), loc);
6155 ReDimExpr.Resolve(ec);
6160 protected override bool DoEmit (EmitContext ec)
6168 public class Erase : Statement {
6169 Expression EraseTarget;
6171 private StatementExpression EraseExpr;
6173 public Erase (Expression expr, Location l)
6179 public override bool Resolve (EmitContext ec)
6181 EraseTarget = EraseTarget.Resolve (ec);
6182 if (!EraseTarget.Type.IsArray)
6183 Report.Error (49, "'Erase' statement requires an array");
6185 EraseExpr = (StatementExpression) new StatementExpression ((ExpressionStatement) new Assign (EraseTarget, NullLiteral.Null, loc), loc);
6186 EraseExpr.Resolve(ec);
6191 protected override bool DoEmit (EmitContext ec)