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 string LabelName {
957 public Label LabelTarget (EmitContext ec)
961 label = ec.ig.DefineLabel ();
968 public bool IsDefined {
974 public bool HasBeenReferenced {
980 public void AddUsageVector (FlowBranching.UsageVector vector)
983 vectors = new ArrayList ();
985 vectors.Add (vector.Clone ());
989 public override bool Resolve (EmitContext ec)
991 if (vectors != null) {
992 ec.CurrentBranching.CurrentUsageVector.MergeJumpOrigins (vectors);
995 ec.CurrentBranching.CurrentUsageVector.Breaks = FlowReturns.NEVER;
996 ec.CurrentBranching.CurrentUsageVector.Returns = FlowReturns.NEVER;
1005 protected override bool DoEmit (EmitContext ec)
1008 ec.ig.MarkLabel (label);
1012 public void AddReference ()
1020 /// 'goto default' statement
1022 public class GotoDefault : Statement {
1024 public GotoDefault (Location l)
1029 public override bool Resolve (EmitContext ec)
1031 ec.CurrentBranching.CurrentUsageVector.Breaks = FlowReturns.UNREACHABLE;
1035 protected override bool DoEmit (EmitContext ec)
1037 if (ec.Switch == null){
1038 Report.Error (153, loc, "goto default is only valid in a switch statement");
1042 if (!ec.Switch.GotDefault){
1043 Report.Error (30132, loc, "No default target on switch statement");
1046 ec.ig.Emit (OpCodes.Br, ec.Switch.DefaultTarget);
1052 /// 'goto case' statement
1054 public class GotoCase : Statement {
1058 public GotoCase (Expression e, Location l)
1064 public override bool Resolve (EmitContext ec)
1066 if (ec.Switch == null){
1067 Report.Error (153, loc, "goto case is only valid in a switch statement");
1071 expr = expr.Resolve (ec);
1075 if (!(expr is Constant)){
1076 Report.Error (30132, loc, "Target expression for goto case is not constant");
1080 object val = Expression.ConvertIntLiteral (
1081 (Constant) expr, ec.Switch.SwitchType, loc);
1086 SwitchLabel sl = (SwitchLabel) ec.Switch.Elements [val];
1091 "No such label 'case " + val + "': for the goto case");
1094 label = sl.ILLabelCode;
1096 ec.CurrentBranching.CurrentUsageVector.Breaks = FlowReturns.UNREACHABLE;
1100 protected override bool DoEmit (EmitContext ec)
1102 ec.ig.Emit (OpCodes.Br, label);
1107 public class Throw : Statement {
1110 public Throw (Expression expr, Location l)
1116 public override bool Resolve (EmitContext ec)
1119 expr = expr.Resolve (ec);
1123 ExprClass eclass = expr.eclass;
1125 if (!(eclass == ExprClass.Variable || eclass == ExprClass.PropertyAccess ||
1126 eclass == ExprClass.Value || eclass == ExprClass.IndexerAccess)) {
1127 expr.Error118 ("value, variable, property or indexer access ");
1133 if ((t != TypeManager.exception_type) &&
1134 !t.IsSubclassOf (TypeManager.exception_type) &&
1135 !(expr is NullLiteral)) {
1136 Report.Error (30665, loc,
1137 "The type caught or thrown must be derived " +
1138 "from System.Exception");
1143 ec.CurrentBranching.CurrentUsageVector.Returns = FlowReturns.EXCEPTION;
1144 ec.CurrentBranching.CurrentUsageVector.Breaks = FlowReturns.EXCEPTION;
1148 protected override bool DoEmit (EmitContext ec)
1152 ec.ig.Emit (OpCodes.Rethrow);
1156 "A throw statement with no argument is only " +
1157 "allowed in a catch clause");
1164 ec.ig.Emit (OpCodes.Throw);
1170 // Support 'End' Statement which terminates execution immediately
1172 public class End : Statement {
1174 public End (Location l)
1179 public override bool Resolve (EmitContext ec)
1184 protected override bool DoEmit (EmitContext ec)
1186 Expression e = null;
1187 Expression tmp = Mono.MonoBASIC.Parser.DecomposeQI (
1188 "Microsoft.VisualBasic.CompilerServices.ProjectData.EndApp",
1191 e = new Invocation (tmp, null, loc);
1203 public class Break : Statement {
1205 public Break (Location l)
1210 public override bool Resolve (EmitContext ec)
1212 ec.CurrentBranching.MayLeaveLoop = true;
1213 ec.CurrentBranching.CurrentUsageVector.Breaks = FlowReturns.ALWAYS;
1217 protected override bool DoEmit (EmitContext ec)
1219 ILGenerator ig = ec.ig;
1221 if (ec.InLoop == false && ec.Switch == null){
1222 Report.Error (139, loc, "No enclosing loop or switch to continue to");
1226 if (ec.InTry || ec.InCatch)
1227 ig.Emit (OpCodes.Leave, ec.LoopEnd);
1229 ig.Emit (OpCodes.Br, ec.LoopEnd);
1235 public enum ExitType {
1246 public class Exit : Statement {
1247 public readonly ExitType type;
1248 public Exit (ExitType t, Location l)
1254 public override bool Resolve (EmitContext ec)
1256 ec.CurrentBranching.MayLeaveLoop = true;
1257 ec.CurrentBranching.CurrentUsageVector.Breaks = FlowReturns.ALWAYS;
1261 protected override bool DoEmit (EmitContext ec)
1263 ILGenerator ig = ec.ig;
1265 if (type != ExitType.SUB && type != ExitType.FUNCTION &&
1266 type != ExitType.PROPERTY && type != ExitType.TRY) {
1267 if (ec.InLoop == false && ec.Switch == null){
1268 if (type == ExitType.FOR)
1269 Report.Error (30096, loc, "No enclosing FOR loop to exit from");
1270 if (type == ExitType.WHILE)
1271 Report.Error (30097, loc, "No enclosing WHILE loop to exit from");
1272 if (type == ExitType.DO)
1273 Report.Error (30089, loc, "No enclosing DO loop to exit from");
1274 if (type == ExitType.SELECT)
1275 Report.Error (30099, loc, "No enclosing SELECT to exit from");
1280 if (ec.InTry || ec.InCatch)
1281 ig.Emit (OpCodes.Leave, ec.LoopEnd);
1283 ig.Emit (OpCodes.Br, ec.LoopEnd);
1286 Report.Error (30393, loc,
1287 "Control can not leave the body of the finally block");
1291 if (ec.InTry || ec.InCatch) {
1292 if (ec.HasExitLabel)
1293 ec.ig.Emit (OpCodes.Leave, ec.ExitLabel);
1295 if(type == ExitType.SUB) {
1296 ec.ig.Emit (OpCodes.Ret);
1298 ec.ig.Emit (OpCodes.Ldloc_0);
1299 ec.ig.Emit (OpCodes.Ret);
1311 public class Continue : Statement {
1313 public Continue (Location l)
1318 public override bool Resolve (EmitContext ec)
1320 ec.CurrentBranching.CurrentUsageVector.Breaks = FlowReturns.ALWAYS;
1324 protected override bool DoEmit (EmitContext ec)
1326 Label begin = ec.LoopBegin;
1329 Report.Error (139, loc, "No enclosing loop to continue to");
1334 // UGH: Non trivial. This Br might cross a try/catch boundary
1338 // try { ... } catch { continue; }
1342 // try {} catch { while () { continue; }}
1344 if (ec.TryCatchLevel > ec.LoopBeginTryCatchLevel)
1345 ec.ig.Emit (OpCodes.Leave, begin);
1346 else if (ec.TryCatchLevel < ec.LoopBeginTryCatchLevel)
1347 throw new Exception ("Should never happen");
1349 ec.ig.Emit (OpCodes.Br, begin);
1355 // This is used in the control flow analysis code to specify whether the
1356 // current code block may return to its enclosing block before reaching
1359 public enum FlowReturns {
1360 // It can never return.
1363 // This means that the block contains a conditional return statement
1367 // The code always returns, ie. there's an unconditional return / break
1371 // The code always throws an exception.
1374 // The current code block is unreachable. This happens if it's immediately
1375 // following a FlowReturns.ALWAYS block.
1380 // This is a special bit vector which can inherit from another bit vector doing a
1381 // copy-on-write strategy. The inherited vector may have a smaller size than the
1384 public class MyBitVector {
1386 public int Count { get { return count; } }
1387 public readonly MyBitVector InheritsFrom;
1392 public MyBitVector (int Count)
1393 : this (null, Count)
1396 public MyBitVector (MyBitVector InheritsFrom, int Count)
1398 this.InheritsFrom = InheritsFrom;
1403 // Checks whether this bit vector has been modified. After setting this to true,
1404 // we won't use the inherited vector anymore, but our own copy of it.
1406 public bool IsDirty {
1413 initialize_vector ();
1418 // Get/set bit 'index' in the bit vector.
1420 public bool this [int index]
1424 throw new ArgumentOutOfRangeException ();
1426 // We're doing a "copy-on-write" strategy here; as long
1427 // as nobody writes to the array, we can use our parent's
1428 // copy instead of duplicating the vector.
1431 return vector [index];
1432 else if (InheritsFrom != null) {
1433 BitArray inherited = InheritsFrom.Vector;
1435 if (index < inherited.Count)
1436 return inherited [index];
1445 throw new ArgumentOutOfRangeException ();
1447 // Only copy the vector if we're actually modifying it.
1449 if (this [index] != value) {
1450 initialize_vector ();
1452 vector [index] = value;
1458 // If you explicitly convert the MyBitVector to a BitArray, you will get a deep
1459 // copy of the bit vector.
1461 public static explicit operator BitArray (MyBitVector vector)
1463 vector.initialize_vector ();
1464 return vector.Vector;
1468 // Performs an 'or' operation on the bit vector. The 'new_vector' may have a
1469 // different size than the current one.
1471 public void Or (MyBitVector new_vector)
1473 BitArray new_array = new_vector.Vector;
1475 initialize_vector ();
1478 if (vector.Count < new_array.Count)
1479 upper = vector.Count;
1481 upper = new_array.Count;
1483 for (int i = 0; i < upper; i++)
1484 vector [i] = vector [i] | new_array [i];
1488 // Perfonrms an 'and' operation on the bit vector. The 'new_vector' may have
1489 // a different size than the current one.
1491 public void And (MyBitVector new_vector)
1493 BitArray new_array = new_vector.Vector;
1495 initialize_vector ();
1498 if (vector.Count < new_array.Count)
1499 lower = upper = vector.Count;
1501 lower = new_array.Count;
1502 upper = vector.Count;
1505 for (int i = 0; i < lower; i++)
1506 vector [i] = vector [i] & new_array [i];
1508 for (int i = lower; i < upper; i++)
1513 // This does a deep copy of the bit vector.
1515 public MyBitVector Clone ()
1517 MyBitVector retval = new MyBitVector (Count);
1519 retval.Vector = Vector;
1524 public void ExpandBy(int howMany)
1527 throw new ArgumentException("howMany");
1528 initialize_vector();
1529 count = vector.Count + howMany;
1530 BitArray newVector = new BitArray(count, false);
1531 for (int i = 0; i < vector.Count; i++)
1532 newVector [i] = vector [i];
1540 else if (!is_dirty && (InheritsFrom != null))
1541 return InheritsFrom.Vector;
1543 initialize_vector ();
1549 initialize_vector ();
1551 for (int i = 0; i < System.Math.Min (vector.Count, value.Count); i++)
1552 vector [i] = value [i];
1556 void initialize_vector ()
1561 vector = new BitArray (Count, false);
1562 if (InheritsFrom != null)
1563 Vector = InheritsFrom.Vector;
1568 public override string ToString ()
1570 StringBuilder sb = new StringBuilder ("MyBitVector (");
1572 BitArray vector = Vector;
1576 sb.Append ("INHERITED - ");
1577 for (int i = 0; i < vector.Count; i++) {
1580 sb.Append (vector [i]);
1584 return sb.ToString ();
1589 // The type of a FlowBranching.
1591 public enum FlowBranchingType {
1592 // Normal (conditional or toplevel) block.
1609 // A new instance of this class is created every time a new block is resolved
1610 // and if there's branching in the block's control flow.
1612 public class FlowBranching {
1614 // The type of this flow branching.
1616 public readonly FlowBranchingType Type;
1619 // The block this branching is contained in. This may be null if it's not
1620 // a top-level block and it doesn't declare any local variables.
1622 public readonly Block Block;
1625 // The parent of this branching or null if this is the top-block.
1627 public readonly FlowBranching Parent;
1630 // Start-Location of this flow branching.
1632 public readonly Location Location;
1635 // A list of UsageVectors. A new vector is added each time control flow may
1636 // take a different path.
1638 public ArrayList Siblings;
1641 // If this is an infinite loop.
1643 public bool Infinite;
1646 // If we may leave the current loop.
1648 public bool MayLeaveLoop;
1653 InternalParameters param_info;
1655 MyStructInfo[] struct_params;
1657 ArrayList finally_vectors;
1659 static int next_id = 0;
1663 // Performs an 'And' operation on the FlowReturns status
1664 // (for instance, a block only returns ALWAYS if all its siblings
1667 public static FlowReturns AndFlowReturns (FlowReturns a, FlowReturns b)
1669 if (b == FlowReturns.UNREACHABLE)
1673 case FlowReturns.NEVER:
1674 if (b == FlowReturns.NEVER)
1675 return FlowReturns.NEVER;
1677 return FlowReturns.SOMETIMES;
1679 case FlowReturns.SOMETIMES:
1680 return FlowReturns.SOMETIMES;
1682 case FlowReturns.ALWAYS:
1683 if ((b == FlowReturns.ALWAYS) || (b == FlowReturns.EXCEPTION))
1684 return FlowReturns.ALWAYS;
1686 return FlowReturns.SOMETIMES;
1688 case FlowReturns.EXCEPTION:
1689 if (b == FlowReturns.EXCEPTION)
1690 return FlowReturns.EXCEPTION;
1691 else if (b == FlowReturns.ALWAYS)
1692 return FlowReturns.ALWAYS;
1694 return FlowReturns.SOMETIMES;
1701 // The vector contains a BitArray with information about which local variables
1702 // and parameters are already initialized at the current code position.
1704 public class UsageVector {
1706 // If this is true, then the usage vector has been modified and must be
1707 // merged when we're done with this branching.
1709 public bool IsDirty;
1712 // The number of parameters in this block.
1714 public readonly int CountParameters;
1717 // The number of locals in this block.
1719 public readonly int CountLocals;
1722 // The number of locals in this block added after starting usage track.
1724 public int ExtraLocals { get { return locals.Count - CountLocals; } }
1728 // If not null, then we inherit our state from this vector and do a
1729 // copy-on-write. If null, then we're the first sibling in a top-level
1730 // block and inherit from the empty vector.
1732 public readonly UsageVector InheritsFrom;
1737 MyBitVector locals, parameters;
1738 FlowReturns real_returns, real_breaks;
1741 static int next_id = 0;
1745 // Normally, you should not use any of these constructors.
1747 public UsageVector (UsageVector parent, int num_params, int num_locals)
1749 this.InheritsFrom = parent;
1750 this.CountParameters = num_params;
1751 this.CountLocals = num_locals;
1752 this.real_returns = FlowReturns.NEVER;
1753 this.real_breaks = FlowReturns.NEVER;
1755 if (parent != null) {
1756 locals = new MyBitVector (parent.locals, CountLocals);
1758 parameters = new MyBitVector (parent.parameters, num_params);
1759 real_returns = parent.Returns;
1760 real_breaks = parent.Breaks;
1762 locals = new MyBitVector (null, CountLocals);
1764 parameters = new MyBitVector (null, num_params);
1770 public UsageVector (UsageVector parent)
1771 : this (parent, parent.CountParameters, parent.CountLocals)
1774 public void AddExtraLocals(int howMany)
1776 locals.ExpandBy(howMany);
1780 // This does a deep copy of the usage vector.
1782 public UsageVector Clone ()
1784 UsageVector retval = new UsageVector (null, CountParameters, CountLocals);
1786 retval.locals = locals.Clone ();
1787 if (parameters != null)
1788 retval.parameters = parameters.Clone ();
1789 retval.real_returns = real_returns;
1790 retval.real_breaks = real_breaks;
1796 // State of parameter 'number'.
1798 public bool this [int number]
1803 else if (number == 0)
1804 throw new ArgumentException ();
1806 return parameters [number - 1];
1812 else if (number == 0)
1813 throw new ArgumentException ();
1815 parameters [number - 1] = value;
1820 // State of the local variable 'vi'.
1821 // If the local variable is a struct, use a non-zero 'field_idx'
1822 // to check an individual field in it.
1824 public bool this [VariableInfo vi, int field_idx]
1827 if (vi.Number == -1)
1829 else if (vi.Number == 0)
1830 throw new ArgumentException ();
1832 return locals [vi.Number + field_idx - 1];
1836 if (vi.Number == -1)
1838 else if (vi.Number == 0)
1839 throw new ArgumentException ();
1841 locals [vi.Number + field_idx - 1] = value;
1846 // Specifies when the current block returns.
1847 // If this is FlowReturns.UNREACHABLE, then control can never reach the
1848 // end of the method (so that we don't need to emit a return statement).
1849 // The same applies for FlowReturns.EXCEPTION, but in this case the return
1850 // value will never be used.
1852 public FlowReturns Returns {
1854 return real_returns;
1858 real_returns = value;
1863 // Specifies whether control may return to our containing block
1864 // before reaching the end of this block. This happens if there
1865 // is a break/continue/goto/return in it.
1866 // This can also be used to find out whether the statement immediately
1867 // following the current block may be reached or not.
1869 public FlowReturns Breaks {
1875 real_breaks = value;
1879 public bool AlwaysBreaks {
1881 return (Breaks == FlowReturns.ALWAYS) ||
1882 (Breaks == FlowReturns.EXCEPTION) ||
1883 (Breaks == FlowReturns.UNREACHABLE);
1887 public bool MayBreak {
1889 return Breaks != FlowReturns.NEVER;
1893 public bool AlwaysReturns {
1895 return (Returns == FlowReturns.ALWAYS) ||
1896 (Returns == FlowReturns.EXCEPTION);
1900 public bool MayReturn {
1902 return (Returns == FlowReturns.SOMETIMES) ||
1903 (Returns == FlowReturns.ALWAYS);
1908 // Merge a child branching.
1910 public FlowReturns MergeChildren (FlowBranching branching, ICollection children)
1912 MyBitVector new_locals = null;
1913 MyBitVector new_params = null;
1915 FlowReturns new_returns = FlowReturns.NEVER;
1916 FlowReturns new_breaks = FlowReturns.NEVER;
1917 bool new_returns_set = false, new_breaks_set = false;
1919 Report.Debug (2, "MERGING CHILDREN", branching, branching.Type,
1920 this, children.Count);
1922 foreach (UsageVector child in children) {
1923 Report.Debug (2, " MERGING CHILD", child, child.is_finally);
1925 if (!child.is_finally) {
1926 if (child.Breaks != FlowReturns.UNREACHABLE) {
1927 // If Returns is already set, perform an
1928 // 'And' operation on it, otherwise just set just.
1929 if (!new_returns_set) {
1930 new_returns = child.Returns;
1931 new_returns_set = true;
1933 new_returns = AndFlowReturns (
1934 new_returns, child.Returns);
1937 // If Breaks is already set, perform an
1938 // 'And' operation on it, otherwise just set just.
1939 if (!new_breaks_set) {
1940 new_breaks = child.Breaks;
1941 new_breaks_set = true;
1943 new_breaks = AndFlowReturns (
1944 new_breaks, child.Breaks);
1947 // Ignore unreachable children.
1948 if (child.Returns == FlowReturns.UNREACHABLE)
1951 // A local variable is initialized after a flow branching if it
1952 // has been initialized in all its branches which do neither
1953 // always return or always throw an exception.
1955 // If a branch may return, but does not always return, then we
1956 // can treat it like a never-returning branch here: control will
1957 // only reach the code position after the branching if we did not
1960 // It's important to distinguish between always and sometimes
1961 // returning branches here:
1964 // 2 if (something) {
1968 // 6 Console.WriteLine (a);
1970 // The if block in lines 3-4 always returns, so we must not look
1971 // at the initialization of 'a' in line 4 - thus it'll still be
1972 // uninitialized in line 6.
1974 // On the other hand, the following is allowed:
1981 // 6 Console.WriteLine (a);
1983 // Here, 'a' is initialized in line 3 and we must not look at
1984 // line 5 since it always returns.
1986 if (child.is_finally) {
1987 if (new_locals == null)
1988 new_locals = locals.Clone ();
1989 new_locals.Or (child.locals);
1991 if (parameters != null) {
1992 if (new_params == null)
1993 new_params = parameters.Clone ();
1994 new_params.Or (child.parameters);
1998 if (!child.AlwaysReturns && !child.AlwaysBreaks) {
1999 if (new_locals != null)
2000 new_locals.And (child.locals);
2002 new_locals = locals.Clone ();
2003 new_locals.Or (child.locals);
2005 } else if (children.Count == 1) {
2006 new_locals = locals.Clone ();
2007 new_locals.Or (child.locals);
2010 // An 'out' parameter must be assigned in all branches which do
2011 // not always throw an exception.
2012 if (parameters != null) {
2013 if (child.Breaks != FlowReturns.EXCEPTION) {
2014 if (new_params != null)
2015 new_params.And (child.parameters);
2017 new_params = parameters.Clone ();
2018 new_params.Or (child.parameters);
2020 } else if (children.Count == 1) {
2021 new_params = parameters.Clone ();
2022 new_params.Or (child.parameters);
2028 Returns = new_returns;
2029 if ((branching.Type == FlowBranchingType.BLOCK) ||
2030 (branching.Type == FlowBranchingType.EXCEPTION) ||
2031 (new_breaks == FlowReturns.UNREACHABLE) ||
2032 (new_breaks == FlowReturns.EXCEPTION))
2033 Breaks = new_breaks;
2034 else if (branching.Type == FlowBranchingType.SWITCH_SECTION)
2035 Breaks = new_returns;
2036 else if (branching.Type == FlowBranchingType.SWITCH){
2037 if (new_breaks == FlowReturns.ALWAYS)
2038 Breaks = FlowReturns.ALWAYS;
2042 // We've now either reached the point after the branching or we will
2043 // never get there since we always return or always throw an exception.
2045 // If we can reach the point after the branching, mark all locals and
2046 // parameters as initialized which have been initialized in all branches
2047 // we need to look at (see above).
2050 if (((new_breaks != FlowReturns.ALWAYS) &&
2051 (new_breaks != FlowReturns.EXCEPTION) &&
2052 (new_breaks != FlowReturns.UNREACHABLE)) ||
2053 (children.Count == 1)) {
2054 if (new_locals != null)
2055 locals.Or (new_locals);
2057 if (new_params != null)
2058 parameters.Or (new_params);
2061 Report.Debug (2, "MERGING CHILDREN DONE", branching.Type,
2062 new_params, new_locals, new_returns, new_breaks,
2063 branching.Infinite, branching.MayLeaveLoop, this);
2065 if (branching.Type == FlowBranchingType.SWITCH_SECTION) {
2066 if ((new_breaks != FlowReturns.ALWAYS) &&
2067 (new_breaks != FlowReturns.EXCEPTION) &&
2068 (new_breaks != FlowReturns.UNREACHABLE))
2069 Report.Error (163, branching.Location,
2070 "Control cannot fall through from one " +
2071 "case label to another");
2074 if (branching.Infinite && !branching.MayLeaveLoop) {
2075 Report.Debug (1, "INFINITE", new_returns, new_breaks,
2076 Returns, Breaks, this);
2078 // We're actually infinite.
2079 if (new_returns == FlowReturns.NEVER) {
2080 Breaks = FlowReturns.UNREACHABLE;
2081 return FlowReturns.UNREACHABLE;
2084 // If we're an infinite loop and do not break, the code after
2085 // the loop can never be reached. However, if we may return
2086 // from the loop, then we do always return (or stay in the loop
2088 if ((new_returns == FlowReturns.SOMETIMES) ||
2089 (new_returns == FlowReturns.ALWAYS)) {
2090 Returns = FlowReturns.ALWAYS;
2091 return FlowReturns.ALWAYS;
2099 // Tells control flow analysis that the current code position may be reached with
2100 // a forward jump from any of the origins listed in 'origin_vectors' which is a
2101 // list of UsageVectors.
2103 // This is used when resolving forward gotos - in the following example, the
2104 // variable 'a' is uninitialized in line 8 becase this line may be reached via
2105 // the goto in line 4:
2115 // 8 Console.WriteLine (a);
2118 public void MergeJumpOrigins (ICollection origin_vectors)
2120 Report.Debug (1, "MERGING JUMP ORIGIN", this);
2122 real_breaks = FlowReturns.NEVER;
2123 real_returns = FlowReturns.NEVER;
2125 foreach (UsageVector vector in origin_vectors) {
2126 Report.Debug (1, " MERGING JUMP ORIGIN", vector);
2128 locals.And (vector.locals);
2129 if (parameters != null)
2130 parameters.And (vector.parameters);
2131 Breaks = AndFlowReturns (Breaks, vector.Breaks);
2132 Returns = AndFlowReturns (Returns, vector.Returns);
2135 Report.Debug (1, "MERGING JUMP ORIGIN DONE", this);
2139 // This is used at the beginning of a finally block if there were
2140 // any return statements in the try block or one of the catch blocks.
2142 public void MergeFinallyOrigins (ICollection finally_vectors)
2144 Report.Debug (1, "MERGING FINALLY ORIGIN", this);
2146 real_breaks = FlowReturns.NEVER;
2148 foreach (UsageVector vector in finally_vectors) {
2149 Report.Debug (1, " MERGING FINALLY ORIGIN", vector);
2151 if (parameters != null)
2152 parameters.And (vector.parameters);
2153 Breaks = AndFlowReturns (Breaks, vector.Breaks);
2158 Report.Debug (1, "MERGING FINALLY ORIGIN DONE", this);
2161 // Performs an 'or' operation on the locals and the parameters.
2163 public void Or (UsageVector new_vector)
2165 locals.Or (new_vector.locals);
2166 if (parameters != null)
2167 parameters.Or (new_vector.parameters);
2171 // Performs an 'and' operation on the locals.
2173 public void AndLocals (UsageVector new_vector)
2175 locals.And (new_vector.locals);
2179 // Returns a deep copy of the parameters.
2181 public MyBitVector Parameters {
2183 if (parameters != null)
2184 return parameters.Clone ();
2191 // Returns a deep copy of the locals.
2193 public MyBitVector Locals {
2195 return locals.Clone ();
2203 public override string ToString ()
2205 StringBuilder sb = new StringBuilder ();
2207 sb.Append ("Vector (");
2210 sb.Append (Returns);
2213 if (parameters != null) {
2215 sb.Append (parameters);
2221 return sb.ToString ();
2225 FlowBranching (FlowBranchingType type, Location loc)
2227 this.Siblings = new ArrayList ();
2229 this.Location = loc;
2235 // Creates a new flow branching for 'block'.
2236 // This is used from Block.Resolve to create the top-level branching of
2239 public FlowBranching (Block block, InternalParameters ip, Location loc)
2240 : this (FlowBranchingType.BLOCK, loc)
2245 int count = (ip != null) ? ip.Count : 0;
2248 param_map = new int [count];
2249 struct_params = new MyStructInfo [count];
2252 for (int i = 0; i < count; i++) {
2253 //Parameter.Modifier mod = param_info.ParameterModifier (i);
2255 // if ((mod & Parameter.Modifier.OUT) == 0)
2258 param_map [i] = ++num_params;
2260 Type param_type = param_info.ParameterType (i);
2262 struct_params [i] = MyStructInfo.GetStructInfo (param_type);
2263 if (struct_params [i] != null)
2264 num_params += struct_params [i].Count;
2267 Siblings = new ArrayList ();
2268 Siblings.Add (new UsageVector (null, num_params, block.CountVariables));
2272 // Creates a new flow branching which is contained in 'parent'.
2273 // You should only pass non-null for the 'block' argument if this block
2274 // introduces any new variables - in this case, we need to create a new
2275 // usage vector with a different size than our parent's one.
2277 public FlowBranching (FlowBranching parent, FlowBranchingType type,
2278 Block block, Location loc)
2284 if (parent != null) {
2285 param_info = parent.param_info;
2286 param_map = parent.param_map;
2287 struct_params = parent.struct_params;
2288 num_params = parent.num_params;
2293 vector = new UsageVector (parent.CurrentUsageVector, num_params,
2294 Block.CountVariables);
2296 vector = new UsageVector (Parent.CurrentUsageVector);
2298 Siblings.Add (vector);
2301 case FlowBranchingType.EXCEPTION:
2302 finally_vectors = new ArrayList ();
2311 // Returns the branching's current usage vector.
2313 public UsageVector CurrentUsageVector
2316 return (UsageVector) Siblings [Siblings.Count - 1];
2321 // Creates a sibling of the current usage vector.
2323 public void CreateSibling ()
2325 Siblings.Add (new UsageVector (Parent.CurrentUsageVector));
2327 Report.Debug (1, "CREATED SIBLING", CurrentUsageVector);
2331 // Creates a sibling for a 'finally' block.
2333 public void CreateSiblingForFinally ()
2335 if (Type != FlowBranchingType.EXCEPTION)
2336 throw new NotSupportedException ();
2340 CurrentUsageVector.MergeFinallyOrigins (finally_vectors);
2345 // Merge a child branching.
2347 public FlowReturns MergeChild (FlowBranching child)
2349 FlowReturns returns = CurrentUsageVector.MergeChildren (child, child.Siblings);
2351 if (child.Type != FlowBranchingType.LOOP_BLOCK)
2352 MayLeaveLoop |= child.MayLeaveLoop;
2354 MayLeaveLoop = false;
2360 // Does the toplevel merging.
2362 public FlowReturns MergeTopBlock ()
2364 if ((Type != FlowBranchingType.BLOCK) || (Block == null))
2365 throw new NotSupportedException ();
2367 UsageVector vector = new UsageVector (null, num_params, Block.CountVariables);
2369 Report.Debug (1, "MERGING TOP BLOCK", Location, vector);
2371 vector.MergeChildren (this, Siblings);
2374 Siblings.Add (vector);
2376 Report.Debug (1, "MERGING TOP BLOCK DONE", Location, vector);
2378 if (vector.Breaks != FlowReturns.EXCEPTION) {
2379 return vector.AlwaysBreaks ? FlowReturns.ALWAYS : vector.Returns;
2381 return FlowReturns.EXCEPTION;
2384 public bool InTryBlock ()
2386 if (finally_vectors != null)
2388 else if (Parent != null)
2389 return Parent.InTryBlock ();
2394 public void AddFinallyVector (UsageVector vector)
2396 if (finally_vectors != null) {
2397 finally_vectors.Add (vector.Clone ());
2402 Parent.AddFinallyVector (vector);
2404 throw new NotSupportedException ();
2407 public bool IsVariableAssigned (VariableInfo vi)
2409 if (CurrentUsageVector.AlwaysBreaks)
2412 return CurrentUsageVector [vi, 0];
2415 public bool IsVariableAssigned (VariableInfo vi, int field_idx)
2417 if (CurrentUsageVector.AlwaysBreaks)
2420 return CurrentUsageVector [vi, field_idx];
2423 public void SetVariableAssigned (VariableInfo vi)
2425 if (CurrentUsageVector.AlwaysBreaks)
2428 CurrentUsageVector [vi, 0] = true;
2431 public void SetVariableAssigned (VariableInfo vi, int field_idx)
2433 if (CurrentUsageVector.AlwaysBreaks)
2436 CurrentUsageVector [vi, field_idx] = true;
2439 public bool IsParameterAssigned (int number)
2441 int index = param_map [number];
2446 if (CurrentUsageVector [index])
2449 // Parameter is not assigned, so check whether it's a struct.
2450 // If it's either not a struct or a struct which non-public
2451 // fields, return false.
2452 MyStructInfo struct_info = struct_params [number];
2453 if ((struct_info == null) || struct_info.HasNonPublicFields)
2456 // Ok, so each field must be assigned.
2457 for (int i = 0; i < struct_info.Count; i++)
2458 if (!CurrentUsageVector [index + i])
2464 public bool IsParameterAssigned (int number, string field_name)
2466 int index = param_map [number];
2471 MyStructInfo info = (MyStructInfo) struct_params [number];
2475 int field_idx = info [field_name];
2477 return CurrentUsageVector [index + field_idx];
2480 public void SetParameterAssigned (int number)
2482 if (param_map [number] == 0)
2485 if (!CurrentUsageVector.AlwaysBreaks)
2486 CurrentUsageVector [param_map [number]] = true;
2489 public void SetParameterAssigned (int number, string field_name)
2491 int index = param_map [number];
2496 MyStructInfo info = (MyStructInfo) struct_params [number];
2500 int field_idx = info [field_name];
2502 if (!CurrentUsageVector.AlwaysBreaks)
2503 CurrentUsageVector [index + field_idx] = true;
2506 public bool IsReachable ()
2511 case FlowBranchingType.SWITCH_SECTION:
2512 // The code following a switch block is reachable unless the switch
2513 // block always returns.
2514 reachable = !CurrentUsageVector.AlwaysReturns;
2517 case FlowBranchingType.LOOP_BLOCK:
2518 // The code following a loop is reachable unless the loop always
2519 // returns or it's an infinite loop without any 'break's in it.
2520 reachable = !CurrentUsageVector.AlwaysReturns &&
2521 (CurrentUsageVector.Breaks != FlowReturns.UNREACHABLE);
2525 // The code following a block or exception is reachable unless the
2526 // block either always returns or always breaks.
2527 reachable = !CurrentUsageVector.AlwaysBreaks &&
2528 !CurrentUsageVector.AlwaysReturns;
2532 Report.Debug (1, "REACHABLE", Type, CurrentUsageVector.Returns,
2533 CurrentUsageVector.Breaks, CurrentUsageVector, reachable);
2538 public override string ToString ()
2540 StringBuilder sb = new StringBuilder ("FlowBranching (");
2545 if (Block != null) {
2547 sb.Append (Block.ID);
2549 sb.Append (Block.StartLocation);
2552 sb.Append (Siblings.Count);
2554 sb.Append (CurrentUsageVector);
2556 return sb.ToString ();
2560 public class MyStructInfo {
2561 public readonly Type Type;
2562 public readonly FieldInfo[] Fields;
2563 public readonly FieldInfo[] NonPublicFields;
2564 public readonly int Count;
2565 public readonly int CountNonPublic;
2566 public readonly bool HasNonPublicFields;
2568 private static Hashtable field_type_hash = new Hashtable ();
2569 private Hashtable field_hash;
2571 // Private constructor. To save memory usage, we only need to create one instance
2572 // of this class per struct type.
2573 private MyStructInfo (Type type)
2577 if (type is TypeBuilder) {
2578 TypeContainer tc = TypeManager.LookupTypeContainer (type);
2580 ArrayList fields = tc.Fields;
2581 if (fields != null) {
2582 foreach (Field field in fields) {
2583 if ((field.ModFlags & Modifiers.STATIC) != 0)
2585 if ((field.ModFlags & Modifiers.PUBLIC) != 0)
2592 Fields = new FieldInfo [Count];
2593 NonPublicFields = new FieldInfo [CountNonPublic];
2595 Count = CountNonPublic = 0;
2596 if (fields != null) {
2597 foreach (Field field in fields) {
2598 if ((field.ModFlags & Modifiers.STATIC) != 0)
2600 if ((field.ModFlags & Modifiers.PUBLIC) != 0)
2601 Fields [Count++] = field.FieldBuilder;
2603 NonPublicFields [CountNonPublic++] =
2609 Fields = type.GetFields (BindingFlags.Instance|BindingFlags.Public);
2610 Count = Fields.Length;
2612 NonPublicFields = type.GetFields (BindingFlags.Instance|BindingFlags.NonPublic);
2613 CountNonPublic = NonPublicFields.Length;
2616 Count += NonPublicFields.Length;
2619 field_hash = new Hashtable ();
2620 foreach (FieldInfo field in Fields)
2621 field_hash.Add (field.Name, ++number);
2623 if (NonPublicFields.Length != 0)
2624 HasNonPublicFields = true;
2626 foreach (FieldInfo field in NonPublicFields)
2627 field_hash.Add (field.Name, ++number);
2630 public int this [string name] {
2632 if (field_hash.Contains (name))
2633 return (int) field_hash [name];
2639 public FieldInfo this [int index] {
2641 if (index >= Fields.Length)
2642 return NonPublicFields [index - Fields.Length];
2644 return Fields [index];
2648 public static MyStructInfo GetStructInfo (Type type)
2650 if (!TypeManager.IsValueType (type) || TypeManager.IsEnumType (type))
2653 if (!(type is TypeBuilder) && TypeManager.IsBuiltinType (type))
2656 MyStructInfo info = (MyStructInfo) field_type_hash [type];
2660 info = new MyStructInfo (type);
2661 field_type_hash.Add (type, info);
2665 public static MyStructInfo GetStructInfo (TypeContainer tc)
2667 MyStructInfo info = (MyStructInfo) field_type_hash [tc.TypeBuilder];
2671 info = new MyStructInfo (tc.TypeBuilder);
2672 field_type_hash.Add (tc.TypeBuilder, info);
2677 public class VariableInfo : IVariable {
2678 public Expression Type;
2679 public LocalBuilder LocalBuilder;
2680 public Type VariableType;
2681 public string Alias;
2684 public bool Static {
2693 public readonly string Name;
2694 public readonly Location Location;
2695 public readonly int Block;
2700 public bool Assigned;
2701 public bool ReadOnly;
2703 public VariableInfo (Expression type, string name, int block, Location l, string Alias)
2704 : this (type, name, block, l)
2709 public VariableInfo (Expression type, string name, int block, Location l)
2714 LocalBuilder = null;
2718 public VariableInfo (TypeContainer tc, int block, Location l, string Alias)
2719 : this (tc, block, l)
2724 public VariableInfo (TypeContainer tc, int block, Location l)
2726 VariableType = tc.TypeBuilder;
2727 struct_info = MyStructInfo.GetStructInfo (tc);
2729 LocalBuilder = null;
2733 MyStructInfo struct_info;
2734 public MyStructInfo StructInfo {
2740 public bool IsAssigned (EmitContext ec, Location loc)
2741 {/* FIXME: we shouldn't just skip this!!!
2742 if (!ec.DoFlowAnalysis || ec.CurrentBranching.IsVariableAssigned (this))
2745 MyStructInfo struct_info = StructInfo;
2746 if ((struct_info == null) || (struct_info.HasNonPublicFields && (Name != null))) {
2747 Report.Error (165, loc, "Use of unassigned local variable '" + Name + "'");
2748 ec.CurrentBranching.SetVariableAssigned (this);
2752 int count = struct_info.Count;
2754 for (int i = 0; i < count; i++) {
2755 if (!ec.CurrentBranching.IsVariableAssigned (this, i+1)) {
2757 Report.Error (165, loc,
2758 "Use of unassigned local variable '" +
2760 ec.CurrentBranching.SetVariableAssigned (this);
2764 FieldInfo field = struct_info [i];
2765 Report.Error (171, loc,
2766 "Field '" + TypeManager.MonoBASIC_Name (VariableType) +
2767 "." + field.Name + "' must be fully initialized " +
2768 "before control leaves the constructor");
2776 public bool IsFieldAssigned (EmitContext ec, string name, Location loc)
2778 if (!ec.DoFlowAnalysis || ec.CurrentBranching.IsVariableAssigned (this) ||
2779 (struct_info == null))
2782 int field_idx = StructInfo [name];
2786 if (!ec.CurrentBranching.IsVariableAssigned (this, field_idx)) {
2787 Report.Error (170, loc,
2788 "Use of possibly unassigned field '" + name + "'");
2789 ec.CurrentBranching.SetVariableAssigned (this, field_idx);
2796 public void SetAssigned (EmitContext ec)
2798 if (ec.DoFlowAnalysis)
2799 ec.CurrentBranching.SetVariableAssigned (this);
2802 public void SetFieldAssigned (EmitContext ec, string name)
2804 if (ec.DoFlowAnalysis && (struct_info != null))
2805 ec.CurrentBranching.SetVariableAssigned (this, StructInfo [name]);
2808 public bool Resolve (DeclSpace decl)
2810 if (struct_info != null)
2813 if (VariableType == null)
2814 VariableType = decl.ResolveType (Type, false, Location);
2816 if (VariableType == null)
2819 struct_info = MyStructInfo.GetStructInfo (VariableType);
2824 public void MakePinned ()
2826 TypeManager.MakePinned (LocalBuilder);
2829 public override string ToString ()
2831 return "VariableInfo (" + Number + "," + Type + "," + Location + ")";
2836 public class StatementSequence : Expression {
2838 ArrayList args, originalArgs;
2840 bool isRetValRequired;
2841 bool isLeftHandSide;
2842 bool isIndexerAccess;
2844 Expression type_expr;
2845 bool is_resolved = false;
2847 public StatementSequence (Block parent, Location loc, Expression expr)
2848 : this (parent, loc, expr, null)
2851 public StatementSequence (Block parent, Location loc, Expression expr, string name,
2852 Expression type_expr, ArrayList a, bool isRetValRequired,
2853 bool isLeftHandSide)
2854 : this (parent, loc, expr, a)
2856 this.memberName = name;
2857 this.type_expr = type_expr;
2858 this.isRetValRequired = isRetValRequired;
2859 this.isLeftHandSide = isLeftHandSide;
2862 public StatementSequence (Block parent, Location loc, Expression expr, ArrayList a,
2863 bool isRetValRequired, bool isLeftHandSide)
2864 : this (parent, loc, expr, a)
2866 this.isRetValRequired = isRetValRequired;
2867 this.isLeftHandSide = isLeftHandSide;
2868 if (expr is MemberAccess) {
2869 this.expr = ((MemberAccess)expr).Expr;
2870 this.memberName = ((MemberAccess)expr).Identifier;
2871 this.isIndexerAccess = false;
2872 } else if (expr is IndexerAccess) {
2873 this.expr = ((IndexerAccess) expr).Instance;
2874 this.memberName = "";
2875 this.isIndexerAccess = true;
2879 public StatementSequence (Block parent, Location loc, Expression expr, ArrayList a)
2881 stmtBlock = new Block (parent);
2883 originalArgs = new ArrayList ();
2885 for (int index = 0; index < a.Count; index ++) {
2886 Argument argument = (Argument) args [index];
2887 originalArgs.Add (new Argument (argument.Expr, argument.ArgType));
2892 stmtBlock.IsLateBindingRequired = true;
2894 this.isRetValRequired = this.isLeftHandSide = false;
2895 this.memberName = "";
2896 this.type_expr = null;
2899 public ArrayList Arguments {
2908 public bool IsLeftHandSide {
2910 isLeftHandSide = value;
2914 public Block StmtBlock {
2920 public override Expression DoResolve (EmitContext ec)
2924 if (!stmtBlock.Resolve (ec))
2926 eclass = ExprClass.Value;
2927 type = TypeManager.object_type;
2932 public bool ResolveArguments (EmitContext ec) {
2934 bool argNamesFound = false;
2935 if (Arguments != null)
2937 for (int index = 0; index < Arguments.Count; index ++)
2939 Argument a = (Argument) Arguments [index];
2940 if (a.ParamName == null || a.ParamName == "") {
2941 if (argNamesFound) {
2942 Report.Error (30241, loc, "Named Argument expected");
2946 argNamesFound = true;
2947 if (a.ArgType == Argument.AType.NoArg)
2948 a = new Argument (Parser.DecomposeQI ("System.Reflection.Missing.Value", loc), Argument.AType.Expression);
2949 if (!a.Resolve (ec, loc))
2951 Arguments [index] = a;
2957 public void GenerateLateBindingStatements ()
2960 ArrayList arrayInitializers = new ArrayList ();
2961 ArrayList ArgumentNames = null;
2963 //arrayInitializers = new ArrayList ();
2964 argCount = args.Count;
2965 for (int index = 0; index < args.Count; index ++) {
2966 Argument a = (Argument) args [index];
2967 Expression argument = a.Expr;
2968 arrayInitializers.Add (argument);
2969 if (a.ParamName != null && a.ParamName != "") {
2970 if (ArgumentNames == null)
2971 ArgumentNames = new ArrayList ();
2972 ArgumentNames.Add (new StringLiteral (a.ParamName));
2977 // __LateBindingArgs = new Object () {arg1, arg2 ...}
2978 ArrayCreation new_expr = new ArrayCreation (Parser.DecomposeQI ("System.Object", loc), "[]", arrayInitializers, loc);
2979 Assign assign_stmt = null;
2981 LocalVariableReference v1 = new LocalVariableReference (stmtBlock, Block.lateBindingArgs, loc);
2982 assign_stmt = new Assign (v1, new_expr, loc);
2983 stmtBlock.AddStatement (new StatementExpression ((ExpressionStatement) assign_stmt, loc));
2984 // __LateBindingArgNames = new string () { argument names}
2985 LocalVariableReference v2 = null;
2986 if (ArgumentNames != null && ArgumentNames.Count > 0) {
2987 new_expr = new ArrayCreation (Parser.DecomposeQI ("System.String", loc), "[]", ArgumentNames, loc);
2988 v2 = new LocalVariableReference (stmtBlock, Block.lateBindingArgNames, loc);
2989 assign_stmt = new Assign (v2, new_expr, loc);
2990 stmtBlock.AddStatement (new StatementExpression ((ExpressionStatement) assign_stmt, loc));
2993 //string memName = "";
2994 //bool isIndexerAccess = true;
2996 ArrayList invocationArgs = new ArrayList ();
2997 if (isIndexerAccess || memberName == "") {
2998 invocationArgs.Add (new Argument (expr, Argument.AType.Expression));
2999 invocationArgs.Add (new Argument (v1, Argument.AType.Expression));
3000 invocationArgs.Add (new Argument (NullLiteral.Null, Argument.AType.Expression));
3001 Expression tmp = null;
3002 if (!isLeftHandSide)
3003 tmp = Parser.DecomposeQI ("Microsoft.VisualBasic.CompilerServices.LateBinding.LateIndexGet", loc);
3005 tmp = Parser.DecomposeQI ("Microsoft.VisualBasic.CompilerServices.LateBinding.LateIndexSet", loc);
3006 Invocation invStmt = new Invocation (tmp, invocationArgs, Location.Null);
3007 invStmt.IsLateBinding = true;
3008 stmtBlock.AddStatement (new StatementExpression ((ExpressionStatement) invStmt, loc));
3013 invocationArgs.Add (new Argument (expr, Argument.AType.Expression));
3015 invocationArgs.Add (new Argument (NullLiteral.Null, Argument.AType.Expression));
3016 if (type_expr != null)
3017 invocationArgs.Add (new Argument (type_expr, Argument.AType.Expression));
3019 invocationArgs.Add (new Argument (NullLiteral.Null, Argument.AType.Expression));
3020 invocationArgs.Add (new Argument (new StringLiteral (memberName), Argument.AType.Expression));
3021 invocationArgs.Add (new Argument (v1, Argument.AType.Expression));
3022 if (ArgumentNames != null && ArgumentNames.Count > 0)
3023 invocationArgs.Add (new Argument (v2, Argument.AType.Expression));
3025 invocationArgs.Add (new Argument (NullLiteral.Null, Argument.AType.Expression));
3027 // __LateBindingCopyBack = new Boolean (no_of_args) {}
3028 bool isCopyBackRequired = false;
3029 if (!isLeftHandSide) {
3030 for (int i = 0; i < argCount; i++) {
3031 Argument origArg = (Argument) Arguments [i];
3032 Expression origExpr = origArg.Expr;
3033 if (!(origExpr is Constant || origArg.ArgType == Argument.AType.NoArg))
3034 isCopyBackRequired = true;
3038 LocalVariableReference v3 = new LocalVariableReference (stmtBlock, Block.lateBindingCopyBack, loc);
3039 if (isCopyBackRequired) {
3040 ArrayList rank_specifier = new ArrayList ();
3041 rank_specifier.Add (new IntLiteral (argCount));
3042 arrayInitializers = new ArrayList ();
3043 for (int i = 0; i < argCount; i++) {
3044 Argument a = (Argument) Arguments [i];
3045 Expression origExpr = a.Expr;
3046 if (origExpr is Constant || a.ArgType == Argument.AType.NoArg || origExpr is New)
3047 arrayInitializers.Add (new BoolLiteral (false));
3049 arrayInitializers.Add (new BoolLiteral (true));
3052 new_expr = new ArrayCreation (Parser.DecomposeQI ("System.Boolean", loc), "[]", arrayInitializers, loc);
3053 assign_stmt = new Assign (v3, new_expr, loc);
3054 stmtBlock.AddStatement (new StatementExpression ((ExpressionStatement) assign_stmt, loc));
3055 invocationArgs.Add (new Argument (v3, Argument.AType.Expression));
3056 } else if (! isLeftHandSide) {
3057 invocationArgs.Add (new Argument (NullLiteral.Null, Argument.AType.Expression));
3060 Expression etmp = null;
3061 if (isLeftHandSide) {
3063 etmp = Parser.DecomposeQI ("Microsoft.VisualBasic.CompilerServices.LateBinding.LateSet", loc);
3064 } else if (isRetValRequired) {
3066 etmp = Parser.DecomposeQI ("Microsoft.VisualBasic.CompilerServices.LateBinding.LateGet", loc);
3068 etmp = Parser.DecomposeQI ("Microsoft.VisualBasic.CompilerServices.LateBinding.LateCall", loc);
3071 Invocation inv_stmt = new Invocation (etmp, invocationArgs, Location.Null);
3072 inv_stmt.IsLateBinding = true;
3073 stmtBlock.AddStatement (new StatementExpression ((ExpressionStatement) inv_stmt, loc));
3075 if (! isCopyBackRequired)
3078 for (int i = argCount - 1; i >= 0; i --) {
3079 Argument arg = (Argument) originalArgs [i];
3080 Expression origExpr = (Expression) arg.Expr;
3081 if (arg.ArgType == Argument.AType.NoArg)
3083 if (origExpr is Constant)
3085 if (origExpr is New)
3088 Expression intExpr = new IntLiteral (i);
3089 ArrayList argsLocal = new ArrayList ();
3090 argsLocal.Add (new Argument (intExpr, Argument.AType.Expression));
3091 Expression indexExpr = new Invocation (new SimpleName (Block.lateBindingCopyBack, loc), argsLocal, loc);
3092 Expression value = new Invocation (new SimpleName (Block.lateBindingArgs, loc), argsLocal, loc);
3093 assign_stmt = new Assign (origExpr, value, loc);
3094 Expression boolExpr = new Binary (Binary.Operator.Inequality, indexExpr, new BoolLiteral (false), loc);
3095 Statement ifStmt = new If (boolExpr, new StatementExpression ((ExpressionStatement) assign_stmt, loc), loc);
3096 stmtBlock.AddStatement (ifStmt);
3100 public override void Emit (EmitContext ec)
3102 stmtBlock.Emit (ec);
3106 public class SwitchLabel {
3107 public enum LabelType : byte {
3108 Operator, Range, Label, Else
3111 Expression label, start, end;
3112 LabelType label_type;
3113 Expression label_condition, start_condition, end_condition;
3114 Binary.Operator oper;
3115 public Location loc;
3116 public Label ILLabel;
3117 public Label ILLabelCode;
3120 // if expr == null, then it is the default case.
3122 public SwitchLabel (Expression start, Expression end, LabelType ltype, Binary.Operator oper, Location l) {
3125 this.label_type = ltype;
3128 label_condition = start_condition = end_condition = null;
3131 public SwitchLabel (Expression expr, LabelType ltype, Binary.Operator oper, Location l)
3135 label_condition = start_condition = end_condition = null;
3137 this.label_type = ltype;
3141 public Expression Label {
3147 public LabelType Type {
3153 public Expression ConditionStart {
3155 return start_condition;
3159 public Expression ConditionEnd {
3161 return end_condition;
3165 public Expression ConditionLabel {
3167 return label_condition;
3172 // Resolves the expression, reduces it to a literal if possible
3173 // and then converts it to the requested type.
3175 public bool ResolveAndReduce (EmitContext ec, Expression expr)
3177 ILLabel = ec.ig.DefineLabel ();
3178 ILLabelCode = ec.ig.DefineLabel ();
3180 Expression e = null;
3181 switch (label_type) {
3182 case LabelType.Label :
3185 e = label.Resolve (ec);
3187 e = Expression.ConvertImplicit (ec, e, expr.Type, loc);
3190 label_condition = new Binary (Binary.Operator.Equality, expr, e, loc);
3191 if ((label_condition = label_condition.DoResolve (ec)) == null)
3194 case LabelType.Operator :
3195 e = label.Resolve (ec);
3196 label_condition = new Binary (oper, expr, e, loc);
3197 if ((label_condition = label_condition.DoResolve (ec)) == null)
3200 case LabelType.Range :
3201 if (start == null || end == null)
3203 e = start.Resolve (ec);
3205 e = Expression.ConvertImplicit (ec, e, expr.Type, loc);
3208 start_condition = new Binary (Binary.Operator.GreaterThanOrEqual, expr, e, loc);
3209 start_condition = start_condition.Resolve (ec);
3210 e = end.Resolve (ec);
3212 e = Expression.ConvertImplicit (ec, e, expr.Type, loc);
3215 end_condition = new Binary (Binary.Operator.LessThanOrEqual, expr, e, loc);
3216 end_condition = end_condition.Resolve (ec);
3217 if (start_condition == null || end_condition == null)
3221 case LabelType.Else :
3228 public class SwitchSection {
3229 // An array of SwitchLabels.
3230 public readonly ArrayList Labels;
3231 public readonly Block Block;
3233 public SwitchSection (ArrayList labels, Block block)
3240 public class Switch : Statement {
3241 public readonly ArrayList Sections;
3242 public Expression Expr;
3245 /// Maps constants whose type type SwitchType to their SwitchLabels.
3247 public Hashtable Elements;
3250 /// The governing switch type
3252 public Type SwitchType;
3258 Label default_target;
3259 Expression new_expr;
3262 // The types allowed to be implicitly cast from
3263 // on the governing type
3265 //static Type [] allowed_types;
3267 public Switch (Expression e, ArrayList sects, Location l)
3274 public bool GotDefault {
3280 public Label DefaultTarget {
3282 return default_target;
3287 // Determines the governing type for a switch. The returned
3288 // expression might be the expression from the switch, or an
3289 // expression that includes any potential conversions to the
3290 // integral types or to string.
3292 Expression SwitchGoverningType (EmitContext ec, Type t)
3294 if (t == TypeManager.byte_type ||
3295 t == TypeManager.short_type ||
3296 t == TypeManager.int32_type ||
3297 t == TypeManager.int64_type ||
3298 t == TypeManager.decimal_type ||
3299 t == TypeManager.float_type ||
3300 t == TypeManager.double_type ||
3301 t == TypeManager.date_type ||
3302 t == TypeManager.char_type ||
3303 t == TypeManager.object_type ||
3304 t == TypeManager.string_type ||
3305 t == TypeManager.bool_type ||
3306 t.IsSubclassOf (TypeManager.enum_type))
3309 if (allowed_types == null){
3310 allowed_types = new Type [] {
3311 TypeManager.sbyte_type,
3312 TypeManager.byte_type,
3313 TypeManager.short_type,
3314 TypeManager.ushort_type,
3315 TypeManager.int32_type,
3316 TypeManager.uint32_type,
3317 TypeManager.int64_type,
3318 TypeManager.uint64_type,
3319 TypeManager.char_type,
3320 TypeManager.bool_type,
3321 TypeManager.string_type
3326 // Try to find a *user* defined implicit conversion.
3328 // If there is no implicit conversion, or if there are multiple
3329 // conversions, we have to report an error
3331 Expression converted = null;
3332 foreach (Type tt in allowed_types){
3335 e = Expression.ImplicitUserConversion (ec, Expr, tt, loc);
3339 if (converted != null){
3340 Report.Error (-12, loc, "More than one conversion to an integral " +
3341 " type exists for type '" +
3342 TypeManager.MonoBASIC_Name (Expr.Type)+"'");
3352 void error152 (string n)
3355 152, "The label '" + n + ":' " +
3356 "is already present on this switch statement");
3360 // Performs the basic sanity checks on the switch statement
3361 // (looks for duplicate keys and non-constant expressions).
3363 // It also returns a hashtable with the keys that we will later
3364 // use to compute the switch tables
3366 bool CheckSwitch (EmitContext ec)
3368 //Type compare_type;
3370 Elements = new CaseInsensitiveHashtable ();
3372 got_default = false;
3375 if (TypeManager.IsEnumType (SwitchType)){
3376 compare_type = TypeManager.EnumToUnderlying (SwitchType);
3378 compare_type = SwitchType;
3381 for (int secIndex = 0; secIndex < Sections.Count; secIndex ++) {
3382 SwitchSection ss = (SwitchSection) Sections [secIndex];
3383 for (int labelIndex = 0; labelIndex < ss.Labels.Count; labelIndex ++) {
3384 SwitchLabel sl = (SwitchLabel) ss.Labels [labelIndex];
3385 if (!sl.ResolveAndReduce (ec, Expr)){
3390 if (sl.Type == SwitchLabel.LabelType.Else){
3392 error152 ("default");
3406 void EmitObjectInteger (ILGenerator ig, object k)
3409 IntConstant.EmitInt (ig, (int) k);
3410 else if (k is Constant) {
3411 EmitObjectInteger (ig, ((Constant) k).GetValue ());
3414 IntConstant.EmitInt (ig, unchecked ((int) (uint) k));
3417 if ((long) k >= int.MinValue && (long) k <= int.MaxValue)
3419 IntConstant.EmitInt (ig, (int) (long) k);
3420 ig.Emit (OpCodes.Conv_I8);
3423 LongConstant.EmitLong (ig, (long) k);
3425 else if (k is ulong)
3427 if ((ulong) k < (1L<<32))
3429 IntConstant.EmitInt (ig, (int) (long) k);
3430 ig.Emit (OpCodes.Conv_U8);
3434 LongConstant.EmitLong (ig, unchecked ((long) (ulong) k));
3438 IntConstant.EmitInt (ig, (int) ((char) k));
3439 else if (k is sbyte)
3440 IntConstant.EmitInt (ig, (int) ((sbyte) k));
3442 IntConstant.EmitInt (ig, (int) ((byte) k));
3443 else if (k is short)
3444 IntConstant.EmitInt (ig, (int) ((short) k));
3445 else if (k is ushort)
3446 IntConstant.EmitInt (ig, (int) ((ushort) k));
3448 IntConstant.EmitInt (ig, ((bool) k) ? 1 : 0);
3450 throw new Exception ("Unhandled case");
3453 // structure used to hold blocks of keys while calculating table switch
3454 class KeyBlock : IComparable
3456 public KeyBlock (long _nFirst)
3458 nFirst = nLast = _nFirst;
3462 public ArrayList rgKeys = null;
3465 get { return (int) (nLast - nFirst + 1); }
3467 public static long TotalLength (KeyBlock kbFirst, KeyBlock kbLast)
3469 return kbLast.nLast - kbFirst.nFirst + 1;
3471 public int CompareTo (object obj)
3473 KeyBlock kb = (KeyBlock) obj;
3474 int nLength = Length;
3475 int nLengthOther = kb.Length;
3476 if (nLengthOther == nLength)
3477 return (int) (kb.nFirst - nFirst);
3478 return nLength - nLengthOther;
3484 /// This method emits code for a lookup-based switch statement (non-string)
3485 /// Basically it groups the cases into blocks that are at least half full,
3486 /// and then spits out individual lookup opcodes for each block.
3487 /// It emits the longest blocks first, and short blocks are just
3488 /// handled with direct compares.
3490 /// <param name="ec"></param>
3491 /// <param name="val"></param>
3492 /// <returns></returns>
3493 bool TableSwitchEmit (EmitContext ec, LocalBuilder val)
3495 int cElements = Elements.Count;
3496 object [] rgKeys = new object [cElements];
3497 Elements.Keys.CopyTo (rgKeys, 0);
3498 Array.Sort (rgKeys);
3500 // initialize the block list with one element per key
3501 ArrayList rgKeyBlocks = new ArrayList ();
3502 foreach (object key in rgKeys)
3503 rgKeyBlocks.Add (new KeyBlock (Convert.ToInt64 (key)));
3506 // iteratively merge the blocks while they are at least half full
3507 // there's probably a really cool way to do this with a tree...
3508 while (rgKeyBlocks.Count > 1)
3510 ArrayList rgKeyBlocksNew = new ArrayList ();
3511 kbCurr = (KeyBlock) rgKeyBlocks [0];
3512 for (int ikb = 1; ikb < rgKeyBlocks.Count; ikb++)
3514 KeyBlock kb = (KeyBlock) rgKeyBlocks [ikb];
3515 if ((kbCurr.Length + kb.Length) * 2 >= KeyBlock.TotalLength (kbCurr, kb))
3518 kbCurr.nLast = kb.nLast;
3522 // start a new block
3523 rgKeyBlocksNew.Add (kbCurr);
3527 rgKeyBlocksNew.Add (kbCurr);
3528 if (rgKeyBlocks.Count == rgKeyBlocksNew.Count)
3530 rgKeyBlocks = rgKeyBlocksNew;
3533 // initialize the key lists
3534 foreach (KeyBlock kb in rgKeyBlocks)
3535 kb.rgKeys = new ArrayList ();
3537 // fill the key lists
3539 if (rgKeyBlocks.Count > 0) {
3540 kbCurr = (KeyBlock) rgKeyBlocks [0];
3541 foreach (object key in rgKeys)
3543 bool fNextBlock = (key is UInt64) ? (ulong) key > (ulong) kbCurr.nLast : Convert.ToInt64 (key) > kbCurr.nLast;
3545 kbCurr = (KeyBlock) rgKeyBlocks [++iBlockCurr];
3546 kbCurr.rgKeys.Add (key);
3550 // sort the blocks so we can tackle the largest ones first
3551 rgKeyBlocks.Sort ();
3553 // okay now we can start...
3554 ILGenerator ig = ec.ig;
3555 Label lblEnd = ig.DefineLabel (); // at the end ;-)
3556 Label lblDefault = ig.DefineLabel ();
3558 Type typeKeys = null;
3559 if (rgKeys.Length > 0)
3560 typeKeys = rgKeys [0].GetType (); // used for conversions
3562 for (int iBlock = rgKeyBlocks.Count - 1; iBlock >= 0; --iBlock)
3564 KeyBlock kb = ((KeyBlock) rgKeyBlocks [iBlock]);
3565 lblDefault = (iBlock == 0) ? DefaultTarget : ig.DefineLabel ();
3568 foreach (object key in kb.rgKeys)
3570 ig.Emit (OpCodes.Ldloc, val);
3571 EmitObjectInteger (ig, key);
3572 SwitchLabel sl = (SwitchLabel) Elements [key];
3573 ig.Emit (OpCodes.Beq, sl.ILLabel);
3578 // TODO: if all the keys in the block are the same and there are
3579 // no gaps/defaults then just use a range-check.
3580 if (SwitchType == TypeManager.int64_type ||
3581 SwitchType == TypeManager.uint64_type)
3583 // TODO: optimize constant/I4 cases
3585 // check block range (could be > 2^31)
3586 ig.Emit (OpCodes.Ldloc, val);
3587 EmitObjectInteger (ig, Convert.ChangeType (kb.nFirst, typeKeys));
3588 ig.Emit (OpCodes.Blt, lblDefault);
3589 ig.Emit (OpCodes.Ldloc, val);
3590 EmitObjectInteger (ig, Convert.ChangeType (kb.nFirst, typeKeys));
3591 ig.Emit (OpCodes.Bgt, lblDefault);
3594 ig.Emit (OpCodes.Ldloc, val);
3597 EmitObjectInteger (ig, Convert.ChangeType (kb.nFirst, typeKeys));
3598 ig.Emit (OpCodes.Sub);
3600 ig.Emit (OpCodes.Conv_I4); // assumes < 2^31 labels!
3605 ig.Emit (OpCodes.Ldloc, val);
3606 int nFirst = (int) kb.nFirst;
3609 IntConstant.EmitInt (ig, nFirst);
3610 ig.Emit (OpCodes.Sub);
3612 else if (nFirst < 0)
3614 IntConstant.EmitInt (ig, -nFirst);
3615 ig.Emit (OpCodes.Add);
3619 // first, build the list of labels for the switch
3621 int cJumps = kb.Length;
3622 Label [] rgLabels = new Label [cJumps];
3623 for (int iJump = 0; iJump < cJumps; iJump++)
3625 object key = kb.rgKeys [iKey];
3626 if (Convert.ToInt64 (key) == kb.nFirst + iJump)
3628 SwitchLabel sl = (SwitchLabel) Elements [key];
3629 rgLabels [iJump] = sl.ILLabel;
3633 rgLabels [iJump] = lblDefault;
3635 // emit the switch opcode
3636 ig.Emit (OpCodes.Switch, rgLabels);
3639 // mark the default for this block
3641 ig.MarkLabel (lblDefault);
3644 // TODO: find the default case and emit it here,
3645 // to prevent having to do the following jump.
3646 // make sure to mark other labels in the default section
3648 // the last default just goes to the end
3649 ig.Emit (OpCodes.Br, lblDefault);
3651 // now emit the code for the sections
3652 bool fFoundDefault = false;
3653 bool fAllReturn = true;
3654 foreach (SwitchSection ss in Sections)
3656 foreach (SwitchLabel sl in ss.Labels)
3658 ig.MarkLabel (sl.ILLabel);
3659 ig.MarkLabel (sl.ILLabelCode);
3660 if (sl.Label == null)
3662 ig.MarkLabel (lblDefault);
3663 fFoundDefault = true;
3666 bool returns = ss.Block.Emit (ec);
3667 fAllReturn &= returns;
3668 //ig.Emit (OpCodes.Br, lblEnd);
3671 if (!fFoundDefault) {
3672 ig.MarkLabel (lblDefault);
3675 ig.MarkLabel (lblEnd);
3680 // This simple emit switch works, but does not take advantage of the
3682 // TODO: remove non-string logic from here
3683 // TODO: binary search strings?
3685 bool SimpleSwitchEmit (EmitContext ec, LocalBuilder val)
3687 ILGenerator ig = ec.ig;
3688 Label end_of_switch = ig.DefineLabel ();
3689 Label next_test = ig.DefineLabel ();
3690 Label null_target = ig.DefineLabel ();
3691 bool default_found = false;
3692 bool first_test = true;
3693 bool pending_goto_end = false;
3694 bool all_return = true;
3695 bool is_string = false;
3699 // Special processing for strings: we cant compare
3702 if (SwitchType == TypeManager.string_type){
3703 ig.Emit (OpCodes.Ldloc, val);
3706 if (Elements.Contains (NullLiteral.Null)){
3707 ig.Emit (OpCodes.Brfalse, null_target);
3709 ig.Emit (OpCodes.Brfalse, default_target);
3711 ig.Emit (OpCodes.Ldloc, val);
3712 ig.Emit (OpCodes.Call, TypeManager.string_isinterneted_string);
3713 ig.Emit (OpCodes.Stloc, val);
3716 foreach (SwitchSection ss in Sections){
3717 Label sec_begin = ig.DefineLabel ();
3719 if (pending_goto_end)
3720 ig.Emit (OpCodes.Br, end_of_switch);
3722 int label_count = ss.Labels.Count;
3724 foreach (SwitchLabel sl in ss.Labels){
3725 ig.MarkLabel (sl.ILLabel);
3728 ig.MarkLabel (next_test);
3729 next_test = ig.DefineLabel ();
3732 // If we are the default target
3734 if (sl.Label == null){
3735 ig.MarkLabel (default_target);
3736 default_found = true;
3738 object lit = sl.Converted;
3740 if (lit is NullLiteral){
3742 if (label_count == 1)
3743 ig.Emit (OpCodes.Br, next_test);
3748 StringConstant str = (StringConstant) lit;
3750 ig.Emit (OpCodes.Ldloc, val);
3751 ig.Emit (OpCodes.Ldstr, str.Value);
3752 if (label_count == 1)
3753 ig.Emit (OpCodes.Bne_Un, next_test);
3755 ig.Emit (OpCodes.Beq, sec_begin);
3757 ig.Emit (OpCodes.Ldloc, val);
3758 EmitObjectInteger (ig, lit);
3759 ig.Emit (OpCodes.Ceq);
3760 if (label_count == 1)
3761 ig.Emit (OpCodes.Brfalse, next_test);
3763 ig.Emit (OpCodes.Brtrue, sec_begin);
3767 if (label_count != 1)
3768 ig.Emit (OpCodes.Br, next_test);
3771 ig.MarkLabel (null_target);
3772 ig.MarkLabel (sec_begin);
3773 foreach (SwitchLabel sl in ss.Labels)
3774 ig.MarkLabel (sl.ILLabelCode);
3776 bool returns = ss.Block.Emit (ec);
3778 pending_goto_end = false;
3781 pending_goto_end = true;
3785 if (!default_found){
3786 ig.MarkLabel (default_target);
3789 ig.MarkLabel (next_test);
3790 ig.MarkLabel (end_of_switch);
3796 public override bool Resolve (EmitContext ec)
3798 Expr = Expr.Resolve (ec);
3802 new_expr = SwitchGoverningType (ec, Expr.Type);
3803 if (new_expr == null){
3804 Report.Error (30338, loc, "'Select' expression cannot be of type '" + Expr.Type +"'");
3809 SwitchType = new_expr.Type;
3811 if (!CheckSwitch (ec))
3814 Switch old_switch = ec.Switch;
3816 ec.Switch.SwitchType = SwitchType;
3818 ec.StartFlowBranching (FlowBranchingType.SWITCH, loc);
3821 foreach (SwitchSection ss in Sections){
3823 ec.CurrentBranching.CreateSibling ();
3827 if (ss.Block.Resolve (ec) != true)
3833 ec.CurrentBranching.CreateSibling ();
3835 ec.EndFlowBranching ();
3836 ec.Switch = old_switch;
3841 protected override bool DoEmit (EmitContext ec)
3843 ILGenerator ig = ec.ig;
3845 // Setup the codegen context
3847 Label old_end = ec.LoopEnd;
3848 Switch old_switch = ec.Switch;
3850 ec.LoopEnd = ig.DefineLabel ();
3853 for (int secIndex = 0; secIndex < Sections.Count; secIndex ++) {
3854 SwitchSection section = (SwitchSection) Sections [secIndex];
3855 Label sLabel = ig.DefineLabel ();
3856 Label lLabel = ig.DefineLabel ();
3857 ArrayList Labels = section.Labels;
3858 for (int labelIndex = 0; labelIndex < Labels.Count; labelIndex ++) {
3859 SwitchLabel sl = (SwitchLabel) Labels [labelIndex];
3861 case SwitchLabel.LabelType.Range :
3862 if (labelIndex + 1 == Labels.Count) {
3863 EmitBoolExpression (ec, sl.ConditionStart, sLabel, false);
3864 EmitBoolExpression (ec, sl.ConditionEnd, sLabel, false);
3865 ig.Emit (OpCodes.Br, lLabel);
3867 Label newLabel = ig.DefineLabel ();
3868 EmitBoolExpression (ec, sl.ConditionStart, newLabel, false);
3869 EmitBoolExpression (ec, sl.ConditionEnd, newLabel, false);
3870 ig.Emit (OpCodes.Br, lLabel);
3871 ig.MarkLabel (newLabel);
3874 case SwitchLabel.LabelType.Else :
3875 // Nothing to be done here
3877 case SwitchLabel.LabelType.Operator :
3878 EmitBoolExpression (ec, sl.ConditionLabel, lLabel, true);
3879 if (labelIndex + 1 == Labels.Count)
3880 ig.Emit (OpCodes.Br, sLabel);
3882 case SwitchLabel.LabelType.Label :
3883 EmitBoolExpression (ec, sl.ConditionLabel, lLabel, true);
3884 if (labelIndex + 1 == Labels.Count)
3885 ig.Emit (OpCodes.Br, sLabel);
3890 ig.MarkLabel (lLabel);
3891 section.Block.Emit (ec);
3892 ig.MarkLabel (sLabel);
3895 // Restore context state.
3896 ig.MarkLabel (ec.LoopEnd);
3899 // Restore the previous context
3901 ec.LoopEnd = old_end;
3902 ec.Switch = old_switch;
3907 public class Lock : Statement {
3909 Statement Statement;
3911 public Lock (Expression expr, Statement stmt, Location l)
3918 public override bool Resolve (EmitContext ec)
3920 expr = expr.Resolve (ec);
3921 return Statement.Resolve (ec) && expr != null;
3924 protected override bool DoEmit (EmitContext ec)
3926 Type type = expr.Type;
3929 if (type.IsValueType){
3930 Report.Error (30582, loc, "lock statement requires the expression to be " +
3931 " a reference type (type is: '" +
3932 TypeManager.MonoBASIC_Name (type) + "'");
3936 ILGenerator ig = ec.ig;
3937 LocalBuilder temp = ig.DeclareLocal (type);
3940 ig.Emit (OpCodes.Dup);
3941 ig.Emit (OpCodes.Stloc, temp);
3942 ig.Emit (OpCodes.Call, TypeManager.void_monitor_enter_object);
3945 ig.BeginExceptionBlock ();
3946 bool old_in_try = ec.InTry;
3948 Label finish = ig.DefineLabel ();
3949 val = Statement.Emit (ec);
3950 ec.InTry = old_in_try;
3951 // ig.Emit (OpCodes.Leave, finish);
3953 ig.MarkLabel (finish);
3956 ig.BeginFinallyBlock ();
3957 ig.Emit (OpCodes.Ldloc, temp);
3958 ig.Emit (OpCodes.Call, TypeManager.void_monitor_exit_object);
3959 ig.EndExceptionBlock ();
3965 public class Unchecked : Statement {
3966 public readonly Block Block;
3968 public Unchecked (Block b)
3973 public override bool Resolve (EmitContext ec)
3975 return Block.Resolve (ec);
3978 protected override bool DoEmit (EmitContext ec)
3980 bool previous_state = ec.CheckState;
3981 bool previous_state_const = ec.ConstantCheckState;
3984 ec.CheckState = false;
3985 ec.ConstantCheckState = false;
3986 val = Block.Emit (ec);
3987 ec.CheckState = previous_state;
3988 ec.ConstantCheckState = previous_state_const;
3994 public class Checked : Statement {
3995 public readonly Block Block;
3997 public Checked (Block b)
4002 public override bool Resolve (EmitContext ec)
4004 bool previous_state = ec.CheckState;
4005 bool previous_state_const = ec.ConstantCheckState;
4007 ec.CheckState = true;
4008 ec.ConstantCheckState = true;
4009 bool ret = Block.Resolve (ec);
4010 ec.CheckState = previous_state;
4011 ec.ConstantCheckState = previous_state_const;
4016 protected override bool DoEmit (EmitContext ec)
4018 bool previous_state = ec.CheckState;
4019 bool previous_state_const = ec.ConstantCheckState;
4022 ec.CheckState = true;
4023 ec.ConstantCheckState = true;
4024 val = Block.Emit (ec);
4025 ec.CheckState = previous_state;
4026 ec.ConstantCheckState = previous_state_const;
4032 public class Unsafe : Statement {
4033 public readonly Block Block;
4035 public Unsafe (Block b)
4040 public override bool Resolve (EmitContext ec)
4042 bool previous_state = ec.InUnsafe;
4046 val = Block.Resolve (ec);
4047 ec.InUnsafe = previous_state;
4052 protected override bool DoEmit (EmitContext ec)
4054 bool previous_state = ec.InUnsafe;
4058 val = Block.Emit (ec);
4059 ec.InUnsafe = previous_state;
4068 public class Fixed : Statement {
4070 ArrayList declarators;
4071 Statement statement;
4076 public bool is_object;
4077 public VariableInfo vi;
4078 public Expression expr;
4079 public Expression converted;
4082 public Fixed (Expression type, ArrayList decls, Statement stmt, Location l)
4085 declarators = decls;
4090 public override bool Resolve (EmitContext ec)
4092 expr_type = ec.DeclSpace.ResolveType (type, false, loc);
4093 if (expr_type == null)
4096 data = new FixedData [declarators.Count];
4099 foreach (Pair p in declarators){
4100 VariableInfo vi = (VariableInfo) p.First;
4101 Expression e = (Expression) p.Second;
4106 // The rules for the possible declarators are pretty wise,
4107 // but the production on the grammar is more concise.
4109 // So we have to enforce these rules here.
4111 // We do not resolve before doing the case 1 test,
4112 // because the grammar is explicit in that the token &
4113 // is present, so we need to test for this particular case.
4117 // Case 1: & object.
4119 if (e is Unary && ((Unary) e).Oper == Unary.Operator.AddressOf){
4120 Expression child = ((Unary) e).Expr;
4123 if (child is ParameterReference || child is LocalVariableReference){
4126 "No need to use fixed statement for parameters or " +
4127 "local variable declarations (address is already " +
4136 child = ((Unary) e).Expr;
4138 if (!TypeManager.VerifyUnManaged (child.Type, loc))
4141 data [i].is_object = true;
4143 data [i].converted = null;
4157 if (e.Type.IsArray){
4158 Type array_type = e.Type.GetElementType ();
4162 // Provided that array_type is unmanaged,
4164 if (!TypeManager.VerifyUnManaged (array_type, loc))
4168 // and T* is implicitly convertible to the
4169 // pointer type given in the fixed statement.
4171 ArrayPtr array_ptr = new ArrayPtr (e, loc);
4173 Expression converted = Expression.ConvertImplicitRequired (
4174 ec, array_ptr, vi.VariableType, loc);
4175 if (converted == null)
4178 data [i].is_object = false;
4180 data [i].converted = converted;
4190 if (e.Type == TypeManager.string_type){
4191 data [i].is_object = false;
4193 data [i].converted = null;
4199 return statement.Resolve (ec);
4202 protected override bool DoEmit (EmitContext ec)
4204 ILGenerator ig = ec.ig;
4206 bool is_ret = false;
4208 for (int i = 0; i < data.Length; i++) {
4209 VariableInfo vi = data [i].vi;
4212 // Case 1: & object.
4214 if (data [i].is_object) {
4216 // Store pointer in pinned location
4218 data [i].expr.Emit (ec);
4219 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
4221 is_ret = statement.Emit (ec);
4223 // Clear the pinned variable.
4224 ig.Emit (OpCodes.Ldc_I4_0);
4225 ig.Emit (OpCodes.Conv_U);
4226 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
4234 if (data [i].expr.Type.IsArray){
4236 // Store pointer in pinned location
4238 data [i].converted.Emit (ec);
4240 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
4242 is_ret = statement.Emit (ec);
4244 // Clear the pinned variable.
4245 ig.Emit (OpCodes.Ldc_I4_0);
4246 ig.Emit (OpCodes.Conv_U);
4247 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
4255 if (data [i].expr.Type == TypeManager.string_type){
4256 LocalBuilder pinned_string = ig.DeclareLocal (TypeManager.string_type);
4257 TypeManager.MakePinned (pinned_string);
4259 data [i].expr.Emit (ec);
4260 ig.Emit (OpCodes.Stloc, pinned_string);
4262 Expression sptr = new StringPtr (pinned_string, loc);
4263 Expression converted = Expression.ConvertImplicitRequired (
4264 ec, sptr, vi.VariableType, loc);
4266 if (converted == null)
4269 converted.Emit (ec);
4270 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
4272 is_ret = statement.Emit (ec);
4274 // Clear the pinned variable
4275 ig.Emit (OpCodes.Ldnull);
4276 ig.Emit (OpCodes.Stloc, pinned_string);
4284 public class Catch {
4285 public readonly string Name;
4286 public readonly Block Block;
4287 public Expression Clause;
4288 public readonly Location Location;
4290 Expression type_expr;
4291 //Expression clus_expr;
4294 public Catch (Expression type, string name, Block block, Expression clause, Location l)
4303 public Type CatchType {
4309 public bool IsGeneral {
4311 return type_expr == null;
4315 public bool Resolve (EmitContext ec)
4317 if (type_expr != null) {
4318 type = ec.DeclSpace.ResolveType (type_expr, false, Location);
4322 if (type != TypeManager.exception_type && !type.IsSubclassOf (TypeManager.exception_type)){
4323 Report.Error (30665, Location,
4324 "The type caught or thrown must be derived " +
4325 "from System.Exception");
4331 if (Clause != null) {
4332 Clause = Statement.ResolveBoolean (ec, Clause, Location);
4333 if (Clause == null) {
4338 if (!Block.Resolve (ec))
4345 public class Try : Statement {
4346 public readonly Block Fini, Block;
4347 public readonly ArrayList Specific;
4348 public readonly Catch General;
4351 // specific, general and fini might all be null.
4353 public Try (Block block, ArrayList specific, Catch general, Block fini, Location l)
4355 if (specific == null && general == null){
4356 Console.WriteLine ("CIR.Try: Either specific or general have to be non-null");
4360 this.Specific = specific;
4361 this.General = general;
4366 public override bool Resolve (EmitContext ec)
4370 ec.StartFlowBranching (FlowBranchingType.EXCEPTION, Block.StartLocation);
4372 Report.Debug (1, "START OF TRY BLOCK", Block.StartLocation);
4374 bool old_in_try = ec.InTry;
4377 if (!Block.Resolve (ec))
4380 ec.InTry = old_in_try;
4382 FlowBranching.UsageVector vector = ec.CurrentBranching.CurrentUsageVector;
4384 Report.Debug (1, "START OF CATCH BLOCKS", vector);
4386 foreach (Catch c in Specific){
4387 ec.CurrentBranching.CreateSibling ();
4388 Report.Debug (1, "STARTED SIBLING FOR CATCH", ec.CurrentBranching);
4390 if (c.Name != null) {
4391 VariableInfo vi = c.Block.GetVariableInfo (c.Name);
4393 throw new Exception ();
4398 bool old_in_catch = ec.InCatch;
4401 if (!c.Resolve (ec))
4404 ec.InCatch = old_in_catch;
4406 FlowBranching.UsageVector current = ec.CurrentBranching.CurrentUsageVector;
4408 if (!current.AlwaysReturns && !current.AlwaysBreaks)
4409 vector.AndLocals (current);
4412 Report.Debug (1, "END OF CATCH BLOCKS", ec.CurrentBranching);
4414 if (General != null){
4415 ec.CurrentBranching.CreateSibling ();
4416 Report.Debug (1, "STARTED SIBLING FOR GENERAL", ec.CurrentBranching);
4418 bool old_in_catch = ec.InCatch;
4421 if (!General.Resolve (ec))
4424 ec.InCatch = old_in_catch;
4426 FlowBranching.UsageVector current = ec.CurrentBranching.CurrentUsageVector;
4428 if (!current.AlwaysReturns && !current.AlwaysBreaks)
4429 vector.AndLocals (current);
4432 Report.Debug (1, "END OF GENERAL CATCH BLOCKS", ec.CurrentBranching);
4435 ec.CurrentBranching.CreateSiblingForFinally ();
4436 Report.Debug (1, "STARTED SIBLING FOR FINALLY", ec.CurrentBranching, vector);
4438 bool old_in_finally = ec.InFinally;
4439 ec.InFinally = true;
4441 if (!Fini.Resolve (ec))
4444 ec.InFinally = old_in_finally;
4447 FlowReturns returns = ec.EndFlowBranching ();
4449 FlowBranching.UsageVector f_vector = ec.CurrentBranching.CurrentUsageVector;
4451 Report.Debug (1, "END OF FINALLY", ec.CurrentBranching, returns, vector, f_vector);
4452 ec.CurrentBranching.CurrentUsageVector.Or (vector);
4454 Report.Debug (1, "END OF TRY", ec.CurrentBranching);
4459 protected override bool DoEmit (EmitContext ec)
4461 ILGenerator ig = ec.ig;
4465 Label finish = ig.BeginExceptionBlock ();
4466 ec.HasExitLabel = true;
4467 ec.ExitLabel = finish;
4469 bool old_in_try = ec.InTry;
4471 returns = Block.Emit (ec);
4472 ec.InTry = old_in_try;
4475 // System.Reflection.Emit provides this automatically:
4476 // ig.Emit (OpCodes.Leave, finish);
4478 bool old_in_catch = ec.InCatch;
4480 //DeclSpace ds = ec.DeclSpace;
4482 foreach (Catch c in Specific){
4485 ig.BeginCatchBlock (c.CatchType);
4487 if (c.Name != null){
4488 vi = c.Block.GetVariableInfo (c.Name);
4490 throw new Exception ("Variable does not exist in this block");
4492 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
4494 ig.Emit (OpCodes.Pop);
4497 // if when clause is there
4499 if (c.Clause != null) {
4500 if (c.Clause is BoolConstant) {
4501 bool take = ((BoolConstant) c.Clause).Value;
4504 if (!c.Block.Emit (ec))
4507 EmitBoolExpression (ec, c.Clause, finish, false);
4508 if (!c.Block.Emit (ec))
4512 if (!c.Block.Emit (ec))
4516 if (General != null){
4517 ig.BeginCatchBlock (TypeManager.object_type);
4518 ig.Emit (OpCodes.Pop);
4520 if (General.Clause != null) {
4521 if (General.Clause is BoolConstant) {
4522 bool take = ((BoolConstant) General.Clause).Value;
4524 if (!General.Block.Emit (ec))
4527 EmitBoolExpression (ec, General.Clause, finish, false);
4528 if (!General.Block.Emit (ec))
4532 if (!General.Block.Emit (ec))
4536 ec.InCatch = old_in_catch;
4539 ig.BeginFinallyBlock ();
4540 bool old_in_finally = ec.InFinally;
4541 ec.InFinally = true;
4543 ec.InFinally = old_in_finally;
4546 ig.EndExceptionBlock ();
4549 if (!returns || ec.InTry || ec.InCatch)
4556 public class Using : Statement {
4557 object expression_or_block;
4558 Statement Statement;
4563 Expression [] converted_vars;
4564 ExpressionStatement [] assign;
4566 public Using (object expression_or_block, Statement stmt, Location l)
4568 this.expression_or_block = expression_or_block;
4574 // Resolves for the case of using using a local variable declaration.
4576 bool ResolveLocalVariableDecls (EmitContext ec)
4578 bool need_conv = false;
4579 expr_type = ec.DeclSpace.ResolveType (expr, false, loc);
4582 if (expr_type == null)
4586 // The type must be an IDisposable or an implicit conversion
4589 converted_vars = new Expression [var_list.Count];
4590 assign = new ExpressionStatement [var_list.Count];
4591 if (!TypeManager.ImplementsInterface (expr_type, TypeManager.idisposable_type)){
4592 foreach (DictionaryEntry e in var_list){
4593 Expression var = (Expression) e.Key;
4595 var = var.ResolveLValue (ec, new EmptyExpression ());
4599 converted_vars [i] = Expression.ConvertImplicitRequired (
4600 ec, var, TypeManager.idisposable_type, loc);
4602 if (converted_vars [i] == null)
4610 foreach (DictionaryEntry e in var_list){
4611 LocalVariableReference var = (LocalVariableReference) e.Key;
4612 Expression new_expr = (Expression) e.Value;
4615 a = new Assign (var, new_expr, loc);
4621 converted_vars [i] = var;
4622 assign [i] = (ExpressionStatement) a;
4629 bool ResolveExpression (EmitContext ec)
4631 if (!TypeManager.ImplementsInterface (expr_type, TypeManager.idisposable_type)){
4632 conv = Expression.ConvertImplicitRequired (
4633 ec, expr, TypeManager.idisposable_type, loc);
4643 // Emits the code for the case of using using a local variable declaration.
4645 bool EmitLocalVariableDecls (EmitContext ec)
4647 ILGenerator ig = ec.ig;
4650 bool old_in_try = ec.InTry;
4652 for (i = 0; i < assign.Length; i++) {
4653 assign [i].EmitStatement (ec);
4655 ig.BeginExceptionBlock ();
4657 Statement.Emit (ec);
4658 ec.InTry = old_in_try;
4660 bool old_in_finally = ec.InFinally;
4661 ec.InFinally = true;
4662 var_list.Reverse ();
4663 foreach (DictionaryEntry e in var_list){
4664 LocalVariableReference var = (LocalVariableReference) e.Key;
4665 Label skip = ig.DefineLabel ();
4668 ig.BeginFinallyBlock ();
4671 ig.Emit (OpCodes.Brfalse, skip);
4672 converted_vars [i].Emit (ec);
4673 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
4674 ig.MarkLabel (skip);
4675 ig.EndExceptionBlock ();
4677 ec.InFinally = old_in_finally;
4682 bool EmitExpression (EmitContext ec)
4685 // Make a copy of the expression and operate on that.
4687 ILGenerator ig = ec.ig;
4688 LocalBuilder local_copy = ig.DeclareLocal (expr_type);
4693 ig.Emit (OpCodes.Stloc, local_copy);
4695 bool old_in_try = ec.InTry;
4697 ig.BeginExceptionBlock ();
4698 Statement.Emit (ec);
4699 ec.InTry = old_in_try;
4701 Label skip = ig.DefineLabel ();
4702 bool old_in_finally = ec.InFinally;
4703 ig.BeginFinallyBlock ();
4704 ig.Emit (OpCodes.Ldloc, local_copy);
4705 ig.Emit (OpCodes.Brfalse, skip);
4706 ig.Emit (OpCodes.Ldloc, local_copy);
4707 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
4708 ig.MarkLabel (skip);
4709 ec.InFinally = old_in_finally;
4710 ig.EndExceptionBlock ();
4715 public override bool Resolve (EmitContext ec)
4717 if (expression_or_block is DictionaryEntry){
4718 expr = (Expression) ((DictionaryEntry) expression_or_block).Key;
4719 var_list = (ArrayList)((DictionaryEntry)expression_or_block).Value;
4721 if (!ResolveLocalVariableDecls (ec))
4724 } else if (expression_or_block is Expression){
4725 expr = (Expression) expression_or_block;
4727 expr = expr.Resolve (ec);
4731 expr_type = expr.Type;
4733 if (!ResolveExpression (ec))
4737 return Statement.Resolve (ec);
4740 protected override bool DoEmit (EmitContext ec)
4742 if (expression_or_block is DictionaryEntry)
4743 return EmitLocalVariableDecls (ec);
4744 else if (expression_or_block is Expression)
4745 return EmitExpression (ec);
4752 /// Implementation of the for each statement
4754 public class Foreach : Statement {
4756 LocalVariableReference variable;
4758 Statement statement;
4759 ForeachHelperMethods hm;
4760 Expression empty, conv;
4761 Type array_type, element_type;
4764 public Foreach (Expression type, LocalVariableReference var, Expression expr,
4765 Statement stmt, Location l)
4772 VariableInfo vi = var.VariableInfo;
4773 this.type = vi.Type;
4775 this.variable = var;
4781 public override bool Resolve (EmitContext ec)
4783 expr = expr.Resolve (ec);
4787 var_type = ec.DeclSpace.ResolveType (type, false, loc);
4788 if (var_type == null)
4792 // We need an instance variable. Not sure this is the best
4793 // way of doing this.
4795 // FIXME: When we implement propertyaccess, will those turn
4796 // out to return values in ExprClass? I think they should.
4798 if (!(expr.eclass == ExprClass.Variable || expr.eclass == ExprClass.Value ||
4799 expr.eclass == ExprClass.PropertyAccess || expr.eclass == ExprClass.IndexerAccess)){
4800 error1579 (expr.Type);
4804 if (expr.Type.IsArray) {
4805 array_type = expr.Type;
4806 element_type = array_type.GetElementType ();
4808 empty = new EmptyExpression (element_type);
4810 hm = ProbeCollectionType (ec, expr.Type);
4812 error1579 (expr.Type);
4816 array_type = expr.Type;
4817 element_type = hm.element_type;
4819 empty = new EmptyExpression (hm.element_type);
4822 ec.StartFlowBranching (FlowBranchingType.LOOP_BLOCK, loc);
4823 ec.CurrentBranching.CreateSibling ();
4827 // FIXME: maybe we can apply the same trick we do in the
4828 // array handling to avoid creating empty and conv in some cases.
4830 // Although it is not as important in this case, as the type
4831 // will not likely be object (what the enumerator will return).
4833 conv = Expression.ConvertExplicit (ec, empty, var_type, false, loc);
4837 if (variable.ResolveLValue (ec, empty) == null)
4840 if (!statement.Resolve (ec))
4843 //FlowReturns returns = ec.EndFlowBranching ();
4844 ec.EndFlowBranching ();
4849 // Retrieves a 'public bool MoveNext ()' method from the Type 't'
4851 static MethodInfo FetchMethodMoveNext (Type t)
4853 MemberList move_next_list;
4855 move_next_list = TypeContainer.FindMembers (
4856 t, MemberTypes.Method,
4857 BindingFlags.Public | BindingFlags.Instance,
4858 Type.FilterName, "MoveNext");
4859 if (move_next_list.Count == 0)
4862 foreach (MemberInfo m in move_next_list){
4863 MethodInfo mi = (MethodInfo) m;
4866 args = TypeManager.GetArgumentTypes (mi);
4867 if (args != null && args.Length == 0){
4868 if (mi.ReturnType == TypeManager.bool_type)
4876 // Retrieves a 'public T get_Current ()' method from the Type 't'
4878 static MethodInfo FetchMethodGetCurrent (Type t)
4880 MemberList move_next_list;
4882 move_next_list = TypeContainer.FindMembers (
4883 t, MemberTypes.Method,
4884 BindingFlags.Public | BindingFlags.Instance,
4885 Type.FilterName, "get_Current");
4886 if (move_next_list.Count == 0)
4889 foreach (MemberInfo m in move_next_list){
4890 MethodInfo mi = (MethodInfo) m;
4893 args = TypeManager.GetArgumentTypes (mi);
4894 if (args != null && args.Length == 0)
4901 // This struct records the helper methods used by the Foreach construct
4903 class ForeachHelperMethods {
4904 public EmitContext ec;
4905 public MethodInfo get_enumerator;
4906 public MethodInfo move_next;
4907 public MethodInfo get_current;
4908 public Type element_type;
4909 public Type enumerator_type;
4910 public bool is_disposable;
4912 public ForeachHelperMethods (EmitContext ec)
4915 this.element_type = TypeManager.object_type;
4916 this.enumerator_type = TypeManager.ienumerator_type;
4917 this.is_disposable = true;
4921 static bool GetEnumeratorFilter (MemberInfo m, object criteria)
4926 if (!(m is MethodInfo))
4929 if (m.Name != "GetEnumerator")
4932 MethodInfo mi = (MethodInfo) m;
4933 Type [] args = TypeManager.GetArgumentTypes (mi);
4935 if (args.Length != 0)
4938 ForeachHelperMethods hm = (ForeachHelperMethods) criteria;
4939 EmitContext ec = hm.ec;
4942 // Check whether GetEnumerator is accessible to us
4944 MethodAttributes prot = mi.Attributes & MethodAttributes.MemberAccessMask;
4946 Type declaring = mi.DeclaringType;
4947 if (prot == MethodAttributes.Private){
4948 if (declaring != ec.ContainerType)
4950 } else if (prot == MethodAttributes.FamANDAssem){
4951 // If from a different assembly, false
4952 if (!(mi is MethodBuilder))
4955 // Are we being invoked from the same class, or from a derived method?
4957 if (ec.ContainerType != declaring){
4958 if (!ec.ContainerType.IsSubclassOf (declaring))
4961 } else if (prot == MethodAttributes.FamORAssem){
4962 if (!(mi is MethodBuilder ||
4963 ec.ContainerType == declaring ||
4964 ec.ContainerType.IsSubclassOf (declaring)))
4966 } if (prot == MethodAttributes.Family){
4967 if (!(ec.ContainerType == declaring ||
4968 ec.ContainerType.IsSubclassOf (declaring)))
4973 // Ok, we can access it, now make sure that we can do something
4974 // with this 'GetEnumerator'
4977 if (mi.ReturnType == TypeManager.ienumerator_type ||
4978 TypeManager.ienumerator_type.IsAssignableFrom (mi.ReturnType) ||
4979 (!RootContext.StdLib && TypeManager.ImplementsInterface (mi.ReturnType, TypeManager.ienumerator_type))) {
4980 hm.move_next = TypeManager.bool_movenext_void;
4981 hm.get_current = TypeManager.object_getcurrent_void;
4986 // Ok, so they dont return an IEnumerable, we will have to
4987 // find if they support the GetEnumerator pattern.
4989 Type return_type = mi.ReturnType;
4991 hm.move_next = FetchMethodMoveNext (return_type);
4992 if (hm.move_next == null)
4994 hm.get_current = FetchMethodGetCurrent (return_type);
4995 if (hm.get_current == null)
4998 hm.element_type = hm.get_current.ReturnType;
4999 hm.enumerator_type = return_type;
5000 hm.is_disposable = TypeManager.ImplementsInterface (
5001 hm.enumerator_type, TypeManager.idisposable_type);
5007 /// This filter is used to find the GetEnumerator method
5008 /// on which IEnumerator operates
5010 static MemberFilter FilterEnumerator;
5014 FilterEnumerator = new MemberFilter (GetEnumeratorFilter);
5017 void error1579 (Type t)
5019 Report.Error (1579, loc,
5020 "foreach statement cannot operate on variables of type '" +
5021 t.FullName + "' because that class does not provide a " +
5022 " GetEnumerator method or it is inaccessible");
5025 static bool TryType (Type t, ForeachHelperMethods hm)
5029 mi = TypeContainer.FindMembers (t, MemberTypes.Method,
5030 BindingFlags.Public | BindingFlags.NonPublic |
5031 BindingFlags.Instance,
5032 FilterEnumerator, hm);
5037 hm.get_enumerator = (MethodInfo) mi [0];
5042 // Looks for a usable GetEnumerator in the Type, and if found returns
5043 // the three methods that participate: GetEnumerator, MoveNext and get_Current
5045 ForeachHelperMethods ProbeCollectionType (EmitContext ec, Type t)
5047 ForeachHelperMethods hm = new ForeachHelperMethods (ec);
5049 if (TryType (t, hm))
5053 // Now try to find the method in the interfaces
5056 Type [] ifaces = t.GetInterfaces ();
5058 foreach (Type i in ifaces){
5059 if (TryType (i, hm))
5064 // Since TypeBuilder.GetInterfaces only returns the interface
5065 // types for this type, we have to keep looping, but once
5066 // we hit a non-TypeBuilder (ie, a Type), then we know we are
5067 // done, because it returns all the types
5069 if ((t is TypeBuilder))
5079 // FIXME: possible optimization.
5080 // We might be able to avoid creating 'empty' if the type is the sam
5082 bool EmitCollectionForeach (EmitContext ec)
5084 ILGenerator ig = ec.ig;
5085 LocalBuilder enumerator, disposable;
5087 enumerator = ig.DeclareLocal (hm.enumerator_type);
5088 if (hm.is_disposable)
5089 disposable = ig.DeclareLocal (TypeManager.idisposable_type);
5094 // Instantiate the enumerator
5096 if (expr.Type.IsValueType){
5097 if (expr is IMemoryLocation){
5098 IMemoryLocation ml = (IMemoryLocation) expr;
5100 ml.AddressOf (ec, AddressOp.Load);
5102 throw new Exception ("Expr " + expr + " of type " + expr.Type +
5103 " does not implement IMemoryLocation");
5104 ig.Emit (OpCodes.Call, hm.get_enumerator);
5107 ig.Emit (OpCodes.Callvirt, hm.get_enumerator);
5109 ig.Emit (OpCodes.Stloc, enumerator);
5112 // Protect the code in a try/finalize block, so that
5113 // if the beast implement IDisposable, we get rid of it
5115 bool old_in_try = ec.InTry;
5117 if (hm.is_disposable) {
5118 ig.BeginExceptionBlock ();
5122 Label end_try = ig.DefineLabel ();
5124 ig.MarkLabel (ec.LoopBegin);
5125 ig.Emit (OpCodes.Ldloc, enumerator);
5126 ig.Emit (OpCodes.Callvirt, hm.move_next);
5127 ig.Emit (OpCodes.Brfalse, end_try);
5128 ig.Emit (OpCodes.Ldloc, enumerator);
5129 ig.Emit (OpCodes.Callvirt, hm.get_current);
5130 variable.EmitAssign (ec, conv);
5131 statement.Emit (ec);
5132 ig.Emit (OpCodes.Br, ec.LoopBegin);
5133 ig.MarkLabel (end_try);
5134 ec.InTry = old_in_try;
5136 // The runtime provides this for us.
5137 // ig.Emit (OpCodes.Leave, end);
5140 // Now the finally block
5142 if (hm.is_disposable) {
5143 Label end_finally = ig.DefineLabel ();
5144 bool old_in_finally = ec.InFinally;
5145 ec.InFinally = true;
5146 ig.BeginFinallyBlock ();
5148 ig.Emit (OpCodes.Ldloc, enumerator);
5149 ig.Emit (OpCodes.Isinst, TypeManager.idisposable_type);
5150 ig.Emit (OpCodes.Stloc, disposable);
5151 ig.Emit (OpCodes.Ldloc, disposable);
5152 ig.Emit (OpCodes.Brfalse, end_finally);
5153 ig.Emit (OpCodes.Ldloc, disposable);
5154 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
5155 ig.MarkLabel (end_finally);
5156 ec.InFinally = old_in_finally;
5158 // The runtime generates this anyways.
5159 // ig.Emit (OpCodes.Endfinally);
5161 ig.EndExceptionBlock ();
5164 ig.MarkLabel (ec.LoopEnd);
5169 // FIXME: possible optimization.
5170 // We might be able to avoid creating 'empty' if the type is the sam
5172 bool EmitArrayForeach (EmitContext ec)
5174 int rank = array_type.GetArrayRank ();
5175 ILGenerator ig = ec.ig;
5177 LocalBuilder copy = ig.DeclareLocal (array_type);
5180 // Make our copy of the array
5183 ig.Emit (OpCodes.Stloc, copy);
5186 LocalBuilder counter = ig.DeclareLocal (TypeManager.int32_type);
5190 ig.Emit (OpCodes.Ldc_I4_0);
5191 ig.Emit (OpCodes.Stloc, counter);
5192 test = ig.DefineLabel ();
5193 ig.Emit (OpCodes.Br, test);
5195 loop = ig.DefineLabel ();
5196 ig.MarkLabel (loop);
5198 ig.Emit (OpCodes.Ldloc, copy);
5199 ig.Emit (OpCodes.Ldloc, counter);
5200 ArrayAccess.EmitLoadOpcode (ig, var_type);
5202 variable.EmitAssign (ec, conv);
5204 statement.Emit (ec);
5206 ig.MarkLabel (ec.LoopBegin);
5207 ig.Emit (OpCodes.Ldloc, counter);
5208 ig.Emit (OpCodes.Ldc_I4_1);
5209 ig.Emit (OpCodes.Add);
5210 ig.Emit (OpCodes.Stloc, counter);
5212 ig.MarkLabel (test);
5213 ig.Emit (OpCodes.Ldloc, counter);
5214 ig.Emit (OpCodes.Ldloc, copy);
5215 ig.Emit (OpCodes.Ldlen);
5216 ig.Emit (OpCodes.Conv_I4);
5217 ig.Emit (OpCodes.Blt, loop);
5219 LocalBuilder [] dim_len = new LocalBuilder [rank];
5220 LocalBuilder [] dim_count = new LocalBuilder [rank];
5221 Label [] loop = new Label [rank];
5222 Label [] test = new Label [rank];
5225 for (dim = 0; dim < rank; dim++){
5226 dim_len [dim] = ig.DeclareLocal (TypeManager.int32_type);
5227 dim_count [dim] = ig.DeclareLocal (TypeManager.int32_type);
5228 test [dim] = ig.DefineLabel ();
5229 loop [dim] = ig.DefineLabel ();
5232 for (dim = 0; dim < rank; dim++){
5233 ig.Emit (OpCodes.Ldloc, copy);
5234 IntLiteral.EmitInt (ig, dim);
5235 ig.Emit (OpCodes.Callvirt, TypeManager.int_getlength_int);
5236 ig.Emit (OpCodes.Stloc, dim_len [dim]);
5239 for (dim = 0; dim < rank; dim++){
5240 ig.Emit (OpCodes.Ldc_I4_0);
5241 ig.Emit (OpCodes.Stloc, dim_count [dim]);
5242 ig.Emit (OpCodes.Br, test [dim]);
5243 ig.MarkLabel (loop [dim]);
5246 ig.Emit (OpCodes.Ldloc, copy);
5247 for (dim = 0; dim < rank; dim++)
5248 ig.Emit (OpCodes.Ldloc, dim_count [dim]);
5251 // FIXME: Maybe we can cache the computation of 'get'?
5253 Type [] args = new Type [rank];
5256 for (int i = 0; i < rank; i++)
5257 args [i] = TypeManager.int32_type;
5259 ModuleBuilder mb = CodeGen.ModuleBuilder;
5260 get = mb.GetArrayMethod (
5262 CallingConventions.HasThis| CallingConventions.Standard,
5264 ig.Emit (OpCodes.Call, get);
5265 variable.EmitAssign (ec, conv);
5266 statement.Emit (ec);
5267 ig.MarkLabel (ec.LoopBegin);
5268 for (dim = rank - 1; dim >= 0; dim--){
5269 ig.Emit (OpCodes.Ldloc, dim_count [dim]);
5270 ig.Emit (OpCodes.Ldc_I4_1);
5271 ig.Emit (OpCodes.Add);
5272 ig.Emit (OpCodes.Stloc, dim_count [dim]);
5274 ig.MarkLabel (test [dim]);
5275 ig.Emit (OpCodes.Ldloc, dim_count [dim]);
5276 ig.Emit (OpCodes.Ldloc, dim_len [dim]);
5277 ig.Emit (OpCodes.Blt, loop [dim]);
5280 ig.MarkLabel (ec.LoopEnd);
5285 protected override bool DoEmit (EmitContext ec)
5289 ILGenerator ig = ec.ig;
5291 Label old_begin = ec.LoopBegin, old_end = ec.LoopEnd;
5292 bool old_inloop = ec.InLoop;
5293 int old_loop_begin_try_catch_level = ec.LoopBeginTryCatchLevel;
5294 ec.LoopBegin = ig.DefineLabel ();
5295 ec.LoopEnd = ig.DefineLabel ();
5297 ec.LoopBeginTryCatchLevel = ec.TryCatchLevel;
5300 ret_val = EmitCollectionForeach (ec);
5302 ret_val = EmitArrayForeach (ec);
5304 ec.LoopBegin = old_begin;
5305 ec.LoopEnd = old_end;
5306 ec.InLoop = old_inloop;
5307 ec.LoopBeginTryCatchLevel = old_loop_begin_try_catch_level;
5314 /// AddHandler statement
5316 public class AddHandler : Statement {
5318 Expression EvtHandler;
5321 // keeps track whether EvtId is already resolved
5325 public AddHandler (Expression evt_id, Expression evt_handler, Location l)
5328 EvtHandler = Parser.SetAddressOf (evt_handler);
5331 //Console.WriteLine ("Adding handler '" + evt_handler + "' for Event '" + evt_id +"'");
5334 public override bool Resolve (EmitContext ec)
5337 // if EvetId is of EventExpr type that means
5338 // this is already resolved
5340 if (EvtId is EventExpr) {
5345 EvtId = EvtId.Resolve(ec);
5346 EvtHandler = EvtHandler.Resolve(ec,ResolveFlags.MethodGroup);
5347 if (EvtId == null || (!(EvtId is EventExpr))) {
5348 Report.Error (30676, "Need an event designator.");
5352 if (EvtHandler == null)
5354 Report.Error (999, "'AddHandler' statement needs an event handler.");
5361 protected override bool DoEmit (EmitContext ec)
5364 // Already resolved and emitted don't do anything
5370 ArrayList args = new ArrayList();
5371 Argument arg = new Argument (EvtHandler, Argument.AType.Expression);
5376 // The even type was already resolved to a delegate, so
5377 // we must un-resolve its name to generate a type expression
5378 string ts = (EvtId.Type.ToString()).Replace ('+','.');
5379 Expression dtype = Mono.MonoBASIC.Parser.DecomposeQI (ts, Location.Null);
5381 // which we can use to declare a new event handler
5383 d = new New (dtype, args, Location.Null);
5385 e = new CompoundAssign(Binary.Operator.Addition, EvtId, d, Location.Null);
5387 // we resolve it all and emit the code
5400 /// RemoveHandler statement
5402 public class RemoveHandler : Statement
\r
5405 Expression EvtHandler;
5407 public RemoveHandler (Expression evt_id, Expression evt_handler, Location l)
5410 EvtHandler = Parser.SetAddressOf (evt_handler);
5414 public override bool Resolve (EmitContext ec)
5416 EvtId = EvtId.Resolve(ec);
5417 EvtHandler = EvtHandler.Resolve(ec,ResolveFlags.MethodGroup);
5418 if (EvtId == null || (!(EvtId is EventExpr)))
\r
5420 Report.Error (30676, "Need an event designator.");
5424 if (EvtHandler == null)
5426 Report.Error (999, "'AddHandler' statement needs an event handler.");
5432 protected override bool DoEmit (EmitContext ec)
5435 ArrayList args = new ArrayList();
5436 Argument arg = new Argument (EvtHandler, Argument.AType.Expression);
5439 // The even type was already resolved to a delegate, so
5440 // we must un-resolve its name to generate a type expression
5441 string ts = (EvtId.Type.ToString()).Replace ('+','.');
5442 Expression dtype = Mono.MonoBASIC.Parser.DecomposeQI (ts, Location.Null);
5444 // which we can use to declare a new event handler
5446 d = new New (dtype, args, Location.Null);
5449 e = new CompoundAssign(Binary.Operator.Subtraction, EvtId, d, Location.Null);
5451 // we resolve it all and emit the code
5463 public class RedimClause {
5464 private Expression RedimTarget;
5465 private ArrayList NewIndexes;
5466 private Expression AsType;
5468 private LocalTemporary localTmp = null;
5469 private Expression origRedimTarget = null;
5470 private StatementExpression ReDimExpr;
5472 public RedimClause (Expression e, ArrayList args, Expression e_as)
5474 if (e is SimpleName)
5475 ((SimpleName) e).IsInvocation = false;
5476 if (e is MemberAccess)
5477 ((MemberAccess) e).IsInvocation = false;
5484 public bool Resolve (EmitContext ec, bool Preserve, Location loc)
5486 RedimTarget = RedimTarget.Resolve (ec);
5488 if (AsType != null) {
5489 Report.Error (30811, loc, "'ReDim' statements can no longer be used to declare array variables");
5493 if (!RedimTarget.Type.IsArray) {
5494 Report.Error (49, loc, "'ReDim' statement requires an array");
5498 ArrayList args = new ArrayList();
5499 foreach (Argument a in NewIndexes) {
5500 if (a.Resolve(ec, loc))
5504 for (int x = 0; x < args.Count; x++) {
5505 args[x] = new Binary (Binary.Operator.Addition,
5506 (Expression) args[x], new IntLiteral (1), Location.Null);
5510 if (RedimTarget.Type.GetArrayRank() != NewIndexes.Count) {
5511 Report.Error (30415, loc, "'ReDim' cannot change the number of dimensions of an array.");
5515 Type BaseType = RedimTarget.Type.GetElementType();
5516 Expression BaseTypeExpr = MonoBASIC.Parser.DecomposeQI(BaseType.FullName.ToString(), Location.Null);
5517 ArrayCreation acExpr = new ArrayCreation (BaseTypeExpr, NewIndexes, "", null, Location.Null);
5520 ExpressionStatement PreserveExpr = null;
5521 if (RedimTarget is PropertyGroupExpr) {
5522 localTmp = new LocalTemporary (ec, RedimTarget.Type);
5523 PropertyGroupExpr pe = RedimTarget as PropertyGroupExpr;
5524 origRedimTarget = new PropertyGroupExpr (pe.Properties, pe.Arguments, pe.InstanceExpression, loc);
5525 if ((origRedimTarget = origRedimTarget.Resolve (ec)) == null) {
5526 Report.Error (-1, loc, "'ReDim' vs PropertyGroup");
5529 PreserveExpr = (ExpressionStatement) new Preserve(localTmp, acExpr, loc);
5531 PreserveExpr = (ExpressionStatement) new Preserve(RedimTarget, acExpr, loc);
5532 ReDimExpr = (StatementExpression) new StatementExpression ((ExpressionStatement) new Assign (RedimTarget, PreserveExpr, loc), loc);
5535 ReDimExpr = (StatementExpression) new StatementExpression ((ExpressionStatement) new Assign (RedimTarget, acExpr, loc), loc);
5536 ReDimExpr.Resolve(ec);
5540 public void DoEmit (EmitContext ec)
5542 if (ReDimExpr == null)
5545 if (localTmp != null && origRedimTarget != null) {
5546 origRedimTarget.Emit (ec);
5547 localTmp.Store (ec);
5554 public class ReDim : Statement {
5555 ArrayList RedimTargets;
5558 public ReDim (ArrayList targets, bool opt_preserve, Location l)
5561 RedimTargets = targets;
5562 Preserve = opt_preserve;
5565 public override bool Resolve (EmitContext ec)
5568 foreach (RedimClause rc in RedimTargets)
5569 result = rc.Resolve(ec, Preserve, loc) && result;
5573 protected override bool DoEmit (EmitContext ec)
5575 foreach (RedimClause rc in RedimTargets)
5582 public class Erase : Statement {
5583 Expression EraseTarget;
5585 private StatementExpression EraseExpr;
5587 public Erase (Expression expr, Location l)
5593 public override bool Resolve (EmitContext ec)
5595 EraseTarget = EraseTarget.Resolve (ec);
5596 if (!EraseTarget.Type.IsArray)
5597 Report.Error (49, "'Erase' statement requires an array");
5599 EraseExpr = (StatementExpression) new StatementExpression ((ExpressionStatement) new Assign (EraseTarget, NullLiteral.Null, loc), loc);
5600 EraseExpr.Resolve(ec);
5605 protected override bool DoEmit (EmitContext ec)