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)
815 expr = Parser.SetValueRequiredFlag (expr);
820 public override bool Resolve (EmitContext ec)
823 Expr = Expr.Resolve (ec);
828 FlowBranching.UsageVector vector = ec.CurrentBranching.CurrentUsageVector;
830 if (ec.CurrentBranching.InTryBlock ())
831 ec.CurrentBranching.AddFinallyVector (vector);
833 if (! ec.InTry && ! ec.InCatch) {
834 vector.Returns = FlowReturns.ALWAYS;
835 vector.Breaks = FlowReturns.ALWAYS;
840 protected override bool DoEmit (EmitContext ec)
843 Report.Error (157,loc,"Control can not leave the body of the finally block");
847 if (ec.ReturnType == null){
849 Report.Error (127, loc, "Return with a value not allowed here");
854 Report.Error (126, loc, "An object of type '" +
855 TypeManager.MonoBASIC_Name (ec.ReturnType) + "' is " +
856 "expected for the return statement");
860 if (Expr.Type != ec.ReturnType)
861 Expr = Expression.ConvertImplicitRequired (
862 ec, Expr, ec.ReturnType, loc);
869 if (ec.InTry || ec.InCatch)
870 ec.ig.Emit (OpCodes.Stloc, ec.TemporaryReturn ());
873 if (ec.InTry || ec.InCatch) {
874 if (!ec.HasReturnLabel) {
875 ec.ReturnLabel = ec.ig.DefineLabel ();
876 ec.HasReturnLabel = true;
878 ec.ig.Emit (OpCodes.Leave, ec.ReturnLabel);
880 ec.ig.Emit (OpCodes.Ret);
886 public class Goto : Statement {
889 LabeledStatement label;
891 public override bool Resolve (EmitContext ec)
893 label = block.LookupLabel (target);
898 "No such label '" + target + "' in this scope");
902 // If this is a forward goto.
903 if (!label.IsDefined)
904 label.AddUsageVector (ec.CurrentBranching.CurrentUsageVector);
906 ec.CurrentBranching.CurrentUsageVector.Breaks = FlowReturns.ALWAYS;
907 label.AddReference ();
911 public Goto (Block parent_block, string label, Location l)
913 block = parent_block;
918 public string Target {
924 protected override bool DoEmit (EmitContext ec)
926 Label l = label.LabelTarget (ec);
927 if (ec.InTry || ec.InCatch)
928 ec.ig.Emit (OpCodes.Leave, l);
930 ec.ig.Emit (OpCodes.Br, l);
936 public class LabeledStatement : Statement {
937 public readonly Location Location;
945 public LabeledStatement (string label_name, Location l)
947 //this.label_name = label_name;
951 public Label LabelTarget (EmitContext ec)
955 label = ec.ig.DefineLabel ();
962 public bool IsDefined {
968 public bool HasBeenReferenced {
974 public void AddUsageVector (FlowBranching.UsageVector vector)
977 vectors = new ArrayList ();
979 vectors.Add (vector.Clone ());
983 public override bool Resolve (EmitContext ec)
985 if (vectors != null) {
986 ec.CurrentBranching.CurrentUsageVector.MergeJumpOrigins (vectors);
989 ec.CurrentBranching.CurrentUsageVector.Breaks = FlowReturns.NEVER;
990 ec.CurrentBranching.CurrentUsageVector.Returns = FlowReturns.NEVER;
999 protected override bool DoEmit (EmitContext ec)
1002 ec.ig.MarkLabel (label);
1006 public void AddReference ()
1014 /// 'goto default' statement
1016 public class GotoDefault : Statement {
1018 public GotoDefault (Location l)
1023 public override bool Resolve (EmitContext ec)
1025 ec.CurrentBranching.CurrentUsageVector.Breaks = FlowReturns.UNREACHABLE;
1029 protected override bool DoEmit (EmitContext ec)
1031 if (ec.Switch == null){
1032 Report.Error (153, loc, "goto default is only valid in a switch statement");
1036 if (!ec.Switch.GotDefault){
1037 Report.Error (30132, loc, "No default target on switch statement");
1040 ec.ig.Emit (OpCodes.Br, ec.Switch.DefaultTarget);
1046 /// 'goto case' statement
1048 public class GotoCase : Statement {
1052 public GotoCase (Expression e, Location l)
1058 public override bool Resolve (EmitContext ec)
1060 if (ec.Switch == null){
1061 Report.Error (153, loc, "goto case is only valid in a switch statement");
1065 expr = expr.Resolve (ec);
1069 if (!(expr is Constant)){
1070 Report.Error (30132, loc, "Target expression for goto case is not constant");
1074 object val = Expression.ConvertIntLiteral (
1075 (Constant) expr, ec.Switch.SwitchType, loc);
1080 SwitchLabel sl = (SwitchLabel) ec.Switch.Elements [val];
1085 "No such label 'case " + val + "': for the goto case");
1088 label = sl.ILLabelCode;
1090 ec.CurrentBranching.CurrentUsageVector.Breaks = FlowReturns.UNREACHABLE;
1094 protected override bool DoEmit (EmitContext ec)
1096 ec.ig.Emit (OpCodes.Br, label);
1101 public class Throw : Statement {
1104 public Throw (Expression expr, Location l)
1110 public override bool Resolve (EmitContext ec)
1113 expr = expr.Resolve (ec);
1117 ExprClass eclass = expr.eclass;
1119 if (!(eclass == ExprClass.Variable || eclass == ExprClass.PropertyAccess ||
1120 eclass == ExprClass.Value || eclass == ExprClass.IndexerAccess)) {
1121 expr.Error118 ("value, variable, property or indexer access ");
1127 if ((t != TypeManager.exception_type) &&
1128 !t.IsSubclassOf (TypeManager.exception_type) &&
1129 !(expr is NullLiteral)) {
1130 Report.Error (30665, loc,
1131 "The type caught or thrown must be derived " +
1132 "from System.Exception");
1137 ec.CurrentBranching.CurrentUsageVector.Returns = FlowReturns.EXCEPTION;
1138 ec.CurrentBranching.CurrentUsageVector.Breaks = FlowReturns.EXCEPTION;
1142 protected override bool DoEmit (EmitContext ec)
1146 ec.ig.Emit (OpCodes.Rethrow);
1150 "A throw statement with no argument is only " +
1151 "allowed in a catch clause");
1158 ec.ig.Emit (OpCodes.Throw);
1164 // Support 'End' Statement which terminates execution immediately
1166 public class End : Statement {
1168 public End (Location l)
1173 public override bool Resolve (EmitContext ec)
1178 protected override bool DoEmit (EmitContext ec)
1180 Expression e = null;
1181 Expression tmp = Mono.MonoBASIC.Parser.DecomposeQI (
1182 "Microsoft.VisualBasic.CompilerServices.ProjectData.EndApp",
1185 e = new Invocation (tmp, null, loc);
1197 public class Break : Statement {
1199 public Break (Location l)
1204 public override bool Resolve (EmitContext ec)
1206 ec.CurrentBranching.MayLeaveLoop = true;
1207 ec.CurrentBranching.CurrentUsageVector.Breaks = FlowReturns.ALWAYS;
1211 protected override bool DoEmit (EmitContext ec)
1213 ILGenerator ig = ec.ig;
1215 if (ec.InLoop == false && ec.Switch == null){
1216 Report.Error (139, loc, "No enclosing loop or switch to continue to");
1220 if (ec.InTry || ec.InCatch)
1221 ig.Emit (OpCodes.Leave, ec.LoopEnd);
1223 ig.Emit (OpCodes.Br, ec.LoopEnd);
1229 public enum ExitType {
1240 public class Exit : Statement {
1241 public readonly ExitType type;
1242 public Exit (ExitType t, Location l)
1248 public override bool Resolve (EmitContext ec)
1250 ec.CurrentBranching.MayLeaveLoop = true;
1251 ec.CurrentBranching.CurrentUsageVector.Breaks = FlowReturns.ALWAYS;
1255 protected override bool DoEmit (EmitContext ec)
1257 ILGenerator ig = ec.ig;
1259 if (type != ExitType.SUB && type != ExitType.FUNCTION &&
1260 type != ExitType.PROPERTY && type != ExitType.TRY) {
1261 if (ec.InLoop == false && ec.Switch == null){
1262 if (type == ExitType.FOR)
1263 Report.Error (30096, loc, "No enclosing FOR loop to exit from");
1264 if (type == ExitType.WHILE)
1265 Report.Error (30097, loc, "No enclosing WHILE loop to exit from");
1266 if (type == ExitType.DO)
1267 Report.Error (30089, loc, "No enclosing DO loop to exit from");
1268 if (type == ExitType.SELECT)
1269 Report.Error (30099, loc, "No enclosing SELECT to exit from");
1274 if (ec.InTry || ec.InCatch)
1275 ig.Emit (OpCodes.Leave, ec.LoopEnd);
1277 ig.Emit (OpCodes.Br, ec.LoopEnd);
1280 Report.Error (30393, loc,
1281 "Control can not leave the body of the finally block");
1285 if (ec.InTry || ec.InCatch) {
1286 if (ec.HasExitLabel)
1287 ec.ig.Emit (OpCodes.Leave, ec.ExitLabel);
1289 if(type == ExitType.SUB) {
1290 ec.ig.Emit (OpCodes.Ret);
1292 ec.ig.Emit (OpCodes.Ldloc_0);
1293 ec.ig.Emit (OpCodes.Ret);
1305 public class Continue : Statement {
1307 public Continue (Location l)
1312 public override bool Resolve (EmitContext ec)
1314 ec.CurrentBranching.CurrentUsageVector.Breaks = FlowReturns.ALWAYS;
1318 protected override bool DoEmit (EmitContext ec)
1320 Label begin = ec.LoopBegin;
1323 Report.Error (139, loc, "No enclosing loop to continue to");
1328 // UGH: Non trivial. This Br might cross a try/catch boundary
1332 // try { ... } catch { continue; }
1336 // try {} catch { while () { continue; }}
1338 if (ec.TryCatchLevel > ec.LoopBeginTryCatchLevel)
1339 ec.ig.Emit (OpCodes.Leave, begin);
1340 else if (ec.TryCatchLevel < ec.LoopBeginTryCatchLevel)
1341 throw new Exception ("Should never happen");
1343 ec.ig.Emit (OpCodes.Br, begin);
1349 // This is used in the control flow analysis code to specify whether the
1350 // current code block may return to its enclosing block before reaching
1353 public enum FlowReturns {
1354 // It can never return.
1357 // This means that the block contains a conditional return statement
1361 // The code always returns, ie. there's an unconditional return / break
1365 // The code always throws an exception.
1368 // The current code block is unreachable. This happens if it's immediately
1369 // following a FlowReturns.ALWAYS block.
1374 // This is a special bit vector which can inherit from another bit vector doing a
1375 // copy-on-write strategy. The inherited vector may have a smaller size than the
1378 public class MyBitVector {
1380 public int Count { get { return count; } }
1381 public readonly MyBitVector InheritsFrom;
1386 public MyBitVector (int Count)
1387 : this (null, Count)
1390 public MyBitVector (MyBitVector InheritsFrom, int Count)
1392 this.InheritsFrom = InheritsFrom;
1397 // Checks whether this bit vector has been modified. After setting this to true,
1398 // we won't use the inherited vector anymore, but our own copy of it.
1400 public bool IsDirty {
1407 initialize_vector ();
1412 // Get/set bit 'index' in the bit vector.
1414 public bool this [int index]
1418 throw new ArgumentOutOfRangeException ();
1420 // We're doing a "copy-on-write" strategy here; as long
1421 // as nobody writes to the array, we can use our parent's
1422 // copy instead of duplicating the vector.
1425 return vector [index];
1426 else if (InheritsFrom != null) {
1427 BitArray inherited = InheritsFrom.Vector;
1429 if (index < inherited.Count)
1430 return inherited [index];
1439 throw new ArgumentOutOfRangeException ();
1441 // Only copy the vector if we're actually modifying it.
1443 if (this [index] != value) {
1444 initialize_vector ();
1446 vector [index] = value;
1452 // If you explicitly convert the MyBitVector to a BitArray, you will get a deep
1453 // copy of the bit vector.
1455 public static explicit operator BitArray (MyBitVector vector)
1457 vector.initialize_vector ();
1458 return vector.Vector;
1462 // Performs an 'or' operation on the bit vector. The 'new_vector' may have a
1463 // different size than the current one.
1465 public void Or (MyBitVector new_vector)
1467 BitArray new_array = new_vector.Vector;
1469 initialize_vector ();
1472 if (vector.Count < new_array.Count)
1473 upper = vector.Count;
1475 upper = new_array.Count;
1477 for (int i = 0; i < upper; i++)
1478 vector [i] = vector [i] | new_array [i];
1482 // Perfonrms an 'and' operation on the bit vector. The 'new_vector' may have
1483 // a different size than the current one.
1485 public void And (MyBitVector new_vector)
1487 BitArray new_array = new_vector.Vector;
1489 initialize_vector ();
1492 if (vector.Count < new_array.Count)
1493 lower = upper = vector.Count;
1495 lower = new_array.Count;
1496 upper = vector.Count;
1499 for (int i = 0; i < lower; i++)
1500 vector [i] = vector [i] & new_array [i];
1502 for (int i = lower; i < upper; i++)
1507 // This does a deep copy of the bit vector.
1509 public MyBitVector Clone ()
1511 MyBitVector retval = new MyBitVector (Count);
1513 retval.Vector = Vector;
1518 public void ExpandBy(int howMany)
1521 throw new ArgumentException("howMany");
1522 initialize_vector();
1523 count = vector.Count + howMany;
1524 BitArray newVector = new BitArray(count, false);
1525 for (int i = 0; i < vector.Count; i++)
1526 newVector [i] = vector [i];
1534 else if (!is_dirty && (InheritsFrom != null))
1535 return InheritsFrom.Vector;
1537 initialize_vector ();
1543 initialize_vector ();
1545 for (int i = 0; i < System.Math.Min (vector.Count, value.Count); i++)
1546 vector [i] = value [i];
1550 void initialize_vector ()
1555 vector = new BitArray (Count, false);
1556 if (InheritsFrom != null)
1557 Vector = InheritsFrom.Vector;
1562 public override string ToString ()
1564 StringBuilder sb = new StringBuilder ("MyBitVector (");
1566 BitArray vector = Vector;
1570 sb.Append ("INHERITED - ");
1571 for (int i = 0; i < vector.Count; i++) {
1574 sb.Append (vector [i]);
1578 return sb.ToString ();
1583 // The type of a FlowBranching.
1585 public enum FlowBranchingType {
1586 // Normal (conditional or toplevel) block.
1603 // A new instance of this class is created every time a new block is resolved
1604 // and if there's branching in the block's control flow.
1606 public class FlowBranching {
1608 // The type of this flow branching.
1610 public readonly FlowBranchingType Type;
1613 // The block this branching is contained in. This may be null if it's not
1614 // a top-level block and it doesn't declare any local variables.
1616 public readonly Block Block;
1619 // The parent of this branching or null if this is the top-block.
1621 public readonly FlowBranching Parent;
1624 // Start-Location of this flow branching.
1626 public readonly Location Location;
1629 // A list of UsageVectors. A new vector is added each time control flow may
1630 // take a different path.
1632 public ArrayList Siblings;
1635 // If this is an infinite loop.
1637 public bool Infinite;
1640 // If we may leave the current loop.
1642 public bool MayLeaveLoop;
1647 InternalParameters param_info;
1649 MyStructInfo[] struct_params;
1651 ArrayList finally_vectors;
1653 static int next_id = 0;
1657 // Performs an 'And' operation on the FlowReturns status
1658 // (for instance, a block only returns ALWAYS if all its siblings
1661 public static FlowReturns AndFlowReturns (FlowReturns a, FlowReturns b)
1663 if (b == FlowReturns.UNREACHABLE)
1667 case FlowReturns.NEVER:
1668 if (b == FlowReturns.NEVER)
1669 return FlowReturns.NEVER;
1671 return FlowReturns.SOMETIMES;
1673 case FlowReturns.SOMETIMES:
1674 return FlowReturns.SOMETIMES;
1676 case FlowReturns.ALWAYS:
1677 if ((b == FlowReturns.ALWAYS) || (b == FlowReturns.EXCEPTION))
1678 return FlowReturns.ALWAYS;
1680 return FlowReturns.SOMETIMES;
1682 case FlowReturns.EXCEPTION:
1683 if (b == FlowReturns.EXCEPTION)
1684 return FlowReturns.EXCEPTION;
1685 else if (b == FlowReturns.ALWAYS)
1686 return FlowReturns.ALWAYS;
1688 return FlowReturns.SOMETIMES;
1695 // The vector contains a BitArray with information about which local variables
1696 // and parameters are already initialized at the current code position.
1698 public class UsageVector {
1700 // If this is true, then the usage vector has been modified and must be
1701 // merged when we're done with this branching.
1703 public bool IsDirty;
1706 // The number of parameters in this block.
1708 public readonly int CountParameters;
1711 // The number of locals in this block.
1713 public readonly int CountLocals;
1716 // The number of locals in this block added after starting usage track.
1718 public int ExtraLocals { get { return locals.Count - CountLocals; } }
1722 // If not null, then we inherit our state from this vector and do a
1723 // copy-on-write. If null, then we're the first sibling in a top-level
1724 // block and inherit from the empty vector.
1726 public readonly UsageVector InheritsFrom;
1731 MyBitVector locals, parameters;
1732 FlowReturns real_returns, real_breaks;
1735 static int next_id = 0;
1739 // Normally, you should not use any of these constructors.
1741 public UsageVector (UsageVector parent, int num_params, int num_locals)
1743 this.InheritsFrom = parent;
1744 this.CountParameters = num_params;
1745 this.CountLocals = num_locals;
1746 this.real_returns = FlowReturns.NEVER;
1747 this.real_breaks = FlowReturns.NEVER;
1749 if (parent != null) {
1750 locals = new MyBitVector (parent.locals, CountLocals);
1752 parameters = new MyBitVector (parent.parameters, num_params);
1753 real_returns = parent.Returns;
1754 real_breaks = parent.Breaks;
1756 locals = new MyBitVector (null, CountLocals);
1758 parameters = new MyBitVector (null, num_params);
1764 public UsageVector (UsageVector parent)
1765 : this (parent, parent.CountParameters, parent.CountLocals)
1768 public void AddExtraLocals(int howMany)
1770 locals.ExpandBy(howMany);
1774 // This does a deep copy of the usage vector.
1776 public UsageVector Clone ()
1778 UsageVector retval = new UsageVector (null, CountParameters, CountLocals);
1780 retval.locals = locals.Clone ();
1781 if (parameters != null)
1782 retval.parameters = parameters.Clone ();
1783 retval.real_returns = real_returns;
1784 retval.real_breaks = real_breaks;
1790 // State of parameter 'number'.
1792 public bool this [int number]
1797 else if (number == 0)
1798 throw new ArgumentException ();
1800 return parameters [number - 1];
1806 else if (number == 0)
1807 throw new ArgumentException ();
1809 parameters [number - 1] = value;
1814 // State of the local variable 'vi'.
1815 // If the local variable is a struct, use a non-zero 'field_idx'
1816 // to check an individual field in it.
1818 public bool this [VariableInfo vi, int field_idx]
1821 if (vi.Number == -1)
1823 else if (vi.Number == 0)
1824 throw new ArgumentException ();
1826 return locals [vi.Number + field_idx - 1];
1830 if (vi.Number == -1)
1832 else if (vi.Number == 0)
1833 throw new ArgumentException ();
1835 locals [vi.Number + field_idx - 1] = value;
1840 // Specifies when the current block returns.
1841 // If this is FlowReturns.UNREACHABLE, then control can never reach the
1842 // end of the method (so that we don't need to emit a return statement).
1843 // The same applies for FlowReturns.EXCEPTION, but in this case the return
1844 // value will never be used.
1846 public FlowReturns Returns {
1848 return real_returns;
1852 real_returns = value;
1857 // Specifies whether control may return to our containing block
1858 // before reaching the end of this block. This happens if there
1859 // is a break/continue/goto/return in it.
1860 // This can also be used to find out whether the statement immediately
1861 // following the current block may be reached or not.
1863 public FlowReturns Breaks {
1869 real_breaks = value;
1873 public bool AlwaysBreaks {
1875 return (Breaks == FlowReturns.ALWAYS) ||
1876 (Breaks == FlowReturns.EXCEPTION) ||
1877 (Breaks == FlowReturns.UNREACHABLE);
1881 public bool MayBreak {
1883 return Breaks != FlowReturns.NEVER;
1887 public bool AlwaysReturns {
1889 return (Returns == FlowReturns.ALWAYS) ||
1890 (Returns == FlowReturns.EXCEPTION);
1894 public bool MayReturn {
1896 return (Returns == FlowReturns.SOMETIMES) ||
1897 (Returns == FlowReturns.ALWAYS);
1902 // Merge a child branching.
1904 public FlowReturns MergeChildren (FlowBranching branching, ICollection children)
1906 MyBitVector new_locals = null;
1907 MyBitVector new_params = null;
1909 FlowReturns new_returns = FlowReturns.NEVER;
1910 FlowReturns new_breaks = FlowReturns.NEVER;
1911 bool new_returns_set = false, new_breaks_set = false;
1913 Report.Debug (2, "MERGING CHILDREN", branching, branching.Type,
1914 this, children.Count);
1916 foreach (UsageVector child in children) {
1917 Report.Debug (2, " MERGING CHILD", child, child.is_finally);
1919 if (!child.is_finally) {
1920 if (child.Breaks != FlowReturns.UNREACHABLE) {
1921 // If Returns is already set, perform an
1922 // 'And' operation on it, otherwise just set just.
1923 if (!new_returns_set) {
1924 new_returns = child.Returns;
1925 new_returns_set = true;
1927 new_returns = AndFlowReturns (
1928 new_returns, child.Returns);
1931 // If Breaks is already set, perform an
1932 // 'And' operation on it, otherwise just set just.
1933 if (!new_breaks_set) {
1934 new_breaks = child.Breaks;
1935 new_breaks_set = true;
1937 new_breaks = AndFlowReturns (
1938 new_breaks, child.Breaks);
1941 // Ignore unreachable children.
1942 if (child.Returns == FlowReturns.UNREACHABLE)
1945 // A local variable is initialized after a flow branching if it
1946 // has been initialized in all its branches which do neither
1947 // always return or always throw an exception.
1949 // If a branch may return, but does not always return, then we
1950 // can treat it like a never-returning branch here: control will
1951 // only reach the code position after the branching if we did not
1954 // It's important to distinguish between always and sometimes
1955 // returning branches here:
1958 // 2 if (something) {
1962 // 6 Console.WriteLine (a);
1964 // The if block in lines 3-4 always returns, so we must not look
1965 // at the initialization of 'a' in line 4 - thus it'll still be
1966 // uninitialized in line 6.
1968 // On the other hand, the following is allowed:
1975 // 6 Console.WriteLine (a);
1977 // Here, 'a' is initialized in line 3 and we must not look at
1978 // line 5 since it always returns.
1980 if (child.is_finally) {
1981 if (new_locals == null)
1982 new_locals = locals.Clone ();
1983 new_locals.Or (child.locals);
1985 if (parameters != null) {
1986 if (new_params == null)
1987 new_params = parameters.Clone ();
1988 new_params.Or (child.parameters);
1992 if (!child.AlwaysReturns && !child.AlwaysBreaks) {
1993 if (new_locals != null)
1994 new_locals.And (child.locals);
1996 new_locals = locals.Clone ();
1997 new_locals.Or (child.locals);
1999 } else if (children.Count == 1) {
2000 new_locals = locals.Clone ();
2001 new_locals.Or (child.locals);
2004 // An 'out' parameter must be assigned in all branches which do
2005 // not always throw an exception.
2006 if (parameters != null) {
2007 if (child.Breaks != FlowReturns.EXCEPTION) {
2008 if (new_params != null)
2009 new_params.And (child.parameters);
2011 new_params = parameters.Clone ();
2012 new_params.Or (child.parameters);
2014 } else if (children.Count == 1) {
2015 new_params = parameters.Clone ();
2016 new_params.Or (child.parameters);
2022 Returns = new_returns;
2023 if ((branching.Type == FlowBranchingType.BLOCK) ||
2024 (branching.Type == FlowBranchingType.EXCEPTION) ||
2025 (new_breaks == FlowReturns.UNREACHABLE) ||
2026 (new_breaks == FlowReturns.EXCEPTION))
2027 Breaks = new_breaks;
2028 else if (branching.Type == FlowBranchingType.SWITCH_SECTION)
2029 Breaks = new_returns;
2030 else if (branching.Type == FlowBranchingType.SWITCH){
2031 if (new_breaks == FlowReturns.ALWAYS)
2032 Breaks = FlowReturns.ALWAYS;
2036 // We've now either reached the point after the branching or we will
2037 // never get there since we always return or always throw an exception.
2039 // If we can reach the point after the branching, mark all locals and
2040 // parameters as initialized which have been initialized in all branches
2041 // we need to look at (see above).
2044 if (((new_breaks != FlowReturns.ALWAYS) &&
2045 (new_breaks != FlowReturns.EXCEPTION) &&
2046 (new_breaks != FlowReturns.UNREACHABLE)) ||
2047 (children.Count == 1)) {
2048 if (new_locals != null)
2049 locals.Or (new_locals);
2051 if (new_params != null)
2052 parameters.Or (new_params);
2055 Report.Debug (2, "MERGING CHILDREN DONE", branching.Type,
2056 new_params, new_locals, new_returns, new_breaks,
2057 branching.Infinite, branching.MayLeaveLoop, this);
2059 if (branching.Type == FlowBranchingType.SWITCH_SECTION) {
2060 if ((new_breaks != FlowReturns.ALWAYS) &&
2061 (new_breaks != FlowReturns.EXCEPTION) &&
2062 (new_breaks != FlowReturns.UNREACHABLE))
2063 Report.Error (163, branching.Location,
2064 "Control cannot fall through from one " +
2065 "case label to another");
2068 if (branching.Infinite && !branching.MayLeaveLoop) {
2069 Report.Debug (1, "INFINITE", new_returns, new_breaks,
2070 Returns, Breaks, this);
2072 // We're actually infinite.
2073 if (new_returns == FlowReturns.NEVER) {
2074 Breaks = FlowReturns.UNREACHABLE;
2075 return FlowReturns.UNREACHABLE;
2078 // If we're an infinite loop and do not break, the code after
2079 // the loop can never be reached. However, if we may return
2080 // from the loop, then we do always return (or stay in the loop
2082 if ((new_returns == FlowReturns.SOMETIMES) ||
2083 (new_returns == FlowReturns.ALWAYS)) {
2084 Returns = FlowReturns.ALWAYS;
2085 return FlowReturns.ALWAYS;
2093 // Tells control flow analysis that the current code position may be reached with
2094 // a forward jump from any of the origins listed in 'origin_vectors' which is a
2095 // list of UsageVectors.
2097 // This is used when resolving forward gotos - in the following example, the
2098 // variable 'a' is uninitialized in line 8 becase this line may be reached via
2099 // the goto in line 4:
2109 // 8 Console.WriteLine (a);
2112 public void MergeJumpOrigins (ICollection origin_vectors)
2114 Report.Debug (1, "MERGING JUMP ORIGIN", this);
2116 real_breaks = FlowReturns.NEVER;
2117 real_returns = FlowReturns.NEVER;
2119 foreach (UsageVector vector in origin_vectors) {
2120 Report.Debug (1, " MERGING JUMP ORIGIN", vector);
2122 locals.And (vector.locals);
2123 if (parameters != null)
2124 parameters.And (vector.parameters);
2125 Breaks = AndFlowReturns (Breaks, vector.Breaks);
2126 Returns = AndFlowReturns (Returns, vector.Returns);
2129 Report.Debug (1, "MERGING JUMP ORIGIN DONE", this);
2133 // This is used at the beginning of a finally block if there were
2134 // any return statements in the try block or one of the catch blocks.
2136 public void MergeFinallyOrigins (ICollection finally_vectors)
2138 Report.Debug (1, "MERGING FINALLY ORIGIN", this);
2140 real_breaks = FlowReturns.NEVER;
2142 foreach (UsageVector vector in finally_vectors) {
2143 Report.Debug (1, " MERGING FINALLY ORIGIN", vector);
2145 if (parameters != null)
2146 parameters.And (vector.parameters);
2147 Breaks = AndFlowReturns (Breaks, vector.Breaks);
2152 Report.Debug (1, "MERGING FINALLY ORIGIN DONE", this);
2155 // Performs an 'or' operation on the locals and the parameters.
2157 public void Or (UsageVector new_vector)
2159 locals.Or (new_vector.locals);
2160 if (parameters != null)
2161 parameters.Or (new_vector.parameters);
2165 // Performs an 'and' operation on the locals.
2167 public void AndLocals (UsageVector new_vector)
2169 locals.And (new_vector.locals);
2173 // Returns a deep copy of the parameters.
2175 public MyBitVector Parameters {
2177 if (parameters != null)
2178 return parameters.Clone ();
2185 // Returns a deep copy of the locals.
2187 public MyBitVector Locals {
2189 return locals.Clone ();
2197 public override string ToString ()
2199 StringBuilder sb = new StringBuilder ();
2201 sb.Append ("Vector (");
2204 sb.Append (Returns);
2207 if (parameters != null) {
2209 sb.Append (parameters);
2215 return sb.ToString ();
2219 FlowBranching (FlowBranchingType type, Location loc)
2221 this.Siblings = new ArrayList ();
2223 this.Location = loc;
2229 // Creates a new flow branching for 'block'.
2230 // This is used from Block.Resolve to create the top-level branching of
2233 public FlowBranching (Block block, InternalParameters ip, Location loc)
2234 : this (FlowBranchingType.BLOCK, loc)
2239 int count = (ip != null) ? ip.Count : 0;
2242 param_map = new int [count];
2243 struct_params = new MyStructInfo [count];
2246 for (int i = 0; i < count; i++) {
2247 //Parameter.Modifier mod = param_info.ParameterModifier (i);
2249 // if ((mod & Parameter.Modifier.OUT) == 0)
2252 param_map [i] = ++num_params;
2254 Type param_type = param_info.ParameterType (i);
2256 struct_params [i] = MyStructInfo.GetStructInfo (param_type);
2257 if (struct_params [i] != null)
2258 num_params += struct_params [i].Count;
2261 Siblings = new ArrayList ();
2262 Siblings.Add (new UsageVector (null, num_params, block.CountVariables));
2266 // Creates a new flow branching which is contained in 'parent'.
2267 // You should only pass non-null for the 'block' argument if this block
2268 // introduces any new variables - in this case, we need to create a new
2269 // usage vector with a different size than our parent's one.
2271 public FlowBranching (FlowBranching parent, FlowBranchingType type,
2272 Block block, Location loc)
2278 if (parent != null) {
2279 param_info = parent.param_info;
2280 param_map = parent.param_map;
2281 struct_params = parent.struct_params;
2282 num_params = parent.num_params;
2287 vector = new UsageVector (parent.CurrentUsageVector, num_params,
2288 Block.CountVariables);
2290 vector = new UsageVector (Parent.CurrentUsageVector);
2292 Siblings.Add (vector);
2295 case FlowBranchingType.EXCEPTION:
2296 finally_vectors = new ArrayList ();
2305 // Returns the branching's current usage vector.
2307 public UsageVector CurrentUsageVector
2310 return (UsageVector) Siblings [Siblings.Count - 1];
2315 // Creates a sibling of the current usage vector.
2317 public void CreateSibling ()
2319 Siblings.Add (new UsageVector (Parent.CurrentUsageVector));
2321 Report.Debug (1, "CREATED SIBLING", CurrentUsageVector);
2325 // Creates a sibling for a 'finally' block.
2327 public void CreateSiblingForFinally ()
2329 if (Type != FlowBranchingType.EXCEPTION)
2330 throw new NotSupportedException ();
2334 CurrentUsageVector.MergeFinallyOrigins (finally_vectors);
2339 // Merge a child branching.
2341 public FlowReturns MergeChild (FlowBranching child)
2343 FlowReturns returns = CurrentUsageVector.MergeChildren (child, child.Siblings);
2345 if (child.Type != FlowBranchingType.LOOP_BLOCK)
2346 MayLeaveLoop |= child.MayLeaveLoop;
2348 MayLeaveLoop = false;
2354 // Does the toplevel merging.
2356 public FlowReturns MergeTopBlock ()
2358 if ((Type != FlowBranchingType.BLOCK) || (Block == null))
2359 throw new NotSupportedException ();
2361 UsageVector vector = new UsageVector (null, num_params, Block.CountVariables);
2363 Report.Debug (1, "MERGING TOP BLOCK", Location, vector);
2365 vector.MergeChildren (this, Siblings);
2368 Siblings.Add (vector);
2370 Report.Debug (1, "MERGING TOP BLOCK DONE", Location, vector);
2372 if (vector.Breaks != FlowReturns.EXCEPTION) {
2373 return vector.AlwaysBreaks ? FlowReturns.ALWAYS : vector.Returns;
2375 return FlowReturns.EXCEPTION;
2378 public bool InTryBlock ()
2380 if (finally_vectors != null)
2382 else if (Parent != null)
2383 return Parent.InTryBlock ();
2388 public void AddFinallyVector (UsageVector vector)
2390 if (finally_vectors != null) {
2391 finally_vectors.Add (vector.Clone ());
2396 Parent.AddFinallyVector (vector);
2398 throw new NotSupportedException ();
2401 public bool IsVariableAssigned (VariableInfo vi)
2403 if (CurrentUsageVector.AlwaysBreaks)
2406 return CurrentUsageVector [vi, 0];
2409 public bool IsVariableAssigned (VariableInfo vi, int field_idx)
2411 if (CurrentUsageVector.AlwaysBreaks)
2414 return CurrentUsageVector [vi, field_idx];
2417 public void SetVariableAssigned (VariableInfo vi)
2419 if (CurrentUsageVector.AlwaysBreaks)
2422 CurrentUsageVector [vi, 0] = true;
2425 public void SetVariableAssigned (VariableInfo vi, int field_idx)
2427 if (CurrentUsageVector.AlwaysBreaks)
2430 CurrentUsageVector [vi, field_idx] = true;
2433 public bool IsParameterAssigned (int number)
2435 int index = param_map [number];
2440 if (CurrentUsageVector [index])
2443 // Parameter is not assigned, so check whether it's a struct.
2444 // If it's either not a struct or a struct which non-public
2445 // fields, return false.
2446 MyStructInfo struct_info = struct_params [number];
2447 if ((struct_info == null) || struct_info.HasNonPublicFields)
2450 // Ok, so each field must be assigned.
2451 for (int i = 0; i < struct_info.Count; i++)
2452 if (!CurrentUsageVector [index + i])
2458 public bool IsParameterAssigned (int number, string field_name)
2460 int index = param_map [number];
2465 MyStructInfo info = (MyStructInfo) struct_params [number];
2469 int field_idx = info [field_name];
2471 return CurrentUsageVector [index + field_idx];
2474 public void SetParameterAssigned (int number)
2476 if (param_map [number] == 0)
2479 if (!CurrentUsageVector.AlwaysBreaks)
2480 CurrentUsageVector [param_map [number]] = true;
2483 public void SetParameterAssigned (int number, string field_name)
2485 int index = param_map [number];
2490 MyStructInfo info = (MyStructInfo) struct_params [number];
2494 int field_idx = info [field_name];
2496 if (!CurrentUsageVector.AlwaysBreaks)
2497 CurrentUsageVector [index + field_idx] = true;
2500 public bool IsReachable ()
2505 case FlowBranchingType.SWITCH_SECTION:
2506 // The code following a switch block is reachable unless the switch
2507 // block always returns.
2508 reachable = !CurrentUsageVector.AlwaysReturns;
2511 case FlowBranchingType.LOOP_BLOCK:
2512 // The code following a loop is reachable unless the loop always
2513 // returns or it's an infinite loop without any 'break's in it.
2514 reachable = !CurrentUsageVector.AlwaysReturns &&
2515 (CurrentUsageVector.Breaks != FlowReturns.UNREACHABLE);
2519 // The code following a block or exception is reachable unless the
2520 // block either always returns or always breaks.
2521 reachable = !CurrentUsageVector.AlwaysBreaks &&
2522 !CurrentUsageVector.AlwaysReturns;
2526 Report.Debug (1, "REACHABLE", Type, CurrentUsageVector.Returns,
2527 CurrentUsageVector.Breaks, CurrentUsageVector, reachable);
2532 public override string ToString ()
2534 StringBuilder sb = new StringBuilder ("FlowBranching (");
2539 if (Block != null) {
2541 sb.Append (Block.ID);
2543 sb.Append (Block.StartLocation);
2546 sb.Append (Siblings.Count);
2548 sb.Append (CurrentUsageVector);
2550 return sb.ToString ();
2554 public class MyStructInfo {
2555 public readonly Type Type;
2556 public readonly FieldInfo[] Fields;
2557 public readonly FieldInfo[] NonPublicFields;
2558 public readonly int Count;
2559 public readonly int CountNonPublic;
2560 public readonly bool HasNonPublicFields;
2562 private static Hashtable field_type_hash = new Hashtable ();
2563 private Hashtable field_hash;
2565 // Private constructor. To save memory usage, we only need to create one instance
2566 // of this class per struct type.
2567 private MyStructInfo (Type type)
2571 if (type is TypeBuilder) {
2572 TypeContainer tc = TypeManager.LookupTypeContainer (type);
2574 ArrayList fields = tc.Fields;
2575 if (fields != null) {
2576 foreach (Field field in fields) {
2577 if ((field.ModFlags & Modifiers.STATIC) != 0)
2579 if ((field.ModFlags & Modifiers.PUBLIC) != 0)
2586 Fields = new FieldInfo [Count];
2587 NonPublicFields = new FieldInfo [CountNonPublic];
2589 Count = CountNonPublic = 0;
2590 if (fields != null) {
2591 foreach (Field field in fields) {
2592 if ((field.ModFlags & Modifiers.STATIC) != 0)
2594 if ((field.ModFlags & Modifiers.PUBLIC) != 0)
2595 Fields [Count++] = field.FieldBuilder;
2597 NonPublicFields [CountNonPublic++] =
2603 Fields = type.GetFields (BindingFlags.Instance|BindingFlags.Public);
2604 Count = Fields.Length;
2606 NonPublicFields = type.GetFields (BindingFlags.Instance|BindingFlags.NonPublic);
2607 CountNonPublic = NonPublicFields.Length;
2610 Count += NonPublicFields.Length;
2613 field_hash = new Hashtable ();
2614 foreach (FieldInfo field in Fields)
2615 field_hash.Add (field.Name, ++number);
2617 if (NonPublicFields.Length != 0)
2618 HasNonPublicFields = true;
2620 foreach (FieldInfo field in NonPublicFields)
2621 field_hash.Add (field.Name, ++number);
2624 public int this [string name] {
2626 if (field_hash.Contains (name))
2627 return (int) field_hash [name];
2633 public FieldInfo this [int index] {
2635 if (index >= Fields.Length)
2636 return NonPublicFields [index - Fields.Length];
2638 return Fields [index];
2642 public static MyStructInfo GetStructInfo (Type type)
2644 if (!TypeManager.IsValueType (type) || TypeManager.IsEnumType (type))
2647 if (!(type is TypeBuilder) && TypeManager.IsBuiltinType (type))
2650 MyStructInfo info = (MyStructInfo) field_type_hash [type];
2654 info = new MyStructInfo (type);
2655 field_type_hash.Add (type, info);
2659 public static MyStructInfo GetStructInfo (TypeContainer tc)
2661 MyStructInfo info = (MyStructInfo) field_type_hash [tc.TypeBuilder];
2665 info = new MyStructInfo (tc.TypeBuilder);
2666 field_type_hash.Add (tc.TypeBuilder, info);
2671 public class VariableInfo : IVariable {
2672 public Expression Type;
2673 public LocalBuilder LocalBuilder;
2674 public Type VariableType;
2675 public string Alias;
2678 public bool Static {
2687 public readonly string Name;
2688 public readonly Location Location;
2689 public readonly int Block;
2694 public bool Assigned;
2695 public bool ReadOnly;
2697 public VariableInfo (Expression type, string name, int block, Location l, string Alias)
2698 : this (type, name, block, l)
2703 public VariableInfo (Expression type, string name, int block, Location l)
2708 LocalBuilder = null;
2712 public VariableInfo (TypeContainer tc, int block, Location l, string Alias)
2713 : this (tc, block, l)
2718 public VariableInfo (TypeContainer tc, int block, Location l)
2720 VariableType = tc.TypeBuilder;
2721 struct_info = MyStructInfo.GetStructInfo (tc);
2723 LocalBuilder = null;
2727 MyStructInfo struct_info;
2728 public MyStructInfo StructInfo {
2734 public bool IsAssigned (EmitContext ec, Location loc)
2735 {/* FIXME: we shouldn't just skip this!!!
2736 if (!ec.DoFlowAnalysis || ec.CurrentBranching.IsVariableAssigned (this))
2739 MyStructInfo struct_info = StructInfo;
2740 if ((struct_info == null) || (struct_info.HasNonPublicFields && (Name != null))) {
2741 Report.Error (165, loc, "Use of unassigned local variable '" + Name + "'");
2742 ec.CurrentBranching.SetVariableAssigned (this);
2746 int count = struct_info.Count;
2748 for (int i = 0; i < count; i++) {
2749 if (!ec.CurrentBranching.IsVariableAssigned (this, i+1)) {
2751 Report.Error (165, loc,
2752 "Use of unassigned local variable '" +
2754 ec.CurrentBranching.SetVariableAssigned (this);
2758 FieldInfo field = struct_info [i];
2759 Report.Error (171, loc,
2760 "Field '" + TypeManager.MonoBASIC_Name (VariableType) +
2761 "." + field.Name + "' must be fully initialized " +
2762 "before control leaves the constructor");
2770 public bool IsFieldAssigned (EmitContext ec, string name, Location loc)
2772 if (!ec.DoFlowAnalysis || ec.CurrentBranching.IsVariableAssigned (this) ||
2773 (struct_info == null))
2776 int field_idx = StructInfo [name];
2780 if (!ec.CurrentBranching.IsVariableAssigned (this, field_idx)) {
2781 Report.Error (170, loc,
2782 "Use of possibly unassigned field '" + name + "'");
2783 ec.CurrentBranching.SetVariableAssigned (this, field_idx);
2790 public void SetAssigned (EmitContext ec)
2792 if (ec.DoFlowAnalysis)
2793 ec.CurrentBranching.SetVariableAssigned (this);
2796 public void SetFieldAssigned (EmitContext ec, string name)
2798 if (ec.DoFlowAnalysis && (struct_info != null))
2799 ec.CurrentBranching.SetVariableAssigned (this, StructInfo [name]);
2802 public bool Resolve (DeclSpace decl)
2804 if (struct_info != null)
2807 if (VariableType == null)
2808 VariableType = decl.ResolveType (Type, false, Location);
2810 if (VariableType == null)
2813 struct_info = MyStructInfo.GetStructInfo (VariableType);
2818 public void MakePinned ()
2820 TypeManager.MakePinned (LocalBuilder);
2823 public override string ToString ()
2825 return "VariableInfo (" + Number + "," + Type + "," + Location + ")";
2830 public class StatementSequence : Expression {
2832 ArrayList args, originalArgs;
2834 bool isRetValRequired;
2835 bool isLeftHandSide;
2836 bool isIndexerAccess;
2838 Expression type_expr;
2839 bool is_resolved = false;
2841 public StatementSequence (Block parent, Location loc, Expression expr)
2842 : this (parent, loc, expr, null)
2845 public StatementSequence (Block parent, Location loc, Expression expr, string name,
2846 Expression type_expr, ArrayList a, bool isRetValRequired,
2847 bool isLeftHandSide)
2848 : this (parent, loc, expr, a)
2850 this.memberName = name;
2851 this.type_expr = type_expr;
2852 this.isRetValRequired = isRetValRequired;
2853 this.isLeftHandSide = isLeftHandSide;
2856 public StatementSequence (Block parent, Location loc, Expression expr, ArrayList a,
2857 bool isRetValRequired, bool isLeftHandSide)
2858 : this (parent, loc, expr, a)
2860 this.isRetValRequired = isRetValRequired;
2861 this.isLeftHandSide = isLeftHandSide;
2862 if (expr is MemberAccess) {
2863 this.expr = ((MemberAccess)expr).Expr;
2864 this.memberName = ((MemberAccess)expr).Identifier;
2865 this.isIndexerAccess = false;
2866 } else if (expr is IndexerAccess) {
2867 this.expr = ((IndexerAccess) expr).Instance;
2868 this.memberName = "";
2869 this.isIndexerAccess = true;
2873 public StatementSequence (Block parent, Location loc, Expression expr, ArrayList a)
2875 stmtBlock = new Block (parent);
2877 originalArgs = new ArrayList ();
2879 for (int index = 0; index < a.Count; index ++) {
2880 Argument argument = (Argument) args [index];
2881 originalArgs.Add (new Argument (argument.Expr, argument.ArgType));
2886 stmtBlock.IsLateBindingRequired = true;
2888 this.isRetValRequired = this.isLeftHandSide = false;
2889 this.memberName = "";
2890 this.type_expr = null;
2893 public ArrayList Arguments {
2902 public bool IsLeftHandSide {
2904 isLeftHandSide = value;
2908 public Block StmtBlock {
2914 public override Expression DoResolve (EmitContext ec)
2918 if (!stmtBlock.Resolve (ec))
2920 eclass = ExprClass.Value;
2921 type = TypeManager.object_type;
2926 public bool ResolveArguments (EmitContext ec) {
2928 bool argNamesFound = false;
2929 if (Arguments != null)
2931 for (int index = 0; index < Arguments.Count; index ++)
2933 Argument a = (Argument) Arguments [index];
2934 if (a.ParamName == null || a.ParamName == "") {
2935 if (argNamesFound) {
2936 Report.Error (30241, loc, "Named Argument expected");
2940 argNamesFound = true;
2941 if (a.ArgType == Argument.AType.NoArg)
2942 a = new Argument (Parser.DecomposeQI ("System.Reflection.Missing.Value", loc), Argument.AType.Expression);
2943 if (!a.Resolve (ec, loc))
2945 Arguments [index] = a;
2951 public void GenerateLateBindingStatements ()
2954 ArrayList arrayInitializers = new ArrayList ();
2955 ArrayList ArgumentNames = null;
2957 //arrayInitializers = new ArrayList ();
2958 argCount = args.Count;
2959 for (int index = 0; index < args.Count; index ++) {
2960 Argument a = (Argument) args [index];
2961 Expression argument = a.Expr;
2962 arrayInitializers.Add (argument);
2963 if (a.ParamName != null && a.ParamName != "") {
2964 if (ArgumentNames == null)
2965 ArgumentNames = new ArrayList ();
2966 ArgumentNames.Add (new StringLiteral (a.ParamName));
2971 // __LateBindingArgs = new Object () {arg1, arg2 ...}
2972 ArrayCreation new_expr = new ArrayCreation (Parser.DecomposeQI ("System.Object", loc), "[]", arrayInitializers, loc);
2973 Assign assign_stmt = null;
2975 LocalVariableReference v1 = new LocalVariableReference (stmtBlock, Block.lateBindingArgs, loc);
2976 assign_stmt = new Assign (v1, new_expr, loc);
2977 stmtBlock.AddStatement (new StatementExpression ((ExpressionStatement) assign_stmt, loc));
2978 // __LateBindingArgNames = new string () { argument names}
2979 LocalVariableReference v2 = null;
2980 if (ArgumentNames != null && ArgumentNames.Count > 0) {
2981 new_expr = new ArrayCreation (Parser.DecomposeQI ("System.String", loc), "[]", ArgumentNames, loc);
2982 v2 = new LocalVariableReference (stmtBlock, Block.lateBindingArgNames, loc);
2983 assign_stmt = new Assign (v2, new_expr, loc);
2984 stmtBlock.AddStatement (new StatementExpression ((ExpressionStatement) assign_stmt, loc));
2987 //string memName = "";
2988 //bool isIndexerAccess = true;
2990 ArrayList invocationArgs = new ArrayList ();
2991 if (isIndexerAccess || memberName == "") {
2992 invocationArgs.Add (new Argument (expr, Argument.AType.Expression));
2993 invocationArgs.Add (new Argument (v1, Argument.AType.Expression));
2994 invocationArgs.Add (new Argument (NullLiteral.Null, Argument.AType.Expression));
2995 Expression tmp = null;
2996 if (!isLeftHandSide)
2997 tmp = Parser.DecomposeQI ("Microsoft.VisualBasic.CompilerServices.LateBinding.LateIndexGet", loc);
2999 tmp = Parser.DecomposeQI ("Microsoft.VisualBasic.CompilerServices.LateBinding.LateIndexSet", loc);
3000 Invocation invStmt = new Invocation (tmp, invocationArgs, Location.Null);
3001 invStmt.IsLateBinding = true;
3002 stmtBlock.AddStatement (new StatementExpression ((ExpressionStatement) invStmt, loc));
3007 invocationArgs.Add (new Argument (expr, Argument.AType.Expression));
3009 invocationArgs.Add (new Argument (NullLiteral.Null, Argument.AType.Expression));
3010 if (type_expr != null)
3011 invocationArgs.Add (new Argument (type_expr, Argument.AType.Expression));
3013 invocationArgs.Add (new Argument (NullLiteral.Null, Argument.AType.Expression));
3014 invocationArgs.Add (new Argument (new StringLiteral (memberName), Argument.AType.Expression));
3015 invocationArgs.Add (new Argument (v1, Argument.AType.Expression));
3016 if (ArgumentNames != null && ArgumentNames.Count > 0)
3017 invocationArgs.Add (new Argument (v2, Argument.AType.Expression));
3019 invocationArgs.Add (new Argument (NullLiteral.Null, Argument.AType.Expression));
3021 // __LateBindingCopyBack = new Boolean (no_of_args) {}
3022 bool isCopyBackRequired = false;
3023 if (!isLeftHandSide) {
3024 for (int i = 0; i < argCount; i++) {
3025 Argument origArg = (Argument) Arguments [i];
3026 Expression origExpr = origArg.Expr;
3027 if (!(origExpr is Constant || origArg.ArgType == Argument.AType.NoArg))
3028 isCopyBackRequired = true;
3032 LocalVariableReference v3 = new LocalVariableReference (stmtBlock, Block.lateBindingCopyBack, loc);
3033 if (isCopyBackRequired) {
3034 ArrayList rank_specifier = new ArrayList ();
3035 rank_specifier.Add (new IntLiteral (argCount));
3036 arrayInitializers = new ArrayList ();
3037 for (int i = 0; i < argCount; i++) {
3038 Argument a = (Argument) Arguments [i];
3039 Expression origExpr = a.Expr;
3040 if (origExpr is Constant || a.ArgType == Argument.AType.NoArg || origExpr is New)
3041 arrayInitializers.Add (new BoolLiteral (false));
3043 arrayInitializers.Add (new BoolLiteral (true));
3046 new_expr = new ArrayCreation (Parser.DecomposeQI ("System.Boolean", loc), "[]", arrayInitializers, loc);
3047 assign_stmt = new Assign (v3, new_expr, loc);
3048 stmtBlock.AddStatement (new StatementExpression ((ExpressionStatement) assign_stmt, loc));
3049 invocationArgs.Add (new Argument (v3, Argument.AType.Expression));
3050 } else if (! isLeftHandSide) {
3051 invocationArgs.Add (new Argument (NullLiteral.Null, Argument.AType.Expression));
3054 Expression etmp = null;
3055 if (isLeftHandSide) {
3057 etmp = Parser.DecomposeQI ("Microsoft.VisualBasic.CompilerServices.LateBinding.LateSet", loc);
3058 } else if (isRetValRequired) {
3060 etmp = Parser.DecomposeQI ("Microsoft.VisualBasic.CompilerServices.LateBinding.LateGet", loc);
3062 etmp = Parser.DecomposeQI ("Microsoft.VisualBasic.CompilerServices.LateBinding.LateCall", loc);
3065 Invocation inv_stmt = new Invocation (etmp, invocationArgs, Location.Null);
3066 inv_stmt.IsLateBinding = true;
3067 stmtBlock.AddStatement (new StatementExpression ((ExpressionStatement) inv_stmt, loc));
3069 if (! isCopyBackRequired)
3072 for (int i = argCount - 1; i >= 0; i --) {
3073 Argument arg = (Argument) originalArgs [i];
3074 Expression origExpr = (Expression) arg.Expr;
3075 if (arg.ArgType == Argument.AType.NoArg)
3077 if (origExpr is Constant)
3079 if (origExpr is New)
3082 Expression intExpr = new IntLiteral (i);
3083 ArrayList argsLocal = new ArrayList ();
3084 argsLocal.Add (new Argument (intExpr, Argument.AType.Expression));
3085 Expression indexExpr = new Invocation (new SimpleName (Block.lateBindingCopyBack, loc), argsLocal, loc);
3086 Expression value = new Invocation (new SimpleName (Block.lateBindingArgs, loc), argsLocal, loc);
3087 assign_stmt = new Assign (origExpr, value, loc);
3088 Expression boolExpr = new Binary (Binary.Operator.Inequality, indexExpr, new BoolLiteral (false), loc);
3089 Statement ifStmt = new If (boolExpr, new StatementExpression ((ExpressionStatement) assign_stmt, loc), loc);
3090 stmtBlock.AddStatement (ifStmt);
3094 public override void Emit (EmitContext ec)
3096 stmtBlock.Emit (ec);
3100 public class SwitchLabel {
3101 public enum LabelType : byte {
3102 Operator, Range, Label, Else
3105 Expression label, start, end;
3106 LabelType label_type;
3107 Expression label_condition, start_condition, end_condition;
3108 Binary.Operator oper;
3109 public Location loc;
3110 public Label ILLabel;
3111 public Label ILLabelCode;
3114 // if expr == null, then it is the default case.
3116 public SwitchLabel (Expression start, Expression end, LabelType ltype, Binary.Operator oper, Location l) {
3119 this.label_type = ltype;
3122 label_condition = start_condition = end_condition = null;
3125 public SwitchLabel (Expression expr, LabelType ltype, Binary.Operator oper, Location l)
3129 label_condition = start_condition = end_condition = null;
3131 this.label_type = ltype;
3135 public Expression Label {
3141 public LabelType Type {
3147 public Expression ConditionStart {
3149 return start_condition;
3153 public Expression ConditionEnd {
3155 return end_condition;
3159 public Expression ConditionLabel {
3161 return label_condition;
3166 // Resolves the expression, reduces it to a literal if possible
3167 // and then converts it to the requested type.
3169 public bool ResolveAndReduce (EmitContext ec, Expression expr)
3171 ILLabel = ec.ig.DefineLabel ();
3172 ILLabelCode = ec.ig.DefineLabel ();
3174 Expression e = null;
3175 switch (label_type) {
3176 case LabelType.Label :
3179 e = label.Resolve (ec);
3181 e = Expression.ConvertImplicit (ec, e, expr.Type, loc);
3184 label_condition = new Binary (Binary.Operator.Equality, expr, e, loc);
3185 if ((label_condition = label_condition.DoResolve (ec)) == null)
3188 case LabelType.Operator :
3189 e = label.Resolve (ec);
3190 label_condition = new Binary (oper, expr, e, loc);
3191 if ((label_condition = label_condition.DoResolve (ec)) == null)
3194 case LabelType.Range :
3195 if (start == null || end == null)
3197 e = start.Resolve (ec);
3199 e = Expression.ConvertImplicit (ec, e, expr.Type, loc);
3202 start_condition = new Binary (Binary.Operator.GreaterThanOrEqual, expr, e, loc);
3203 start_condition = start_condition.Resolve (ec);
3204 e = end.Resolve (ec);
3206 e = Expression.ConvertImplicit (ec, e, expr.Type, loc);
3209 end_condition = new Binary (Binary.Operator.LessThanOrEqual, expr, e, loc);
3210 end_condition = end_condition.Resolve (ec);
3211 if (start_condition == null || end_condition == null)
3215 case LabelType.Else :
3222 public class SwitchSection {
3223 // An array of SwitchLabels.
3224 public readonly ArrayList Labels;
3225 public readonly Block Block;
3227 public SwitchSection (ArrayList labels, Block block)
3234 public class Switch : Statement {
3235 public readonly ArrayList Sections;
3236 public Expression Expr;
3239 /// Maps constants whose type type SwitchType to their SwitchLabels.
3241 public Hashtable Elements;
3244 /// The governing switch type
3246 public Type SwitchType;
3252 Label default_target;
3253 Expression new_expr;
3256 // The types allowed to be implicitly cast from
3257 // on the governing type
3259 //static Type [] allowed_types;
3261 public Switch (Expression e, ArrayList sects, Location l)
3268 public bool GotDefault {
3274 public Label DefaultTarget {
3276 return default_target;
3281 // Determines the governing type for a switch. The returned
3282 // expression might be the expression from the switch, or an
3283 // expression that includes any potential conversions to the
3284 // integral types or to string.
3286 Expression SwitchGoverningType (EmitContext ec, Type t)
3288 if (t == TypeManager.byte_type ||
3289 t == TypeManager.short_type ||
3290 t == TypeManager.int32_type ||
3291 t == TypeManager.int64_type ||
3292 t == TypeManager.decimal_type ||
3293 t == TypeManager.float_type ||
3294 t == TypeManager.double_type ||
3295 t == TypeManager.date_type ||
3296 t == TypeManager.char_type ||
3297 t == TypeManager.object_type ||
3298 t == TypeManager.string_type ||
3299 t == TypeManager.bool_type ||
3300 t.IsSubclassOf (TypeManager.enum_type))
3303 if (allowed_types == null){
3304 allowed_types = new Type [] {
3305 TypeManager.sbyte_type,
3306 TypeManager.byte_type,
3307 TypeManager.short_type,
3308 TypeManager.ushort_type,
3309 TypeManager.int32_type,
3310 TypeManager.uint32_type,
3311 TypeManager.int64_type,
3312 TypeManager.uint64_type,
3313 TypeManager.char_type,
3314 TypeManager.bool_type,
3315 TypeManager.string_type
3320 // Try to find a *user* defined implicit conversion.
3322 // If there is no implicit conversion, or if there are multiple
3323 // conversions, we have to report an error
3325 Expression converted = null;
3326 foreach (Type tt in allowed_types){
3329 e = Expression.ImplicitUserConversion (ec, Expr, tt, loc);
3333 if (converted != null){
3334 Report.Error (-12, loc, "More than one conversion to an integral " +
3335 " type exists for type '" +
3336 TypeManager.MonoBASIC_Name (Expr.Type)+"'");
3346 void error152 (string n)
3349 152, "The label '" + n + ":' " +
3350 "is already present on this switch statement");
3354 // Performs the basic sanity checks on the switch statement
3355 // (looks for duplicate keys and non-constant expressions).
3357 // It also returns a hashtable with the keys that we will later
3358 // use to compute the switch tables
3360 bool CheckSwitch (EmitContext ec)
3362 //Type compare_type;
3364 Elements = new CaseInsensitiveHashtable ();
3366 got_default = false;
3369 if (TypeManager.IsEnumType (SwitchType)){
3370 compare_type = TypeManager.EnumToUnderlying (SwitchType);
3372 compare_type = SwitchType;
3375 for (int secIndex = 0; secIndex < Sections.Count; secIndex ++) {
3376 SwitchSection ss = (SwitchSection) Sections [secIndex];
3377 for (int labelIndex = 0; labelIndex < ss.Labels.Count; labelIndex ++) {
3378 SwitchLabel sl = (SwitchLabel) ss.Labels [labelIndex];
3379 if (!sl.ResolveAndReduce (ec, Expr)){
3384 if (sl.Type == SwitchLabel.LabelType.Else){
3386 error152 ("default");
3400 void EmitObjectInteger (ILGenerator ig, object k)
3403 IntConstant.EmitInt (ig, (int) k);
3404 else if (k is Constant) {
3405 EmitObjectInteger (ig, ((Constant) k).GetValue ());
3408 IntConstant.EmitInt (ig, unchecked ((int) (uint) k));
3411 if ((long) k >= int.MinValue && (long) k <= int.MaxValue)
3413 IntConstant.EmitInt (ig, (int) (long) k);
3414 ig.Emit (OpCodes.Conv_I8);
3417 LongConstant.EmitLong (ig, (long) k);
3419 else if (k is ulong)
3421 if ((ulong) k < (1L<<32))
3423 IntConstant.EmitInt (ig, (int) (long) k);
3424 ig.Emit (OpCodes.Conv_U8);
3428 LongConstant.EmitLong (ig, unchecked ((long) (ulong) k));
3432 IntConstant.EmitInt (ig, (int) ((char) k));
3433 else if (k is sbyte)
3434 IntConstant.EmitInt (ig, (int) ((sbyte) k));
3436 IntConstant.EmitInt (ig, (int) ((byte) k));
3437 else if (k is short)
3438 IntConstant.EmitInt (ig, (int) ((short) k));
3439 else if (k is ushort)
3440 IntConstant.EmitInt (ig, (int) ((ushort) k));
3442 IntConstant.EmitInt (ig, ((bool) k) ? 1 : 0);
3444 throw new Exception ("Unhandled case");
3447 // structure used to hold blocks of keys while calculating table switch
3448 class KeyBlock : IComparable
3450 public KeyBlock (long _nFirst)
3452 nFirst = nLast = _nFirst;
3456 public ArrayList rgKeys = null;
3459 get { return (int) (nLast - nFirst + 1); }
3461 public static long TotalLength (KeyBlock kbFirst, KeyBlock kbLast)
3463 return kbLast.nLast - kbFirst.nFirst + 1;
3465 public int CompareTo (object obj)
3467 KeyBlock kb = (KeyBlock) obj;
3468 int nLength = Length;
3469 int nLengthOther = kb.Length;
3470 if (nLengthOther == nLength)
3471 return (int) (kb.nFirst - nFirst);
3472 return nLength - nLengthOther;
3478 /// This method emits code for a lookup-based switch statement (non-string)
3479 /// Basically it groups the cases into blocks that are at least half full,
3480 /// and then spits out individual lookup opcodes for each block.
3481 /// It emits the longest blocks first, and short blocks are just
3482 /// handled with direct compares.
3484 /// <param name="ec"></param>
3485 /// <param name="val"></param>
3486 /// <returns></returns>
3487 bool TableSwitchEmit (EmitContext ec, LocalBuilder val)
3489 int cElements = Elements.Count;
3490 object [] rgKeys = new object [cElements];
3491 Elements.Keys.CopyTo (rgKeys, 0);
3492 Array.Sort (rgKeys);
3494 // initialize the block list with one element per key
3495 ArrayList rgKeyBlocks = new ArrayList ();
3496 foreach (object key in rgKeys)
3497 rgKeyBlocks.Add (new KeyBlock (Convert.ToInt64 (key)));
3500 // iteratively merge the blocks while they are at least half full
3501 // there's probably a really cool way to do this with a tree...
3502 while (rgKeyBlocks.Count > 1)
3504 ArrayList rgKeyBlocksNew = new ArrayList ();
3505 kbCurr = (KeyBlock) rgKeyBlocks [0];
3506 for (int ikb = 1; ikb < rgKeyBlocks.Count; ikb++)
3508 KeyBlock kb = (KeyBlock) rgKeyBlocks [ikb];
3509 if ((kbCurr.Length + kb.Length) * 2 >= KeyBlock.TotalLength (kbCurr, kb))
3512 kbCurr.nLast = kb.nLast;
3516 // start a new block
3517 rgKeyBlocksNew.Add (kbCurr);
3521 rgKeyBlocksNew.Add (kbCurr);
3522 if (rgKeyBlocks.Count == rgKeyBlocksNew.Count)
3524 rgKeyBlocks = rgKeyBlocksNew;
3527 // initialize the key lists
3528 foreach (KeyBlock kb in rgKeyBlocks)
3529 kb.rgKeys = new ArrayList ();
3531 // fill the key lists
3533 if (rgKeyBlocks.Count > 0) {
3534 kbCurr = (KeyBlock) rgKeyBlocks [0];
3535 foreach (object key in rgKeys)
3537 bool fNextBlock = (key is UInt64) ? (ulong) key > (ulong) kbCurr.nLast : Convert.ToInt64 (key) > kbCurr.nLast;
3539 kbCurr = (KeyBlock) rgKeyBlocks [++iBlockCurr];
3540 kbCurr.rgKeys.Add (key);
3544 // sort the blocks so we can tackle the largest ones first
3545 rgKeyBlocks.Sort ();
3547 // okay now we can start...
3548 ILGenerator ig = ec.ig;
3549 Label lblEnd = ig.DefineLabel (); // at the end ;-)
3550 Label lblDefault = ig.DefineLabel ();
3552 Type typeKeys = null;
3553 if (rgKeys.Length > 0)
3554 typeKeys = rgKeys [0].GetType (); // used for conversions
3556 for (int iBlock = rgKeyBlocks.Count - 1; iBlock >= 0; --iBlock)
3558 KeyBlock kb = ((KeyBlock) rgKeyBlocks [iBlock]);
3559 lblDefault = (iBlock == 0) ? DefaultTarget : ig.DefineLabel ();
3562 foreach (object key in kb.rgKeys)
3564 ig.Emit (OpCodes.Ldloc, val);
3565 EmitObjectInteger (ig, key);
3566 SwitchLabel sl = (SwitchLabel) Elements [key];
3567 ig.Emit (OpCodes.Beq, sl.ILLabel);
3572 // TODO: if all the keys in the block are the same and there are
3573 // no gaps/defaults then just use a range-check.
3574 if (SwitchType == TypeManager.int64_type ||
3575 SwitchType == TypeManager.uint64_type)
3577 // TODO: optimize constant/I4 cases
3579 // check block range (could be > 2^31)
3580 ig.Emit (OpCodes.Ldloc, val);
3581 EmitObjectInteger (ig, Convert.ChangeType (kb.nFirst, typeKeys));
3582 ig.Emit (OpCodes.Blt, lblDefault);
3583 ig.Emit (OpCodes.Ldloc, val);
3584 EmitObjectInteger (ig, Convert.ChangeType (kb.nFirst, typeKeys));
3585 ig.Emit (OpCodes.Bgt, lblDefault);
3588 ig.Emit (OpCodes.Ldloc, val);
3591 EmitObjectInteger (ig, Convert.ChangeType (kb.nFirst, typeKeys));
3592 ig.Emit (OpCodes.Sub);
3594 ig.Emit (OpCodes.Conv_I4); // assumes < 2^31 labels!
3599 ig.Emit (OpCodes.Ldloc, val);
3600 int nFirst = (int) kb.nFirst;
3603 IntConstant.EmitInt (ig, nFirst);
3604 ig.Emit (OpCodes.Sub);
3606 else if (nFirst < 0)
3608 IntConstant.EmitInt (ig, -nFirst);
3609 ig.Emit (OpCodes.Add);
3613 // first, build the list of labels for the switch
3615 int cJumps = kb.Length;
3616 Label [] rgLabels = new Label [cJumps];
3617 for (int iJump = 0; iJump < cJumps; iJump++)
3619 object key = kb.rgKeys [iKey];
3620 if (Convert.ToInt64 (key) == kb.nFirst + iJump)
3622 SwitchLabel sl = (SwitchLabel) Elements [key];
3623 rgLabels [iJump] = sl.ILLabel;
3627 rgLabels [iJump] = lblDefault;
3629 // emit the switch opcode
3630 ig.Emit (OpCodes.Switch, rgLabels);
3633 // mark the default for this block
3635 ig.MarkLabel (lblDefault);
3638 // TODO: find the default case and emit it here,
3639 // to prevent having to do the following jump.
3640 // make sure to mark other labels in the default section
3642 // the last default just goes to the end
3643 ig.Emit (OpCodes.Br, lblDefault);
3645 // now emit the code for the sections
3646 bool fFoundDefault = false;
3647 bool fAllReturn = true;
3648 foreach (SwitchSection ss in Sections)
3650 foreach (SwitchLabel sl in ss.Labels)
3652 ig.MarkLabel (sl.ILLabel);
3653 ig.MarkLabel (sl.ILLabelCode);
3654 if (sl.Label == null)
3656 ig.MarkLabel (lblDefault);
3657 fFoundDefault = true;
3660 bool returns = ss.Block.Emit (ec);
3661 fAllReturn &= returns;
3662 //ig.Emit (OpCodes.Br, lblEnd);
3665 if (!fFoundDefault) {
3666 ig.MarkLabel (lblDefault);
3669 ig.MarkLabel (lblEnd);
3674 // This simple emit switch works, but does not take advantage of the
3676 // TODO: remove non-string logic from here
3677 // TODO: binary search strings?
3679 bool SimpleSwitchEmit (EmitContext ec, LocalBuilder val)
3681 ILGenerator ig = ec.ig;
3682 Label end_of_switch = ig.DefineLabel ();
3683 Label next_test = ig.DefineLabel ();
3684 Label null_target = ig.DefineLabel ();
3685 bool default_found = false;
3686 bool first_test = true;
3687 bool pending_goto_end = false;
3688 bool all_return = true;
3689 bool is_string = false;
3693 // Special processing for strings: we cant compare
3696 if (SwitchType == TypeManager.string_type){
3697 ig.Emit (OpCodes.Ldloc, val);
3700 if (Elements.Contains (NullLiteral.Null)){
3701 ig.Emit (OpCodes.Brfalse, null_target);
3703 ig.Emit (OpCodes.Brfalse, default_target);
3705 ig.Emit (OpCodes.Ldloc, val);
3706 ig.Emit (OpCodes.Call, TypeManager.string_isinterneted_string);
3707 ig.Emit (OpCodes.Stloc, val);
3710 foreach (SwitchSection ss in Sections){
3711 Label sec_begin = ig.DefineLabel ();
3713 if (pending_goto_end)
3714 ig.Emit (OpCodes.Br, end_of_switch);
3716 int label_count = ss.Labels.Count;
3718 foreach (SwitchLabel sl in ss.Labels){
3719 ig.MarkLabel (sl.ILLabel);
3722 ig.MarkLabel (next_test);
3723 next_test = ig.DefineLabel ();
3726 // If we are the default target
3728 if (sl.Label == null){
3729 ig.MarkLabel (default_target);
3730 default_found = true;
3732 object lit = sl.Converted;
3734 if (lit is NullLiteral){
3736 if (label_count == 1)
3737 ig.Emit (OpCodes.Br, next_test);
3742 StringConstant str = (StringConstant) lit;
3744 ig.Emit (OpCodes.Ldloc, val);
3745 ig.Emit (OpCodes.Ldstr, str.Value);
3746 if (label_count == 1)
3747 ig.Emit (OpCodes.Bne_Un, next_test);
3749 ig.Emit (OpCodes.Beq, sec_begin);
3751 ig.Emit (OpCodes.Ldloc, val);
3752 EmitObjectInteger (ig, lit);
3753 ig.Emit (OpCodes.Ceq);
3754 if (label_count == 1)
3755 ig.Emit (OpCodes.Brfalse, next_test);
3757 ig.Emit (OpCodes.Brtrue, sec_begin);
3761 if (label_count != 1)
3762 ig.Emit (OpCodes.Br, next_test);
3765 ig.MarkLabel (null_target);
3766 ig.MarkLabel (sec_begin);
3767 foreach (SwitchLabel sl in ss.Labels)
3768 ig.MarkLabel (sl.ILLabelCode);
3770 bool returns = ss.Block.Emit (ec);
3772 pending_goto_end = false;
3775 pending_goto_end = true;
3779 if (!default_found){
3780 ig.MarkLabel (default_target);
3783 ig.MarkLabel (next_test);
3784 ig.MarkLabel (end_of_switch);
3790 public override bool Resolve (EmitContext ec)
3792 Expr = Expr.Resolve (ec);
3796 new_expr = SwitchGoverningType (ec, Expr.Type);
3797 if (new_expr == null){
3798 Report.Error (30338, loc, "'Select' expression cannot be of type '" + Expr.Type +"'");
3803 SwitchType = new_expr.Type;
3805 if (!CheckSwitch (ec))
3808 Switch old_switch = ec.Switch;
3810 ec.Switch.SwitchType = SwitchType;
3812 ec.StartFlowBranching (FlowBranchingType.SWITCH, loc);
3815 foreach (SwitchSection ss in Sections){
3817 ec.CurrentBranching.CreateSibling ();
3821 if (ss.Block.Resolve (ec) != true)
3827 ec.CurrentBranching.CreateSibling ();
3829 ec.EndFlowBranching ();
3830 ec.Switch = old_switch;
3835 protected override bool DoEmit (EmitContext ec)
3837 ILGenerator ig = ec.ig;
3839 // Setup the codegen context
3841 Label old_end = ec.LoopEnd;
3842 Switch old_switch = ec.Switch;
3844 ec.LoopEnd = ig.DefineLabel ();
3847 for (int secIndex = 0; secIndex < Sections.Count; secIndex ++) {
3848 SwitchSection section = (SwitchSection) Sections [secIndex];
3849 Label sLabel = ig.DefineLabel ();
3850 Label lLabel = ig.DefineLabel ();
3851 ArrayList Labels = section.Labels;
3852 for (int labelIndex = 0; labelIndex < Labels.Count; labelIndex ++) {
3853 SwitchLabel sl = (SwitchLabel) Labels [labelIndex];
3855 case SwitchLabel.LabelType.Range :
3856 if (labelIndex + 1 == Labels.Count) {
3857 EmitBoolExpression (ec, sl.ConditionStart, sLabel, false);
3858 EmitBoolExpression (ec, sl.ConditionEnd, sLabel, false);
3859 ig.Emit (OpCodes.Br, lLabel);
3861 Label newLabel = ig.DefineLabel ();
3862 EmitBoolExpression (ec, sl.ConditionStart, newLabel, false);
3863 EmitBoolExpression (ec, sl.ConditionEnd, newLabel, false);
3864 ig.Emit (OpCodes.Br, lLabel);
3865 ig.MarkLabel (newLabel);
3868 case SwitchLabel.LabelType.Else :
3869 // Nothing to be done here
3871 case SwitchLabel.LabelType.Operator :
3872 EmitBoolExpression (ec, sl.ConditionLabel, lLabel, true);
3873 if (labelIndex + 1 == Labels.Count)
3874 ig.Emit (OpCodes.Br, sLabel);
3876 case SwitchLabel.LabelType.Label :
3877 EmitBoolExpression (ec, sl.ConditionLabel, lLabel, true);
3878 if (labelIndex + 1 == Labels.Count)
3879 ig.Emit (OpCodes.Br, sLabel);
3884 ig.MarkLabel (lLabel);
3885 section.Block.Emit (ec);
3886 ig.MarkLabel (sLabel);
3889 // Restore context state.
3890 ig.MarkLabel (ec.LoopEnd);
3893 // Restore the previous context
3895 ec.LoopEnd = old_end;
3896 ec.Switch = old_switch;
3901 public class Lock : Statement {
3903 Statement Statement;
3905 public Lock (Expression expr, Statement stmt, Location l)
3912 public override bool Resolve (EmitContext ec)
3914 expr = expr.Resolve (ec);
3915 return Statement.Resolve (ec) && expr != null;
3918 protected override bool DoEmit (EmitContext ec)
3920 Type type = expr.Type;
3923 if (type.IsValueType){
3924 Report.Error (30582, loc, "lock statement requires the expression to be " +
3925 " a reference type (type is: '" +
3926 TypeManager.MonoBASIC_Name (type) + "'");
3930 ILGenerator ig = ec.ig;
3931 LocalBuilder temp = ig.DeclareLocal (type);
3934 ig.Emit (OpCodes.Dup);
3935 ig.Emit (OpCodes.Stloc, temp);
3936 ig.Emit (OpCodes.Call, TypeManager.void_monitor_enter_object);
3939 ig.BeginExceptionBlock ();
3940 bool old_in_try = ec.InTry;
3942 Label finish = ig.DefineLabel ();
3943 val = Statement.Emit (ec);
3944 ec.InTry = old_in_try;
3945 // ig.Emit (OpCodes.Leave, finish);
3947 ig.MarkLabel (finish);
3950 ig.BeginFinallyBlock ();
3951 ig.Emit (OpCodes.Ldloc, temp);
3952 ig.Emit (OpCodes.Call, TypeManager.void_monitor_exit_object);
3953 ig.EndExceptionBlock ();
3959 public class Unchecked : Statement {
3960 public readonly Block Block;
3962 public Unchecked (Block b)
3967 public override bool Resolve (EmitContext ec)
3969 return Block.Resolve (ec);
3972 protected override bool DoEmit (EmitContext ec)
3974 bool previous_state = ec.CheckState;
3975 bool previous_state_const = ec.ConstantCheckState;
3978 ec.CheckState = false;
3979 ec.ConstantCheckState = false;
3980 val = Block.Emit (ec);
3981 ec.CheckState = previous_state;
3982 ec.ConstantCheckState = previous_state_const;
3988 public class Checked : Statement {
3989 public readonly Block Block;
3991 public Checked (Block b)
3996 public override bool Resolve (EmitContext ec)
3998 bool previous_state = ec.CheckState;
3999 bool previous_state_const = ec.ConstantCheckState;
4001 ec.CheckState = true;
4002 ec.ConstantCheckState = true;
4003 bool ret = Block.Resolve (ec);
4004 ec.CheckState = previous_state;
4005 ec.ConstantCheckState = previous_state_const;
4010 protected override bool DoEmit (EmitContext ec)
4012 bool previous_state = ec.CheckState;
4013 bool previous_state_const = ec.ConstantCheckState;
4016 ec.CheckState = true;
4017 ec.ConstantCheckState = true;
4018 val = Block.Emit (ec);
4019 ec.CheckState = previous_state;
4020 ec.ConstantCheckState = previous_state_const;
4026 public class Unsafe : Statement {
4027 public readonly Block Block;
4029 public Unsafe (Block b)
4034 public override bool Resolve (EmitContext ec)
4036 bool previous_state = ec.InUnsafe;
4040 val = Block.Resolve (ec);
4041 ec.InUnsafe = previous_state;
4046 protected override bool DoEmit (EmitContext ec)
4048 bool previous_state = ec.InUnsafe;
4052 val = Block.Emit (ec);
4053 ec.InUnsafe = previous_state;
4062 public class Fixed : Statement {
4064 ArrayList declarators;
4065 Statement statement;
4070 public bool is_object;
4071 public VariableInfo vi;
4072 public Expression expr;
4073 public Expression converted;
4076 public Fixed (Expression type, ArrayList decls, Statement stmt, Location l)
4079 declarators = decls;
4084 public override bool Resolve (EmitContext ec)
4086 expr_type = ec.DeclSpace.ResolveType (type, false, loc);
4087 if (expr_type == null)
4090 data = new FixedData [declarators.Count];
4093 foreach (Pair p in declarators){
4094 VariableInfo vi = (VariableInfo) p.First;
4095 Expression e = (Expression) p.Second;
4100 // The rules for the possible declarators are pretty wise,
4101 // but the production on the grammar is more concise.
4103 // So we have to enforce these rules here.
4105 // We do not resolve before doing the case 1 test,
4106 // because the grammar is explicit in that the token &
4107 // is present, so we need to test for this particular case.
4111 // Case 1: & object.
4113 if (e is Unary && ((Unary) e).Oper == Unary.Operator.AddressOf){
4114 Expression child = ((Unary) e).Expr;
4117 if (child is ParameterReference || child is LocalVariableReference){
4120 "No need to use fixed statement for parameters or " +
4121 "local variable declarations (address is already " +
4130 child = ((Unary) e).Expr;
4132 if (!TypeManager.VerifyUnManaged (child.Type, loc))
4135 data [i].is_object = true;
4137 data [i].converted = null;
4151 if (e.Type.IsArray){
4152 Type array_type = e.Type.GetElementType ();
4156 // Provided that array_type is unmanaged,
4158 if (!TypeManager.VerifyUnManaged (array_type, loc))
4162 // and T* is implicitly convertible to the
4163 // pointer type given in the fixed statement.
4165 ArrayPtr array_ptr = new ArrayPtr (e, loc);
4167 Expression converted = Expression.ConvertImplicitRequired (
4168 ec, array_ptr, vi.VariableType, loc);
4169 if (converted == null)
4172 data [i].is_object = false;
4174 data [i].converted = converted;
4184 if (e.Type == TypeManager.string_type){
4185 data [i].is_object = false;
4187 data [i].converted = null;
4193 return statement.Resolve (ec);
4196 protected override bool DoEmit (EmitContext ec)
4198 ILGenerator ig = ec.ig;
4200 bool is_ret = false;
4202 for (int i = 0; i < data.Length; i++) {
4203 VariableInfo vi = data [i].vi;
4206 // Case 1: & object.
4208 if (data [i].is_object) {
4210 // Store pointer in pinned location
4212 data [i].expr.Emit (ec);
4213 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
4215 is_ret = statement.Emit (ec);
4217 // Clear the pinned variable.
4218 ig.Emit (OpCodes.Ldc_I4_0);
4219 ig.Emit (OpCodes.Conv_U);
4220 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
4228 if (data [i].expr.Type.IsArray){
4230 // Store pointer in pinned location
4232 data [i].converted.Emit (ec);
4234 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
4236 is_ret = statement.Emit (ec);
4238 // Clear the pinned variable.
4239 ig.Emit (OpCodes.Ldc_I4_0);
4240 ig.Emit (OpCodes.Conv_U);
4241 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
4249 if (data [i].expr.Type == TypeManager.string_type){
4250 LocalBuilder pinned_string = ig.DeclareLocal (TypeManager.string_type);
4251 TypeManager.MakePinned (pinned_string);
4253 data [i].expr.Emit (ec);
4254 ig.Emit (OpCodes.Stloc, pinned_string);
4256 Expression sptr = new StringPtr (pinned_string, loc);
4257 Expression converted = Expression.ConvertImplicitRequired (
4258 ec, sptr, vi.VariableType, loc);
4260 if (converted == null)
4263 converted.Emit (ec);
4264 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
4266 is_ret = statement.Emit (ec);
4268 // Clear the pinned variable
4269 ig.Emit (OpCodes.Ldnull);
4270 ig.Emit (OpCodes.Stloc, pinned_string);
4278 public class Catch {
4279 public readonly string Name;
4280 public readonly Block Block;
4281 public Expression Clause;
4282 public readonly Location Location;
4284 Expression type_expr;
4285 //Expression clus_expr;
4288 public Catch (Expression type, string name, Block block, Expression clause, Location l)
4297 public Type CatchType {
4303 public bool IsGeneral {
4305 return type_expr == null;
4309 public bool Resolve (EmitContext ec)
4311 if (type_expr != null) {
4312 type = ec.DeclSpace.ResolveType (type_expr, false, Location);
4316 if (type != TypeManager.exception_type && !type.IsSubclassOf (TypeManager.exception_type)){
4317 Report.Error (30665, Location,
4318 "The type caught or thrown must be derived " +
4319 "from System.Exception");
4325 if (Clause != null) {
4326 Clause = Statement.ResolveBoolean (ec, Clause, Location);
4327 if (Clause == null) {
4332 if (!Block.Resolve (ec))
4339 public class Try : Statement {
4340 public readonly Block Fini, Block;
4341 public readonly ArrayList Specific;
4342 public readonly Catch General;
4345 // specific, general and fini might all be null.
4347 public Try (Block block, ArrayList specific, Catch general, Block fini, Location l)
4349 if (specific == null && general == null){
4350 Console.WriteLine ("CIR.Try: Either specific or general have to be non-null");
4354 this.Specific = specific;
4355 this.General = general;
4360 public override bool Resolve (EmitContext ec)
4364 ec.StartFlowBranching (FlowBranchingType.EXCEPTION, Block.StartLocation);
4366 Report.Debug (1, "START OF TRY BLOCK", Block.StartLocation);
4368 bool old_in_try = ec.InTry;
4371 if (!Block.Resolve (ec))
4374 ec.InTry = old_in_try;
4376 FlowBranching.UsageVector vector = ec.CurrentBranching.CurrentUsageVector;
4378 Report.Debug (1, "START OF CATCH BLOCKS", vector);
4380 foreach (Catch c in Specific){
4381 ec.CurrentBranching.CreateSibling ();
4382 Report.Debug (1, "STARTED SIBLING FOR CATCH", ec.CurrentBranching);
4384 if (c.Name != null) {
4385 VariableInfo vi = c.Block.GetVariableInfo (c.Name);
4387 throw new Exception ();
4392 bool old_in_catch = ec.InCatch;
4395 if (!c.Resolve (ec))
4398 ec.InCatch = old_in_catch;
4400 FlowBranching.UsageVector current = ec.CurrentBranching.CurrentUsageVector;
4402 if (!current.AlwaysReturns && !current.AlwaysBreaks)
4403 vector.AndLocals (current);
4406 Report.Debug (1, "END OF CATCH BLOCKS", ec.CurrentBranching);
4408 if (General != null){
4409 ec.CurrentBranching.CreateSibling ();
4410 Report.Debug (1, "STARTED SIBLING FOR GENERAL", ec.CurrentBranching);
4412 bool old_in_catch = ec.InCatch;
4415 if (!General.Resolve (ec))
4418 ec.InCatch = old_in_catch;
4420 FlowBranching.UsageVector current = ec.CurrentBranching.CurrentUsageVector;
4422 if (!current.AlwaysReturns && !current.AlwaysBreaks)
4423 vector.AndLocals (current);
4426 Report.Debug (1, "END OF GENERAL CATCH BLOCKS", ec.CurrentBranching);
4429 ec.CurrentBranching.CreateSiblingForFinally ();
4430 Report.Debug (1, "STARTED SIBLING FOR FINALLY", ec.CurrentBranching, vector);
4432 bool old_in_finally = ec.InFinally;
4433 ec.InFinally = true;
4435 if (!Fini.Resolve (ec))
4438 ec.InFinally = old_in_finally;
4441 FlowReturns returns = ec.EndFlowBranching ();
4443 FlowBranching.UsageVector f_vector = ec.CurrentBranching.CurrentUsageVector;
4445 Report.Debug (1, "END OF FINALLY", ec.CurrentBranching, returns, vector, f_vector);
4446 ec.CurrentBranching.CurrentUsageVector.Or (vector);
4448 Report.Debug (1, "END OF TRY", ec.CurrentBranching);
4453 protected override bool DoEmit (EmitContext ec)
4455 ILGenerator ig = ec.ig;
4459 Label finish = ig.BeginExceptionBlock ();
4460 ec.HasExitLabel = true;
4461 ec.ExitLabel = finish;
4463 bool old_in_try = ec.InTry;
4465 returns = Block.Emit (ec);
4466 ec.InTry = old_in_try;
4469 // System.Reflection.Emit provides this automatically:
4470 // ig.Emit (OpCodes.Leave, finish);
4472 bool old_in_catch = ec.InCatch;
4474 //DeclSpace ds = ec.DeclSpace;
4476 foreach (Catch c in Specific){
4479 ig.BeginCatchBlock (c.CatchType);
4481 if (c.Name != null){
4482 vi = c.Block.GetVariableInfo (c.Name);
4484 throw new Exception ("Variable does not exist in this block");
4486 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
4488 ig.Emit (OpCodes.Pop);
4491 // if when clause is there
4493 if (c.Clause != null) {
4494 if (c.Clause is BoolConstant) {
4495 bool take = ((BoolConstant) c.Clause).Value;
4498 if (!c.Block.Emit (ec))
4501 EmitBoolExpression (ec, c.Clause, finish, false);
4502 if (!c.Block.Emit (ec))
4506 if (!c.Block.Emit (ec))
4510 if (General != null){
4511 ig.BeginCatchBlock (TypeManager.object_type);
4512 ig.Emit (OpCodes.Pop);
4514 if (General.Clause != null) {
4515 if (General.Clause is BoolConstant) {
4516 bool take = ((BoolConstant) General.Clause).Value;
4518 if (!General.Block.Emit (ec))
4521 EmitBoolExpression (ec, General.Clause, finish, false);
4522 if (!General.Block.Emit (ec))
4526 if (!General.Block.Emit (ec))
4530 ec.InCatch = old_in_catch;
4533 ig.BeginFinallyBlock ();
4534 bool old_in_finally = ec.InFinally;
4535 ec.InFinally = true;
4537 ec.InFinally = old_in_finally;
4540 ig.EndExceptionBlock ();
4543 if (!returns || ec.InTry || ec.InCatch)
4550 public class Using : Statement {
4551 object expression_or_block;
4552 Statement Statement;
4557 Expression [] converted_vars;
4558 ExpressionStatement [] assign;
4560 public Using (object expression_or_block, Statement stmt, Location l)
4562 this.expression_or_block = expression_or_block;
4568 // Resolves for the case of using using a local variable declaration.
4570 bool ResolveLocalVariableDecls (EmitContext ec)
4572 bool need_conv = false;
4573 expr_type = ec.DeclSpace.ResolveType (expr, false, loc);
4576 if (expr_type == null)
4580 // The type must be an IDisposable or an implicit conversion
4583 converted_vars = new Expression [var_list.Count];
4584 assign = new ExpressionStatement [var_list.Count];
4585 if (!TypeManager.ImplementsInterface (expr_type, TypeManager.idisposable_type)){
4586 foreach (DictionaryEntry e in var_list){
4587 Expression var = (Expression) e.Key;
4589 var = var.ResolveLValue (ec, new EmptyExpression ());
4593 converted_vars [i] = Expression.ConvertImplicitRequired (
4594 ec, var, TypeManager.idisposable_type, loc);
4596 if (converted_vars [i] == null)
4604 foreach (DictionaryEntry e in var_list){
4605 LocalVariableReference var = (LocalVariableReference) e.Key;
4606 Expression new_expr = (Expression) e.Value;
4609 a = new Assign (var, new_expr, loc);
4615 converted_vars [i] = var;
4616 assign [i] = (ExpressionStatement) a;
4623 bool ResolveExpression (EmitContext ec)
4625 if (!TypeManager.ImplementsInterface (expr_type, TypeManager.idisposable_type)){
4626 conv = Expression.ConvertImplicitRequired (
4627 ec, expr, TypeManager.idisposable_type, loc);
4637 // Emits the code for the case of using using a local variable declaration.
4639 bool EmitLocalVariableDecls (EmitContext ec)
4641 ILGenerator ig = ec.ig;
4644 bool old_in_try = ec.InTry;
4646 for (i = 0; i < assign.Length; i++) {
4647 assign [i].EmitStatement (ec);
4649 ig.BeginExceptionBlock ();
4651 Statement.Emit (ec);
4652 ec.InTry = old_in_try;
4654 bool old_in_finally = ec.InFinally;
4655 ec.InFinally = true;
4656 var_list.Reverse ();
4657 foreach (DictionaryEntry e in var_list){
4658 LocalVariableReference var = (LocalVariableReference) e.Key;
4659 Label skip = ig.DefineLabel ();
4662 ig.BeginFinallyBlock ();
4665 ig.Emit (OpCodes.Brfalse, skip);
4666 converted_vars [i].Emit (ec);
4667 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
4668 ig.MarkLabel (skip);
4669 ig.EndExceptionBlock ();
4671 ec.InFinally = old_in_finally;
4676 bool EmitExpression (EmitContext ec)
4679 // Make a copy of the expression and operate on that.
4681 ILGenerator ig = ec.ig;
4682 LocalBuilder local_copy = ig.DeclareLocal (expr_type);
4687 ig.Emit (OpCodes.Stloc, local_copy);
4689 bool old_in_try = ec.InTry;
4691 ig.BeginExceptionBlock ();
4692 Statement.Emit (ec);
4693 ec.InTry = old_in_try;
4695 Label skip = ig.DefineLabel ();
4696 bool old_in_finally = ec.InFinally;
4697 ig.BeginFinallyBlock ();
4698 ig.Emit (OpCodes.Ldloc, local_copy);
4699 ig.Emit (OpCodes.Brfalse, skip);
4700 ig.Emit (OpCodes.Ldloc, local_copy);
4701 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
4702 ig.MarkLabel (skip);
4703 ec.InFinally = old_in_finally;
4704 ig.EndExceptionBlock ();
4709 public override bool Resolve (EmitContext ec)
4711 if (expression_or_block is DictionaryEntry){
4712 expr = (Expression) ((DictionaryEntry) expression_or_block).Key;
4713 var_list = (ArrayList)((DictionaryEntry)expression_or_block).Value;
4715 if (!ResolveLocalVariableDecls (ec))
4718 } else if (expression_or_block is Expression){
4719 expr = (Expression) expression_or_block;
4721 expr = expr.Resolve (ec);
4725 expr_type = expr.Type;
4727 if (!ResolveExpression (ec))
4731 return Statement.Resolve (ec);
4734 protected override bool DoEmit (EmitContext ec)
4736 if (expression_or_block is DictionaryEntry)
4737 return EmitLocalVariableDecls (ec);
4738 else if (expression_or_block is Expression)
4739 return EmitExpression (ec);
4746 /// Implementation of the for each statement
4748 public class Foreach : Statement {
4750 LocalVariableReference variable;
4752 Statement statement;
4753 ForeachHelperMethods hm;
4754 Expression empty, conv;
4755 Type array_type, element_type;
4758 public Foreach (Expression type, LocalVariableReference var, Expression expr,
4759 Statement stmt, Location l)
4766 VariableInfo vi = var.VariableInfo;
4767 this.type = vi.Type;
4769 this.variable = var;
4775 public override bool Resolve (EmitContext ec)
4777 expr = expr.Resolve (ec);
4781 var_type = ec.DeclSpace.ResolveType (type, false, loc);
4782 if (var_type == null)
4786 // We need an instance variable. Not sure this is the best
4787 // way of doing this.
4789 // FIXME: When we implement propertyaccess, will those turn
4790 // out to return values in ExprClass? I think they should.
4792 if (!(expr.eclass == ExprClass.Variable || expr.eclass == ExprClass.Value ||
4793 expr.eclass == ExprClass.PropertyAccess || expr.eclass == ExprClass.IndexerAccess)){
4794 error1579 (expr.Type);
4798 if (expr.Type.IsArray) {
4799 array_type = expr.Type;
4800 element_type = array_type.GetElementType ();
4802 empty = new EmptyExpression (element_type);
4804 hm = ProbeCollectionType (ec, expr.Type);
4806 error1579 (expr.Type);
4810 array_type = expr.Type;
4811 element_type = hm.element_type;
4813 empty = new EmptyExpression (hm.element_type);
4816 ec.StartFlowBranching (FlowBranchingType.LOOP_BLOCK, loc);
4817 ec.CurrentBranching.CreateSibling ();
4821 // FIXME: maybe we can apply the same trick we do in the
4822 // array handling to avoid creating empty and conv in some cases.
4824 // Although it is not as important in this case, as the type
4825 // will not likely be object (what the enumerator will return).
4827 conv = Expression.ConvertExplicit (ec, empty, var_type, false, loc);
4831 if (variable.ResolveLValue (ec, empty) == null)
4834 if (!statement.Resolve (ec))
4837 //FlowReturns returns = ec.EndFlowBranching ();
4838 ec.EndFlowBranching ();
4843 // Retrieves a 'public bool MoveNext ()' method from the Type 't'
4845 static MethodInfo FetchMethodMoveNext (Type t)
4847 MemberList move_next_list;
4849 move_next_list = TypeContainer.FindMembers (
4850 t, MemberTypes.Method,
4851 BindingFlags.Public | BindingFlags.Instance,
4852 Type.FilterName, "MoveNext");
4853 if (move_next_list.Count == 0)
4856 foreach (MemberInfo m in move_next_list){
4857 MethodInfo mi = (MethodInfo) m;
4860 args = TypeManager.GetArgumentTypes (mi);
4861 if (args != null && args.Length == 0){
4862 if (mi.ReturnType == TypeManager.bool_type)
4870 // Retrieves a 'public T get_Current ()' method from the Type 't'
4872 static MethodInfo FetchMethodGetCurrent (Type t)
4874 MemberList move_next_list;
4876 move_next_list = TypeContainer.FindMembers (
4877 t, MemberTypes.Method,
4878 BindingFlags.Public | BindingFlags.Instance,
4879 Type.FilterName, "get_Current");
4880 if (move_next_list.Count == 0)
4883 foreach (MemberInfo m in move_next_list){
4884 MethodInfo mi = (MethodInfo) m;
4887 args = TypeManager.GetArgumentTypes (mi);
4888 if (args != null && args.Length == 0)
4895 // This struct records the helper methods used by the Foreach construct
4897 class ForeachHelperMethods {
4898 public EmitContext ec;
4899 public MethodInfo get_enumerator;
4900 public MethodInfo move_next;
4901 public MethodInfo get_current;
4902 public Type element_type;
4903 public Type enumerator_type;
4904 public bool is_disposable;
4906 public ForeachHelperMethods (EmitContext ec)
4909 this.element_type = TypeManager.object_type;
4910 this.enumerator_type = TypeManager.ienumerator_type;
4911 this.is_disposable = true;
4915 static bool GetEnumeratorFilter (MemberInfo m, object criteria)
4920 if (!(m is MethodInfo))
4923 if (m.Name != "GetEnumerator")
4926 MethodInfo mi = (MethodInfo) m;
4927 Type [] args = TypeManager.GetArgumentTypes (mi);
4929 if (args.Length != 0)
4932 ForeachHelperMethods hm = (ForeachHelperMethods) criteria;
4933 EmitContext ec = hm.ec;
4936 // Check whether GetEnumerator is accessible to us
4938 MethodAttributes prot = mi.Attributes & MethodAttributes.MemberAccessMask;
4940 Type declaring = mi.DeclaringType;
4941 if (prot == MethodAttributes.Private){
4942 if (declaring != ec.ContainerType)
4944 } else if (prot == MethodAttributes.FamANDAssem){
4945 // If from a different assembly, false
4946 if (!(mi is MethodBuilder))
4949 // Are we being invoked from the same class, or from a derived method?
4951 if (ec.ContainerType != declaring){
4952 if (!ec.ContainerType.IsSubclassOf (declaring))
4955 } else if (prot == MethodAttributes.FamORAssem){
4956 if (!(mi is MethodBuilder ||
4957 ec.ContainerType == declaring ||
4958 ec.ContainerType.IsSubclassOf (declaring)))
4960 } if (prot == MethodAttributes.Family){
4961 if (!(ec.ContainerType == declaring ||
4962 ec.ContainerType.IsSubclassOf (declaring)))
4967 // Ok, we can access it, now make sure that we can do something
4968 // with this 'GetEnumerator'
4971 if (mi.ReturnType == TypeManager.ienumerator_type ||
4972 TypeManager.ienumerator_type.IsAssignableFrom (mi.ReturnType) ||
4973 (!RootContext.StdLib && TypeManager.ImplementsInterface (mi.ReturnType, TypeManager.ienumerator_type))) {
4974 hm.move_next = TypeManager.bool_movenext_void;
4975 hm.get_current = TypeManager.object_getcurrent_void;
4980 // Ok, so they dont return an IEnumerable, we will have to
4981 // find if they support the GetEnumerator pattern.
4983 Type return_type = mi.ReturnType;
4985 hm.move_next = FetchMethodMoveNext (return_type);
4986 if (hm.move_next == null)
4988 hm.get_current = FetchMethodGetCurrent (return_type);
4989 if (hm.get_current == null)
4992 hm.element_type = hm.get_current.ReturnType;
4993 hm.enumerator_type = return_type;
4994 hm.is_disposable = TypeManager.ImplementsInterface (
4995 hm.enumerator_type, TypeManager.idisposable_type);
5001 /// This filter is used to find the GetEnumerator method
5002 /// on which IEnumerator operates
5004 static MemberFilter FilterEnumerator;
5008 FilterEnumerator = new MemberFilter (GetEnumeratorFilter);
5011 void error1579 (Type t)
5013 Report.Error (1579, loc,
5014 "foreach statement cannot operate on variables of type '" +
5015 t.FullName + "' because that class does not provide a " +
5016 " GetEnumerator method or it is inaccessible");
5019 static bool TryType (Type t, ForeachHelperMethods hm)
5023 mi = TypeContainer.FindMembers (t, MemberTypes.Method,
5024 BindingFlags.Public | BindingFlags.NonPublic |
5025 BindingFlags.Instance,
5026 FilterEnumerator, hm);
5031 hm.get_enumerator = (MethodInfo) mi [0];
5036 // Looks for a usable GetEnumerator in the Type, and if found returns
5037 // the three methods that participate: GetEnumerator, MoveNext and get_Current
5039 ForeachHelperMethods ProbeCollectionType (EmitContext ec, Type t)
5041 ForeachHelperMethods hm = new ForeachHelperMethods (ec);
5043 if (TryType (t, hm))
5047 // Now try to find the method in the interfaces
5050 Type [] ifaces = t.GetInterfaces ();
5052 foreach (Type i in ifaces){
5053 if (TryType (i, hm))
5058 // Since TypeBuilder.GetInterfaces only returns the interface
5059 // types for this type, we have to keep looping, but once
5060 // we hit a non-TypeBuilder (ie, a Type), then we know we are
5061 // done, because it returns all the types
5063 if ((t is TypeBuilder))
5073 // FIXME: possible optimization.
5074 // We might be able to avoid creating 'empty' if the type is the sam
5076 bool EmitCollectionForeach (EmitContext ec)
5078 ILGenerator ig = ec.ig;
5079 LocalBuilder enumerator, disposable;
5081 enumerator = ig.DeclareLocal (hm.enumerator_type);
5082 if (hm.is_disposable)
5083 disposable = ig.DeclareLocal (TypeManager.idisposable_type);
5088 // Instantiate the enumerator
5090 if (expr.Type.IsValueType){
5091 if (expr is IMemoryLocation){
5092 IMemoryLocation ml = (IMemoryLocation) expr;
5094 ml.AddressOf (ec, AddressOp.Load);
5096 throw new Exception ("Expr " + expr + " of type " + expr.Type +
5097 " does not implement IMemoryLocation");
5098 ig.Emit (OpCodes.Call, hm.get_enumerator);
5101 ig.Emit (OpCodes.Callvirt, hm.get_enumerator);
5103 ig.Emit (OpCodes.Stloc, enumerator);
5106 // Protect the code in a try/finalize block, so that
5107 // if the beast implement IDisposable, we get rid of it
5109 bool old_in_try = ec.InTry;
5111 if (hm.is_disposable) {
5112 ig.BeginExceptionBlock ();
5116 Label end_try = ig.DefineLabel ();
5118 ig.MarkLabel (ec.LoopBegin);
5119 ig.Emit (OpCodes.Ldloc, enumerator);
5120 ig.Emit (OpCodes.Callvirt, hm.move_next);
5121 ig.Emit (OpCodes.Brfalse, end_try);
5122 ig.Emit (OpCodes.Ldloc, enumerator);
5123 ig.Emit (OpCodes.Callvirt, hm.get_current);
5124 variable.EmitAssign (ec, conv);
5125 statement.Emit (ec);
5126 ig.Emit (OpCodes.Br, ec.LoopBegin);
5127 ig.MarkLabel (end_try);
5128 ec.InTry = old_in_try;
5130 // The runtime provides this for us.
5131 // ig.Emit (OpCodes.Leave, end);
5134 // Now the finally block
5136 if (hm.is_disposable) {
5137 Label end_finally = ig.DefineLabel ();
5138 bool old_in_finally = ec.InFinally;
5139 ec.InFinally = true;
5140 ig.BeginFinallyBlock ();
5142 ig.Emit (OpCodes.Ldloc, enumerator);
5143 ig.Emit (OpCodes.Isinst, TypeManager.idisposable_type);
5144 ig.Emit (OpCodes.Stloc, disposable);
5145 ig.Emit (OpCodes.Ldloc, disposable);
5146 ig.Emit (OpCodes.Brfalse, end_finally);
5147 ig.Emit (OpCodes.Ldloc, disposable);
5148 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
5149 ig.MarkLabel (end_finally);
5150 ec.InFinally = old_in_finally;
5152 // The runtime generates this anyways.
5153 // ig.Emit (OpCodes.Endfinally);
5155 ig.EndExceptionBlock ();
5158 ig.MarkLabel (ec.LoopEnd);
5163 // FIXME: possible optimization.
5164 // We might be able to avoid creating 'empty' if the type is the sam
5166 bool EmitArrayForeach (EmitContext ec)
5168 int rank = array_type.GetArrayRank ();
5169 ILGenerator ig = ec.ig;
5171 LocalBuilder copy = ig.DeclareLocal (array_type);
5174 // Make our copy of the array
5177 ig.Emit (OpCodes.Stloc, copy);
5180 LocalBuilder counter = ig.DeclareLocal (TypeManager.int32_type);
5184 ig.Emit (OpCodes.Ldc_I4_0);
5185 ig.Emit (OpCodes.Stloc, counter);
5186 test = ig.DefineLabel ();
5187 ig.Emit (OpCodes.Br, test);
5189 loop = ig.DefineLabel ();
5190 ig.MarkLabel (loop);
5192 ig.Emit (OpCodes.Ldloc, copy);
5193 ig.Emit (OpCodes.Ldloc, counter);
5194 ArrayAccess.EmitLoadOpcode (ig, var_type);
5196 variable.EmitAssign (ec, conv);
5198 statement.Emit (ec);
5200 ig.MarkLabel (ec.LoopBegin);
5201 ig.Emit (OpCodes.Ldloc, counter);
5202 ig.Emit (OpCodes.Ldc_I4_1);
5203 ig.Emit (OpCodes.Add);
5204 ig.Emit (OpCodes.Stloc, counter);
5206 ig.MarkLabel (test);
5207 ig.Emit (OpCodes.Ldloc, counter);
5208 ig.Emit (OpCodes.Ldloc, copy);
5209 ig.Emit (OpCodes.Ldlen);
5210 ig.Emit (OpCodes.Conv_I4);
5211 ig.Emit (OpCodes.Blt, loop);
5213 LocalBuilder [] dim_len = new LocalBuilder [rank];
5214 LocalBuilder [] dim_count = new LocalBuilder [rank];
5215 Label [] loop = new Label [rank];
5216 Label [] test = new Label [rank];
5219 for (dim = 0; dim < rank; dim++){
5220 dim_len [dim] = ig.DeclareLocal (TypeManager.int32_type);
5221 dim_count [dim] = ig.DeclareLocal (TypeManager.int32_type);
5222 test [dim] = ig.DefineLabel ();
5223 loop [dim] = ig.DefineLabel ();
5226 for (dim = 0; dim < rank; dim++){
5227 ig.Emit (OpCodes.Ldloc, copy);
5228 IntLiteral.EmitInt (ig, dim);
5229 ig.Emit (OpCodes.Callvirt, TypeManager.int_getlength_int);
5230 ig.Emit (OpCodes.Stloc, dim_len [dim]);
5233 for (dim = 0; dim < rank; dim++){
5234 ig.Emit (OpCodes.Ldc_I4_0);
5235 ig.Emit (OpCodes.Stloc, dim_count [dim]);
5236 ig.Emit (OpCodes.Br, test [dim]);
5237 ig.MarkLabel (loop [dim]);
5240 ig.Emit (OpCodes.Ldloc, copy);
5241 for (dim = 0; dim < rank; dim++)
5242 ig.Emit (OpCodes.Ldloc, dim_count [dim]);
5245 // FIXME: Maybe we can cache the computation of 'get'?
5247 Type [] args = new Type [rank];
5250 for (int i = 0; i < rank; i++)
5251 args [i] = TypeManager.int32_type;
5253 ModuleBuilder mb = CodeGen.ModuleBuilder;
5254 get = mb.GetArrayMethod (
5256 CallingConventions.HasThis| CallingConventions.Standard,
5258 ig.Emit (OpCodes.Call, get);
5259 variable.EmitAssign (ec, conv);
5260 statement.Emit (ec);
5261 ig.MarkLabel (ec.LoopBegin);
5262 for (dim = rank - 1; dim >= 0; dim--){
5263 ig.Emit (OpCodes.Ldloc, dim_count [dim]);
5264 ig.Emit (OpCodes.Ldc_I4_1);
5265 ig.Emit (OpCodes.Add);
5266 ig.Emit (OpCodes.Stloc, dim_count [dim]);
5268 ig.MarkLabel (test [dim]);
5269 ig.Emit (OpCodes.Ldloc, dim_count [dim]);
5270 ig.Emit (OpCodes.Ldloc, dim_len [dim]);
5271 ig.Emit (OpCodes.Blt, loop [dim]);
5274 ig.MarkLabel (ec.LoopEnd);
5279 protected override bool DoEmit (EmitContext ec)
5283 ILGenerator ig = ec.ig;
5285 Label old_begin = ec.LoopBegin, old_end = ec.LoopEnd;
5286 bool old_inloop = ec.InLoop;
5287 int old_loop_begin_try_catch_level = ec.LoopBeginTryCatchLevel;
5288 ec.LoopBegin = ig.DefineLabel ();
5289 ec.LoopEnd = ig.DefineLabel ();
5291 ec.LoopBeginTryCatchLevel = ec.TryCatchLevel;
5294 ret_val = EmitCollectionForeach (ec);
5296 ret_val = EmitArrayForeach (ec);
5298 ec.LoopBegin = old_begin;
5299 ec.LoopEnd = old_end;
5300 ec.InLoop = old_inloop;
5301 ec.LoopBeginTryCatchLevel = old_loop_begin_try_catch_level;
5308 /// AddHandler statement
5310 public class AddHandler : Statement {
5312 Expression EvtHandler;
5315 // keeps track whether EvtId is already resolved
5319 public AddHandler (Expression evt_id, Expression evt_handler, Location l)
5322 EvtHandler = Parser.SetAddressOf (evt_handler);
5325 //Console.WriteLine ("Adding handler '" + evt_handler + "' for Event '" + evt_id +"'");
5328 public override bool Resolve (EmitContext ec)
5331 // if EvetId is of EventExpr type that means
5332 // this is already resolved
5334 if (EvtId is EventExpr) {
5339 EvtId = EvtId.Resolve(ec);
5340 EvtHandler = EvtHandler.Resolve(ec,ResolveFlags.MethodGroup);
5341 if (EvtId == null || (!(EvtId is EventExpr))) {
5342 Report.Error (30676, "Need an event designator.");
5346 if (EvtHandler == null)
5348 Report.Error (999, "'AddHandler' statement needs an event handler.");
5355 protected override bool DoEmit (EmitContext ec)
5358 // Already resolved and emitted don't do anything
5364 ArrayList args = new ArrayList();
5365 Argument arg = new Argument (EvtHandler, Argument.AType.Expression);
5370 // The even type was already resolved to a delegate, so
5371 // we must un-resolve its name to generate a type expression
5372 string ts = (EvtId.Type.ToString()).Replace ('+','.');
5373 Expression dtype = Mono.MonoBASIC.Parser.DecomposeQI (ts, Location.Null);
5375 // which we can use to declare a new event handler
5377 d = new New (dtype, args, Location.Null);
5379 e = new CompoundAssign(Binary.Operator.Addition, EvtId, d, Location.Null);
5381 // we resolve it all and emit the code
5394 /// RemoveHandler statement
5396 public class RemoveHandler : Statement
\r
5399 Expression EvtHandler;
5401 public RemoveHandler (Expression evt_id, Expression evt_handler, Location l)
5404 EvtHandler = Parser.SetAddressOf (evt_handler);
5408 public override bool Resolve (EmitContext ec)
5410 EvtId = EvtId.Resolve(ec);
5411 EvtHandler = EvtHandler.Resolve(ec,ResolveFlags.MethodGroup);
5412 if (EvtId == null || (!(EvtId is EventExpr)))
\r
5414 Report.Error (30676, "Need an event designator.");
5418 if (EvtHandler == null)
5420 Report.Error (999, "'AddHandler' statement needs an event handler.");
5426 protected override bool DoEmit (EmitContext ec)
5429 ArrayList args = new ArrayList();
5430 Argument arg = new Argument (EvtHandler, Argument.AType.Expression);
5433 // The even type was already resolved to a delegate, so
5434 // we must un-resolve its name to generate a type expression
5435 string ts = (EvtId.Type.ToString()).Replace ('+','.');
5436 Expression dtype = Mono.MonoBASIC.Parser.DecomposeQI (ts, Location.Null);
5438 // which we can use to declare a new event handler
5440 d = new New (dtype, args, Location.Null);
5443 e = new CompoundAssign(Binary.Operator.Subtraction, EvtId, d, Location.Null);
5445 // we resolve it all and emit the code
5457 public class RedimClause {
5458 private Expression RedimTarget;
5459 private ArrayList NewIndexes;
5460 private Expression AsType;
5462 private LocalTemporary localTmp = null;
5463 private Expression origRedimTarget = null;
5464 private StatementExpression ReDimExpr;
5466 public RedimClause (Expression e, ArrayList args, Expression e_as)
5468 if (e is SimpleName)
5469 ((SimpleName) e).IsInvocation = false;
5470 if (e is MemberAccess)
5471 ((MemberAccess) e).IsInvocation = false;
5478 public bool Resolve (EmitContext ec, bool Preserve, Location loc)
5480 RedimTarget = RedimTarget.Resolve (ec);
5482 if (AsType != null) {
5483 Report.Error (30811, loc, "'ReDim' statements can no longer be used to declare array variables");
5487 if (!RedimTarget.Type.IsArray) {
5488 Report.Error (49, loc, "'ReDim' statement requires an array");
5492 ArrayList args = new ArrayList();
5493 foreach (Argument a in NewIndexes) {
5494 if (a.Resolve(ec, loc))
5498 for (int x = 0; x < args.Count; x++) {
5499 args[x] = new Binary (Binary.Operator.Addition,
5500 (Expression) args[x], new IntLiteral (1), Location.Null);
5504 if (RedimTarget.Type.GetArrayRank() != NewIndexes.Count) {
5505 Report.Error (30415, loc, "'ReDim' cannot change the number of dimensions of an array.");
5509 Type BaseType = RedimTarget.Type.GetElementType();
5510 Expression BaseTypeExpr = MonoBASIC.Parser.DecomposeQI(BaseType.FullName.ToString(), Location.Null);
5511 ArrayCreation acExpr = new ArrayCreation (BaseTypeExpr, NewIndexes, "", null, Location.Null);
5514 ExpressionStatement PreserveExpr = null;
5515 if (RedimTarget is PropertyGroupExpr) {
5516 localTmp = new LocalTemporary (ec, RedimTarget.Type);
5517 PropertyGroupExpr pe = RedimTarget as PropertyGroupExpr;
5518 origRedimTarget = new PropertyGroupExpr (pe.Properties, pe.Arguments, pe.InstanceExpression, loc);
5519 if ((origRedimTarget = origRedimTarget.Resolve (ec)) == null) {
5520 Report.Error (-1, loc, "'ReDim' vs PropertyGroup");
5523 PreserveExpr = (ExpressionStatement) new Preserve(localTmp, acExpr, loc);
5525 PreserveExpr = (ExpressionStatement) new Preserve(RedimTarget, acExpr, loc);
5526 ReDimExpr = (StatementExpression) new StatementExpression ((ExpressionStatement) new Assign (RedimTarget, PreserveExpr, loc), loc);
5529 ReDimExpr = (StatementExpression) new StatementExpression ((ExpressionStatement) new Assign (RedimTarget, acExpr, loc), loc);
5530 ReDimExpr.Resolve(ec);
5534 public void DoEmit (EmitContext ec)
5536 if (ReDimExpr == null)
5539 if (localTmp != null && origRedimTarget != null) {
5540 origRedimTarget.Emit (ec);
5541 localTmp.Store (ec);
5548 public class ReDim : Statement {
5549 ArrayList RedimTargets;
5552 public ReDim (ArrayList targets, bool opt_preserve, Location l)
5555 RedimTargets = targets;
5556 Preserve = opt_preserve;
5559 public override bool Resolve (EmitContext ec)
5562 foreach (RedimClause rc in RedimTargets)
5563 result = rc.Resolve(ec, Preserve, loc) && result;
5567 protected override bool DoEmit (EmitContext ec)
5569 foreach (RedimClause rc in RedimTargets)
5576 public class Erase : Statement {
5577 Expression EraseTarget;
5579 private StatementExpression EraseExpr;
5581 public Erase (Expression expr, Location l)
5587 public override bool Resolve (EmitContext ec)
5589 EraseTarget = EraseTarget.Resolve (ec);
5590 if (!EraseTarget.Type.IsArray)
5591 Report.Error (49, "'Erase' statement requires an array");
5593 EraseExpr = (StatementExpression) new StatementExpression ((ExpressionStatement) new Assign (EraseTarget, NullLiteral.Null, loc), loc);
5594 EraseExpr.Resolve(ec);
5599 protected override bool DoEmit (EmitContext ec)