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;
2682 FieldBase FieldAlias;
2683 public readonly string Name;
2684 public readonly Location Location;
2685 public readonly int Block;
2690 public bool Assigned;
2691 public bool ReadOnly;
2693 public VariableInfo (Expression type, string name, int block, Location l, string Alias)
2694 : this (type, name, block, l)
2699 public VariableInfo (Expression type, string name, int block, Location l)
2704 LocalBuilder = null;
2708 public VariableInfo (TypeContainer tc, int block, Location l, string Alias)
2709 : this (tc, block, l)
2714 public VariableInfo (TypeContainer tc, int block, Location l)
2716 VariableType = tc.TypeBuilder;
2717 struct_info = MyStructInfo.GetStructInfo (tc);
2719 LocalBuilder = null;
2723 MyStructInfo struct_info;
2724 public MyStructInfo StructInfo {
2730 public bool IsAssigned (EmitContext ec, Location loc)
2731 {/* FIXME: we shouldn't just skip this!!!
2732 if (!ec.DoFlowAnalysis || ec.CurrentBranching.IsVariableAssigned (this))
2735 MyStructInfo struct_info = StructInfo;
2736 if ((struct_info == null) || (struct_info.HasNonPublicFields && (Name != null))) {
2737 Report.Error (165, loc, "Use of unassigned local variable '" + Name + "'");
2738 ec.CurrentBranching.SetVariableAssigned (this);
2742 int count = struct_info.Count;
2744 for (int i = 0; i < count; i++) {
2745 if (!ec.CurrentBranching.IsVariableAssigned (this, i+1)) {
2747 Report.Error (165, loc,
2748 "Use of unassigned local variable '" +
2750 ec.CurrentBranching.SetVariableAssigned (this);
2754 FieldInfo field = struct_info [i];
2755 Report.Error (171, loc,
2756 "Field '" + TypeManager.MonoBASIC_Name (VariableType) +
2757 "." + field.Name + "' must be fully initialized " +
2758 "before control leaves the constructor");
2766 public bool IsFieldAssigned (EmitContext ec, string name, Location loc)
2768 if (!ec.DoFlowAnalysis || ec.CurrentBranching.IsVariableAssigned (this) ||
2769 (struct_info == null))
2772 int field_idx = StructInfo [name];
2776 if (!ec.CurrentBranching.IsVariableAssigned (this, field_idx)) {
2777 Report.Error (170, loc,
2778 "Use of possibly unassigned field '" + name + "'");
2779 ec.CurrentBranching.SetVariableAssigned (this, field_idx);
2786 public void SetAssigned (EmitContext ec)
2788 if (ec.DoFlowAnalysis)
2789 ec.CurrentBranching.SetVariableAssigned (this);
2792 public void SetFieldAssigned (EmitContext ec, string name)
2794 if (ec.DoFlowAnalysis && (struct_info != null))
2795 ec.CurrentBranching.SetVariableAssigned (this, StructInfo [name]);
2798 public FieldBase GetFieldAlias (EmitContext ec) {
2799 if ( this.FieldAlias != null )
2800 return this.FieldAlias;
2803 ArrayList fields = ec.TypeContainer.Fields;
2804 for (int i = 0; i < fields.Count; i++)
2806 if (((Field) fields[i]).Name == this.Alias)
2808 this.FieldAlias = (Field) fields[i];
2812 return this.FieldAlias;
2816 public bool Resolve (DeclSpace decl)
2818 if (struct_info != null)
2821 if (VariableType == null)
2822 VariableType = decl.ResolveType (Type, false, Location);
2824 if (VariableType == null)
2827 struct_info = MyStructInfo.GetStructInfo (VariableType);
2832 public void MakePinned ()
2834 TypeManager.MakePinned (LocalBuilder);
2837 public override string ToString ()
2839 return "VariableInfo (" + Number + "," + Type + "," + Location + ")";
2844 public class StatementSequence : Expression {
2846 ArrayList args, originalArgs;
2848 bool isRetValRequired;
2849 bool isLeftHandSide;
2850 bool isIndexerAccess;
2852 Expression type_expr;
2853 bool is_resolved = false;
2855 public StatementSequence (Block parent, Location loc, Expression expr)
2856 : this (parent, loc, expr, null)
2859 public StatementSequence (Block parent, Location loc, Expression expr, string name,
2860 Expression type_expr, ArrayList a, bool isRetValRequired,
2861 bool isLeftHandSide)
2862 : this (parent, loc, expr, a)
2864 this.memberName = name;
2865 this.type_expr = type_expr;
2866 this.isRetValRequired = isRetValRequired;
2867 this.isLeftHandSide = isLeftHandSide;
2870 public StatementSequence (Block parent, Location loc, Expression expr, ArrayList a,
2871 bool isRetValRequired, bool isLeftHandSide)
2872 : this (parent, loc, expr, a)
2874 this.isRetValRequired = isRetValRequired;
2875 this.isLeftHandSide = isLeftHandSide;
2876 if (expr is MemberAccess) {
2877 this.expr = ((MemberAccess)expr).Expr;
2878 this.memberName = ((MemberAccess)expr).Identifier;
2879 this.isIndexerAccess = false;
2880 } else if (expr is IndexerAccess) {
2881 this.expr = ((IndexerAccess) expr).Instance;
2882 this.memberName = "";
2883 this.isIndexerAccess = true;
2887 public StatementSequence (Block parent, Location loc, Expression expr, ArrayList a)
2889 stmtBlock = new Block (parent);
2891 originalArgs = new ArrayList ();
2893 for (int index = 0; index < a.Count; index ++) {
2894 Argument argument = (Argument) args [index];
2895 originalArgs.Add (new Argument (argument.Expr, argument.ArgType));
2900 stmtBlock.IsLateBindingRequired = true;
2902 this.isRetValRequired = this.isLeftHandSide = false;
2903 this.memberName = "";
2904 this.type_expr = null;
2907 public ArrayList Arguments {
2916 public bool IsLeftHandSide {
2918 isLeftHandSide = value;
2922 public Block StmtBlock {
2928 public override Expression DoResolve (EmitContext ec)
2932 if (!stmtBlock.Resolve (ec))
2934 eclass = ExprClass.Value;
2935 type = TypeManager.object_type;
2940 public bool ResolveArguments (EmitContext ec) {
2942 bool argNamesFound = false;
2943 if (Arguments != null)
2945 for (int index = 0; index < Arguments.Count; index ++)
2947 Argument a = (Argument) Arguments [index];
2948 if (a.ParamName == null || a.ParamName == "") {
2949 if (argNamesFound) {
2950 Report.Error (30241, loc, "Named Argument expected");
2954 argNamesFound = true;
2955 if (a.ArgType == Argument.AType.NoArg)
2956 a = new Argument (Parser.DecomposeQI ("System.Reflection.Missing.Value", loc), Argument.AType.Expression);
2957 if (!a.Resolve (ec, loc))
2959 Arguments [index] = a;
2965 public void GenerateLateBindingStatements ()
2968 ArrayList arrayInitializers = new ArrayList ();
2969 ArrayList ArgumentNames = null;
2971 //arrayInitializers = new ArrayList ();
2972 argCount = args.Count;
2973 for (int index = 0; index < args.Count; index ++) {
2974 Argument a = (Argument) args [index];
2975 Expression argument = a.Expr;
2976 arrayInitializers.Add (argument);
2977 if (a.ParamName != null && a.ParamName != "") {
2978 if (ArgumentNames == null)
2979 ArgumentNames = new ArrayList ();
2980 ArgumentNames.Add (new StringLiteral (a.ParamName));
2985 // __LateBindingArgs = new Object () {arg1, arg2 ...}
2986 ArrayCreation new_expr = new ArrayCreation (Parser.DecomposeQI ("System.Object", loc), "[]", arrayInitializers, loc);
2987 Assign assign_stmt = null;
2989 LocalVariableReference v1 = new LocalVariableReference (stmtBlock, Block.lateBindingArgs, loc);
2990 assign_stmt = new Assign (v1, new_expr, loc);
2991 stmtBlock.AddStatement (new StatementExpression ((ExpressionStatement) assign_stmt, loc));
2992 // __LateBindingArgNames = new string () { argument names}
2993 LocalVariableReference v2 = null;
2994 if (ArgumentNames != null && ArgumentNames.Count > 0) {
2995 new_expr = new ArrayCreation (Parser.DecomposeQI ("System.String", loc), "[]", ArgumentNames, loc);
2996 v2 = new LocalVariableReference (stmtBlock, Block.lateBindingArgNames, loc);
2997 assign_stmt = new Assign (v2, new_expr, loc);
2998 stmtBlock.AddStatement (new StatementExpression ((ExpressionStatement) assign_stmt, loc));
3001 //string memName = "";
3002 //bool isIndexerAccess = true;
3004 ArrayList invocationArgs = new ArrayList ();
3005 if (isIndexerAccess || memberName == "") {
3006 invocationArgs.Add (new Argument (expr, Argument.AType.Expression));
3007 invocationArgs.Add (new Argument (v1, Argument.AType.Expression));
3008 invocationArgs.Add (new Argument (NullLiteral.Null, Argument.AType.Expression));
3009 Expression tmp = null;
3010 if (!isLeftHandSide)
3011 tmp = Parser.DecomposeQI ("Microsoft.VisualBasic.CompilerServices.LateBinding.LateIndexGet", loc);
3013 tmp = Parser.DecomposeQI ("Microsoft.VisualBasic.CompilerServices.LateBinding.LateIndexSet", loc);
3014 Invocation invStmt = new Invocation (tmp, invocationArgs, Location.Null);
3015 invStmt.IsLateBinding = true;
3016 stmtBlock.AddStatement (new StatementExpression ((ExpressionStatement) invStmt, loc));
3021 invocationArgs.Add (new Argument (expr, Argument.AType.Expression));
3023 invocationArgs.Add (new Argument (NullLiteral.Null, Argument.AType.Expression));
3024 if (type_expr != null)
3025 invocationArgs.Add (new Argument (type_expr, Argument.AType.Expression));
3027 invocationArgs.Add (new Argument (NullLiteral.Null, Argument.AType.Expression));
3028 invocationArgs.Add (new Argument (new StringLiteral (memberName), Argument.AType.Expression));
3029 invocationArgs.Add (new Argument (v1, Argument.AType.Expression));
3030 if (ArgumentNames != null && ArgumentNames.Count > 0)
3031 invocationArgs.Add (new Argument (v2, Argument.AType.Expression));
3033 invocationArgs.Add (new Argument (NullLiteral.Null, Argument.AType.Expression));
3035 // __LateBindingCopyBack = new Boolean (no_of_args) {}
3036 bool isCopyBackRequired = false;
3037 if (!isLeftHandSide) {
3038 for (int i = 0; i < argCount; i++) {
3039 Argument origArg = (Argument) Arguments [i];
3040 Expression origExpr = origArg.Expr;
3041 if (!(origExpr is Constant || origArg.ArgType == Argument.AType.NoArg))
3042 isCopyBackRequired = true;
3046 LocalVariableReference v3 = new LocalVariableReference (stmtBlock, Block.lateBindingCopyBack, loc);
3047 if (isCopyBackRequired) {
3048 ArrayList rank_specifier = new ArrayList ();
3049 rank_specifier.Add (new IntLiteral (argCount));
3050 arrayInitializers = new ArrayList ();
3051 for (int i = 0; i < argCount; i++) {
3052 Argument a = (Argument) Arguments [i];
3053 Expression origExpr = a.Expr;
3054 if (origExpr is Constant || a.ArgType == Argument.AType.NoArg || origExpr is New)
3055 arrayInitializers.Add (new BoolLiteral (false));
3057 arrayInitializers.Add (new BoolLiteral (true));
3060 new_expr = new ArrayCreation (Parser.DecomposeQI ("System.Boolean", loc), "[]", arrayInitializers, loc);
3061 assign_stmt = new Assign (v3, new_expr, loc);
3062 stmtBlock.AddStatement (new StatementExpression ((ExpressionStatement) assign_stmt, loc));
3063 invocationArgs.Add (new Argument (v3, Argument.AType.Expression));
3064 } else if (! isLeftHandSide) {
3065 invocationArgs.Add (new Argument (NullLiteral.Null, Argument.AType.Expression));
3068 Expression etmp = null;
3069 if (isLeftHandSide) {
3071 etmp = Parser.DecomposeQI ("Microsoft.VisualBasic.CompilerServices.LateBinding.LateSet", loc);
3072 } else if (isRetValRequired) {
3074 etmp = Parser.DecomposeQI ("Microsoft.VisualBasic.CompilerServices.LateBinding.LateGet", loc);
3076 etmp = Parser.DecomposeQI ("Microsoft.VisualBasic.CompilerServices.LateBinding.LateCall", loc);
3079 Invocation inv_stmt = new Invocation (etmp, invocationArgs, Location.Null);
3080 inv_stmt.IsLateBinding = true;
3081 stmtBlock.AddStatement (new StatementExpression ((ExpressionStatement) inv_stmt, loc));
3083 if (! isCopyBackRequired)
3086 for (int i = argCount - 1; i >= 0; i --) {
3087 Argument arg = (Argument) originalArgs [i];
3088 Expression origExpr = (Expression) arg.Expr;
3089 if (arg.ArgType == Argument.AType.NoArg)
3091 if (origExpr is Constant)
3093 if (origExpr is New)
3096 Expression intExpr = new IntLiteral (i);
3097 ArrayList argsLocal = new ArrayList ();
3098 argsLocal.Add (new Argument (intExpr, Argument.AType.Expression));
3099 Expression indexExpr = new Invocation (new SimpleName (Block.lateBindingCopyBack, loc), argsLocal, loc);
3100 Expression value = new Invocation (new SimpleName (Block.lateBindingArgs, loc), argsLocal, loc);
3101 assign_stmt = new Assign (origExpr, value, loc);
3102 Expression boolExpr = new Binary (Binary.Operator.Inequality, indexExpr, new BoolLiteral (false), loc);
3103 Statement ifStmt = new If (boolExpr, new StatementExpression ((ExpressionStatement) assign_stmt, loc), loc);
3104 stmtBlock.AddStatement (ifStmt);
3108 public override void Emit (EmitContext ec)
3110 stmtBlock.Emit (ec);
3114 public class SwitchLabel {
3115 public enum LabelType : byte {
3116 Operator, Range, Label, Else
3119 Expression label, start, end;
3120 LabelType label_type;
3121 Expression label_condition, start_condition, end_condition;
3122 Binary.Operator oper;
3123 public Location loc;
3124 public Label ILLabel;
3125 public Label ILLabelCode;
3128 // if expr == null, then it is the default case.
3130 public SwitchLabel (Expression start, Expression end, LabelType ltype, Binary.Operator oper, Location l) {
3133 this.label_type = ltype;
3136 label_condition = start_condition = end_condition = null;
3139 public SwitchLabel (Expression expr, LabelType ltype, Binary.Operator oper, Location l)
3143 label_condition = start_condition = end_condition = null;
3145 this.label_type = ltype;
3149 public Expression Label {
3155 public LabelType Type {
3161 public Expression ConditionStart {
3163 return start_condition;
3167 public Expression ConditionEnd {
3169 return end_condition;
3173 public Expression ConditionLabel {
3175 return label_condition;
3180 // Resolves the expression, reduces it to a literal if possible
3181 // and then converts it to the requested type.
3183 public bool ResolveAndReduce (EmitContext ec, Expression expr)
3185 ILLabel = ec.ig.DefineLabel ();
3186 ILLabelCode = ec.ig.DefineLabel ();
3188 Expression e = null;
3189 switch (label_type) {
3190 case LabelType.Label :
3193 e = label.Resolve (ec);
3195 e = Expression.ConvertImplicit (ec, e, expr.Type, loc);
3198 label_condition = new Binary (Binary.Operator.Equality, expr, e, loc);
3199 if ((label_condition = label_condition.DoResolve (ec)) == null)
3202 case LabelType.Operator :
3203 e = label.Resolve (ec);
3204 label_condition = new Binary (oper, expr, e, loc);
3205 if ((label_condition = label_condition.DoResolve (ec)) == null)
3208 case LabelType.Range :
3209 if (start == null || end == null)
3211 e = start.Resolve (ec);
3213 e = Expression.ConvertImplicit (ec, e, expr.Type, loc);
3216 start_condition = new Binary (Binary.Operator.GreaterThanOrEqual, expr, e, loc);
3217 start_condition = start_condition.Resolve (ec);
3218 e = end.Resolve (ec);
3220 e = Expression.ConvertImplicit (ec, e, expr.Type, loc);
3223 end_condition = new Binary (Binary.Operator.LessThanOrEqual, expr, e, loc);
3224 end_condition = end_condition.Resolve (ec);
3225 if (start_condition == null || end_condition == null)
3229 case LabelType.Else :
3236 public class SwitchSection {
3237 // An array of SwitchLabels.
3238 public readonly ArrayList Labels;
3239 public readonly Block Block;
3241 public SwitchSection (ArrayList labels, Block block)
3248 public class Switch : Statement {
3249 public readonly ArrayList Sections;
3250 public Expression Expr;
3253 /// Maps constants whose type type SwitchType to their SwitchLabels.
3255 public Hashtable Elements;
3258 /// The governing switch type
3260 public Type SwitchType;
3266 Label default_target;
3267 Expression new_expr;
3270 // The types allowed to be implicitly cast from
3271 // on the governing type
3273 //static Type [] allowed_types;
3275 public Switch (Expression e, ArrayList sects, Location l)
3282 public bool GotDefault {
3288 public Label DefaultTarget {
3290 return default_target;
3295 // Determines the governing type for a switch. The returned
3296 // expression might be the expression from the switch, or an
3297 // expression that includes any potential conversions to the
3298 // integral types or to string.
3300 Expression SwitchGoverningType (EmitContext ec, Type t)
3302 if (t == TypeManager.byte_type ||
3303 t == TypeManager.short_type ||
3304 t == TypeManager.int32_type ||
3305 t == TypeManager.int64_type ||
3306 t == TypeManager.decimal_type ||
3307 t == TypeManager.float_type ||
3308 t == TypeManager.double_type ||
3309 t == TypeManager.date_type ||
3310 t == TypeManager.char_type ||
3311 t == TypeManager.object_type ||
3312 t == TypeManager.string_type ||
3313 t == TypeManager.bool_type ||
3314 t.IsSubclassOf (TypeManager.enum_type))
3317 if (allowed_types == null){
3318 allowed_types = new Type [] {
3319 TypeManager.sbyte_type,
3320 TypeManager.byte_type,
3321 TypeManager.short_type,
3322 TypeManager.ushort_type,
3323 TypeManager.int32_type,
3324 TypeManager.uint32_type,
3325 TypeManager.int64_type,
3326 TypeManager.uint64_type,
3327 TypeManager.char_type,
3328 TypeManager.bool_type,
3329 TypeManager.string_type
3334 // Try to find a *user* defined implicit conversion.
3336 // If there is no implicit conversion, or if there are multiple
3337 // conversions, we have to report an error
3339 Expression converted = null;
3340 foreach (Type tt in allowed_types){
3343 e = Expression.ImplicitUserConversion (ec, Expr, tt, loc);
3347 if (converted != null){
3348 Report.Error (-12, loc, "More than one conversion to an integral " +
3349 " type exists for type '" +
3350 TypeManager.MonoBASIC_Name (Expr.Type)+"'");
3360 void error152 (string n)
3363 152, "The label '" + n + ":' " +
3364 "is already present on this switch statement");
3368 // Performs the basic sanity checks on the switch statement
3369 // (looks for duplicate keys and non-constant expressions).
3371 // It also returns a hashtable with the keys that we will later
3372 // use to compute the switch tables
3374 bool CheckSwitch (EmitContext ec)
3376 //Type compare_type;
3378 Elements = new CaseInsensitiveHashtable ();
3380 got_default = false;
3383 if (TypeManager.IsEnumType (SwitchType)){
3384 compare_type = TypeManager.EnumToUnderlying (SwitchType);
3386 compare_type = SwitchType;
3389 for (int secIndex = 0; secIndex < Sections.Count; secIndex ++) {
3390 SwitchSection ss = (SwitchSection) Sections [secIndex];
3391 for (int labelIndex = 0; labelIndex < ss.Labels.Count; labelIndex ++) {
3392 SwitchLabel sl = (SwitchLabel) ss.Labels [labelIndex];
3393 if (!sl.ResolveAndReduce (ec, Expr)){
3398 if (sl.Type == SwitchLabel.LabelType.Else){
3400 error152 ("default");
3414 void EmitObjectInteger (ILGenerator ig, object k)
3417 IntConstant.EmitInt (ig, (int) k);
3418 else if (k is Constant) {
3419 EmitObjectInteger (ig, ((Constant) k).GetValue ());
3422 IntConstant.EmitInt (ig, unchecked ((int) (uint) k));
3425 if ((long) k >= int.MinValue && (long) k <= int.MaxValue)
3427 IntConstant.EmitInt (ig, (int) (long) k);
3428 ig.Emit (OpCodes.Conv_I8);
3431 LongConstant.EmitLong (ig, (long) k);
3433 else if (k is ulong)
3435 if ((ulong) k < (1L<<32))
3437 IntConstant.EmitInt (ig, (int) (long) k);
3438 ig.Emit (OpCodes.Conv_U8);
3442 LongConstant.EmitLong (ig, unchecked ((long) (ulong) k));
3446 IntConstant.EmitInt (ig, (int) ((char) k));
3447 else if (k is sbyte)
3448 IntConstant.EmitInt (ig, (int) ((sbyte) k));
3450 IntConstant.EmitInt (ig, (int) ((byte) k));
3451 else if (k is short)
3452 IntConstant.EmitInt (ig, (int) ((short) k));
3453 else if (k is ushort)
3454 IntConstant.EmitInt (ig, (int) ((ushort) k));
3456 IntConstant.EmitInt (ig, ((bool) k) ? 1 : 0);
3458 throw new Exception ("Unhandled case");
3461 // structure used to hold blocks of keys while calculating table switch
3462 class KeyBlock : IComparable
3464 public KeyBlock (long _nFirst)
3466 nFirst = nLast = _nFirst;
3470 public ArrayList rgKeys = null;
3473 get { return (int) (nLast - nFirst + 1); }
3475 public static long TotalLength (KeyBlock kbFirst, KeyBlock kbLast)
3477 return kbLast.nLast - kbFirst.nFirst + 1;
3479 public int CompareTo (object obj)
3481 KeyBlock kb = (KeyBlock) obj;
3482 int nLength = Length;
3483 int nLengthOther = kb.Length;
3484 if (nLengthOther == nLength)
3485 return (int) (kb.nFirst - nFirst);
3486 return nLength - nLengthOther;
3492 /// This method emits code for a lookup-based switch statement (non-string)
3493 /// Basically it groups the cases into blocks that are at least half full,
3494 /// and then spits out individual lookup opcodes for each block.
3495 /// It emits the longest blocks first, and short blocks are just
3496 /// handled with direct compares.
3498 /// <param name="ec"></param>
3499 /// <param name="val"></param>
3500 /// <returns></returns>
3501 bool TableSwitchEmit (EmitContext ec, LocalBuilder val)
3503 int cElements = Elements.Count;
3504 object [] rgKeys = new object [cElements];
3505 Elements.Keys.CopyTo (rgKeys, 0);
3506 Array.Sort (rgKeys);
3508 // initialize the block list with one element per key
3509 ArrayList rgKeyBlocks = new ArrayList ();
3510 foreach (object key in rgKeys)
3511 rgKeyBlocks.Add (new KeyBlock (Convert.ToInt64 (key)));
3514 // iteratively merge the blocks while they are at least half full
3515 // there's probably a really cool way to do this with a tree...
3516 while (rgKeyBlocks.Count > 1)
3518 ArrayList rgKeyBlocksNew = new ArrayList ();
3519 kbCurr = (KeyBlock) rgKeyBlocks [0];
3520 for (int ikb = 1; ikb < rgKeyBlocks.Count; ikb++)
3522 KeyBlock kb = (KeyBlock) rgKeyBlocks [ikb];
3523 if ((kbCurr.Length + kb.Length) * 2 >= KeyBlock.TotalLength (kbCurr, kb))
3526 kbCurr.nLast = kb.nLast;
3530 // start a new block
3531 rgKeyBlocksNew.Add (kbCurr);
3535 rgKeyBlocksNew.Add (kbCurr);
3536 if (rgKeyBlocks.Count == rgKeyBlocksNew.Count)
3538 rgKeyBlocks = rgKeyBlocksNew;
3541 // initialize the key lists
3542 foreach (KeyBlock kb in rgKeyBlocks)
3543 kb.rgKeys = new ArrayList ();
3545 // fill the key lists
3547 if (rgKeyBlocks.Count > 0) {
3548 kbCurr = (KeyBlock) rgKeyBlocks [0];
3549 foreach (object key in rgKeys)
3551 bool fNextBlock = (key is UInt64) ? (ulong) key > (ulong) kbCurr.nLast : Convert.ToInt64 (key) > kbCurr.nLast;
3553 kbCurr = (KeyBlock) rgKeyBlocks [++iBlockCurr];
3554 kbCurr.rgKeys.Add (key);
3558 // sort the blocks so we can tackle the largest ones first
3559 rgKeyBlocks.Sort ();
3561 // okay now we can start...
3562 ILGenerator ig = ec.ig;
3563 Label lblEnd = ig.DefineLabel (); // at the end ;-)
3564 Label lblDefault = ig.DefineLabel ();
3566 Type typeKeys = null;
3567 if (rgKeys.Length > 0)
3568 typeKeys = rgKeys [0].GetType (); // used for conversions
3570 for (int iBlock = rgKeyBlocks.Count - 1; iBlock >= 0; --iBlock)
3572 KeyBlock kb = ((KeyBlock) rgKeyBlocks [iBlock]);
3573 lblDefault = (iBlock == 0) ? DefaultTarget : ig.DefineLabel ();
3576 foreach (object key in kb.rgKeys)
3578 ig.Emit (OpCodes.Ldloc, val);
3579 EmitObjectInteger (ig, key);
3580 SwitchLabel sl = (SwitchLabel) Elements [key];
3581 ig.Emit (OpCodes.Beq, sl.ILLabel);
3586 // TODO: if all the keys in the block are the same and there are
3587 // no gaps/defaults then just use a range-check.
3588 if (SwitchType == TypeManager.int64_type ||
3589 SwitchType == TypeManager.uint64_type)
3591 // TODO: optimize constant/I4 cases
3593 // check block range (could be > 2^31)
3594 ig.Emit (OpCodes.Ldloc, val);
3595 EmitObjectInteger (ig, Convert.ChangeType (kb.nFirst, typeKeys));
3596 ig.Emit (OpCodes.Blt, lblDefault);
3597 ig.Emit (OpCodes.Ldloc, val);
3598 EmitObjectInteger (ig, Convert.ChangeType (kb.nFirst, typeKeys));
3599 ig.Emit (OpCodes.Bgt, lblDefault);
3602 ig.Emit (OpCodes.Ldloc, val);
3605 EmitObjectInteger (ig, Convert.ChangeType (kb.nFirst, typeKeys));
3606 ig.Emit (OpCodes.Sub);
3608 ig.Emit (OpCodes.Conv_I4); // assumes < 2^31 labels!
3613 ig.Emit (OpCodes.Ldloc, val);
3614 int nFirst = (int) kb.nFirst;
3617 IntConstant.EmitInt (ig, nFirst);
3618 ig.Emit (OpCodes.Sub);
3620 else if (nFirst < 0)
3622 IntConstant.EmitInt (ig, -nFirst);
3623 ig.Emit (OpCodes.Add);
3627 // first, build the list of labels for the switch
3629 int cJumps = kb.Length;
3630 Label [] rgLabels = new Label [cJumps];
3631 for (int iJump = 0; iJump < cJumps; iJump++)
3633 object key = kb.rgKeys [iKey];
3634 if (Convert.ToInt64 (key) == kb.nFirst + iJump)
3636 SwitchLabel sl = (SwitchLabel) Elements [key];
3637 rgLabels [iJump] = sl.ILLabel;
3641 rgLabels [iJump] = lblDefault;
3643 // emit the switch opcode
3644 ig.Emit (OpCodes.Switch, rgLabels);
3647 // mark the default for this block
3649 ig.MarkLabel (lblDefault);
3652 // TODO: find the default case and emit it here,
3653 // to prevent having to do the following jump.
3654 // make sure to mark other labels in the default section
3656 // the last default just goes to the end
3657 ig.Emit (OpCodes.Br, lblDefault);
3659 // now emit the code for the sections
3660 bool fFoundDefault = false;
3661 bool fAllReturn = true;
3662 foreach (SwitchSection ss in Sections)
3664 foreach (SwitchLabel sl in ss.Labels)
3666 ig.MarkLabel (sl.ILLabel);
3667 ig.MarkLabel (sl.ILLabelCode);
3668 if (sl.Label == null)
3670 ig.MarkLabel (lblDefault);
3671 fFoundDefault = true;
3674 bool returns = ss.Block.Emit (ec);
3675 fAllReturn &= returns;
3676 //ig.Emit (OpCodes.Br, lblEnd);
3679 if (!fFoundDefault) {
3680 ig.MarkLabel (lblDefault);
3683 ig.MarkLabel (lblEnd);
3688 // This simple emit switch works, but does not take advantage of the
3690 // TODO: remove non-string logic from here
3691 // TODO: binary search strings?
3693 bool SimpleSwitchEmit (EmitContext ec, LocalBuilder val)
3695 ILGenerator ig = ec.ig;
3696 Label end_of_switch = ig.DefineLabel ();
3697 Label next_test = ig.DefineLabel ();
3698 Label null_target = ig.DefineLabel ();
3699 bool default_found = false;
3700 bool first_test = true;
3701 bool pending_goto_end = false;
3702 bool all_return = true;
3703 bool is_string = false;
3707 // Special processing for strings: we cant compare
3710 if (SwitchType == TypeManager.string_type){
3711 ig.Emit (OpCodes.Ldloc, val);
3714 if (Elements.Contains (NullLiteral.Null)){
3715 ig.Emit (OpCodes.Brfalse, null_target);
3717 ig.Emit (OpCodes.Brfalse, default_target);
3719 ig.Emit (OpCodes.Ldloc, val);
3720 ig.Emit (OpCodes.Call, TypeManager.string_isinterneted_string);
3721 ig.Emit (OpCodes.Stloc, val);
3724 foreach (SwitchSection ss in Sections){
3725 Label sec_begin = ig.DefineLabel ();
3727 if (pending_goto_end)
3728 ig.Emit (OpCodes.Br, end_of_switch);
3730 int label_count = ss.Labels.Count;
3732 foreach (SwitchLabel sl in ss.Labels){
3733 ig.MarkLabel (sl.ILLabel);
3736 ig.MarkLabel (next_test);
3737 next_test = ig.DefineLabel ();
3740 // If we are the default target
3742 if (sl.Label == null){
3743 ig.MarkLabel (default_target);
3744 default_found = true;
3746 object lit = sl.Converted;
3748 if (lit is NullLiteral){
3750 if (label_count == 1)
3751 ig.Emit (OpCodes.Br, next_test);
3756 StringConstant str = (StringConstant) lit;
3758 ig.Emit (OpCodes.Ldloc, val);
3759 ig.Emit (OpCodes.Ldstr, str.Value);
3760 if (label_count == 1)
3761 ig.Emit (OpCodes.Bne_Un, next_test);
3763 ig.Emit (OpCodes.Beq, sec_begin);
3765 ig.Emit (OpCodes.Ldloc, val);
3766 EmitObjectInteger (ig, lit);
3767 ig.Emit (OpCodes.Ceq);
3768 if (label_count == 1)
3769 ig.Emit (OpCodes.Brfalse, next_test);
3771 ig.Emit (OpCodes.Brtrue, sec_begin);
3775 if (label_count != 1)
3776 ig.Emit (OpCodes.Br, next_test);
3779 ig.MarkLabel (null_target);
3780 ig.MarkLabel (sec_begin);
3781 foreach (SwitchLabel sl in ss.Labels)
3782 ig.MarkLabel (sl.ILLabelCode);
3784 bool returns = ss.Block.Emit (ec);
3786 pending_goto_end = false;
3789 pending_goto_end = true;
3793 if (!default_found){
3794 ig.MarkLabel (default_target);
3797 ig.MarkLabel (next_test);
3798 ig.MarkLabel (end_of_switch);
3804 public override bool Resolve (EmitContext ec)
3806 Expr = Expr.Resolve (ec);
3810 new_expr = SwitchGoverningType (ec, Expr.Type);
3811 if (new_expr == null){
3812 Report.Error (30338, loc, "'Select' expression cannot be of type '" + Expr.Type +"'");
3817 SwitchType = new_expr.Type;
3819 if (!CheckSwitch (ec))
3822 Switch old_switch = ec.Switch;
3824 ec.Switch.SwitchType = SwitchType;
3826 ec.StartFlowBranching (FlowBranchingType.SWITCH, loc);
3829 foreach (SwitchSection ss in Sections){
3831 ec.CurrentBranching.CreateSibling ();
3835 if (ss.Block.Resolve (ec) != true)
3841 ec.CurrentBranching.CreateSibling ();
3843 ec.EndFlowBranching ();
3844 ec.Switch = old_switch;
3849 protected override bool DoEmit (EmitContext ec)
3851 ILGenerator ig = ec.ig;
3853 // Setup the codegen context
3855 Label old_end = ec.LoopEnd;
3856 Switch old_switch = ec.Switch;
3858 ec.LoopEnd = ig.DefineLabel ();
3861 for (int secIndex = 0; secIndex < Sections.Count; secIndex ++) {
3862 SwitchSection section = (SwitchSection) Sections [secIndex];
3863 Label sLabel = ig.DefineLabel ();
3864 Label lLabel = ig.DefineLabel ();
3865 ArrayList Labels = section.Labels;
3866 for (int labelIndex = 0; labelIndex < Labels.Count; labelIndex ++) {
3867 SwitchLabel sl = (SwitchLabel) Labels [labelIndex];
3869 case SwitchLabel.LabelType.Range :
3870 if (labelIndex + 1 == Labels.Count) {
3871 EmitBoolExpression (ec, sl.ConditionStart, sLabel, false);
3872 EmitBoolExpression (ec, sl.ConditionEnd, sLabel, false);
3873 ig.Emit (OpCodes.Br, lLabel);
3875 Label newLabel = ig.DefineLabel ();
3876 EmitBoolExpression (ec, sl.ConditionStart, newLabel, false);
3877 EmitBoolExpression (ec, sl.ConditionEnd, newLabel, false);
3878 ig.Emit (OpCodes.Br, lLabel);
3879 ig.MarkLabel (newLabel);
3882 case SwitchLabel.LabelType.Else :
3883 // Nothing to be done here
3885 case SwitchLabel.LabelType.Operator :
3886 EmitBoolExpression (ec, sl.ConditionLabel, lLabel, true);
3887 if (labelIndex + 1 == Labels.Count)
3888 ig.Emit (OpCodes.Br, sLabel);
3890 case SwitchLabel.LabelType.Label :
3891 EmitBoolExpression (ec, sl.ConditionLabel, lLabel, true);
3892 if (labelIndex + 1 == Labels.Count)
3893 ig.Emit (OpCodes.Br, sLabel);
3898 ig.MarkLabel (lLabel);
3899 section.Block.Emit (ec);
3900 ig.MarkLabel (sLabel);
3903 // Restore context state.
3904 ig.MarkLabel (ec.LoopEnd);
3907 // Restore the previous context
3909 ec.LoopEnd = old_end;
3910 ec.Switch = old_switch;
3915 public class Lock : Statement {
3917 Statement Statement;
3919 public Lock (Expression expr, Statement stmt, Location l)
3926 public override bool Resolve (EmitContext ec)
3928 expr = expr.Resolve (ec);
3929 return Statement.Resolve (ec) && expr != null;
3932 protected override bool DoEmit (EmitContext ec)
3934 Type type = expr.Type;
3937 if (type.IsValueType){
3938 Report.Error (30582, loc, "lock statement requires the expression to be " +
3939 " a reference type (type is: '" +
3940 TypeManager.MonoBASIC_Name (type) + "'");
3944 ILGenerator ig = ec.ig;
3945 LocalBuilder temp = ig.DeclareLocal (type);
3948 ig.Emit (OpCodes.Dup);
3949 ig.Emit (OpCodes.Stloc, temp);
3950 ig.Emit (OpCodes.Call, TypeManager.void_monitor_enter_object);
3953 ig.BeginExceptionBlock ();
3954 bool old_in_try = ec.InTry;
3956 Label finish = ig.DefineLabel ();
3957 val = Statement.Emit (ec);
3958 ec.InTry = old_in_try;
3959 // ig.Emit (OpCodes.Leave, finish);
3961 ig.MarkLabel (finish);
3964 ig.BeginFinallyBlock ();
3965 ig.Emit (OpCodes.Ldloc, temp);
3966 ig.Emit (OpCodes.Call, TypeManager.void_monitor_exit_object);
3967 ig.EndExceptionBlock ();
3973 public class Unchecked : Statement {
3974 public readonly Block Block;
3976 public Unchecked (Block b)
3981 public override bool Resolve (EmitContext ec)
3983 return Block.Resolve (ec);
3986 protected override bool DoEmit (EmitContext ec)
3988 bool previous_state = ec.CheckState;
3989 bool previous_state_const = ec.ConstantCheckState;
3992 ec.CheckState = false;
3993 ec.ConstantCheckState = false;
3994 val = Block.Emit (ec);
3995 ec.CheckState = previous_state;
3996 ec.ConstantCheckState = previous_state_const;
4002 public class Checked : Statement {
4003 public readonly Block Block;
4005 public Checked (Block b)
4010 public override bool Resolve (EmitContext ec)
4012 bool previous_state = ec.CheckState;
4013 bool previous_state_const = ec.ConstantCheckState;
4015 ec.CheckState = true;
4016 ec.ConstantCheckState = true;
4017 bool ret = Block.Resolve (ec);
4018 ec.CheckState = previous_state;
4019 ec.ConstantCheckState = previous_state_const;
4024 protected override bool DoEmit (EmitContext ec)
4026 bool previous_state = ec.CheckState;
4027 bool previous_state_const = ec.ConstantCheckState;
4030 ec.CheckState = true;
4031 ec.ConstantCheckState = true;
4032 val = Block.Emit (ec);
4033 ec.CheckState = previous_state;
4034 ec.ConstantCheckState = previous_state_const;
4040 public class Unsafe : Statement {
4041 public readonly Block Block;
4043 public Unsafe (Block b)
4048 public override bool Resolve (EmitContext ec)
4050 bool previous_state = ec.InUnsafe;
4054 val = Block.Resolve (ec);
4055 ec.InUnsafe = previous_state;
4060 protected override bool DoEmit (EmitContext ec)
4062 bool previous_state = ec.InUnsafe;
4066 val = Block.Emit (ec);
4067 ec.InUnsafe = previous_state;
4076 public class Fixed : Statement {
4078 ArrayList declarators;
4079 Statement statement;
4084 public bool is_object;
4085 public VariableInfo vi;
4086 public Expression expr;
4087 public Expression converted;
4090 public Fixed (Expression type, ArrayList decls, Statement stmt, Location l)
4093 declarators = decls;
4098 public override bool Resolve (EmitContext ec)
4100 expr_type = ec.DeclSpace.ResolveType (type, false, loc);
4101 if (expr_type == null)
4104 data = new FixedData [declarators.Count];
4107 foreach (Pair p in declarators){
4108 VariableInfo vi = (VariableInfo) p.First;
4109 Expression e = (Expression) p.Second;
4114 // The rules for the possible declarators are pretty wise,
4115 // but the production on the grammar is more concise.
4117 // So we have to enforce these rules here.
4119 // We do not resolve before doing the case 1 test,
4120 // because the grammar is explicit in that the token &
4121 // is present, so we need to test for this particular case.
4125 // Case 1: & object.
4127 if (e is Unary && ((Unary) e).Oper == Unary.Operator.AddressOf){
4128 Expression child = ((Unary) e).Expr;
4131 if (child is ParameterReference || child is LocalVariableReference){
4134 "No need to use fixed statement for parameters or " +
4135 "local variable declarations (address is already " +
4144 child = ((Unary) e).Expr;
4146 if (!TypeManager.VerifyUnManaged (child.Type, loc))
4149 data [i].is_object = true;
4151 data [i].converted = null;
4165 if (e.Type.IsArray){
4166 Type array_type = e.Type.GetElementType ();
4170 // Provided that array_type is unmanaged,
4172 if (!TypeManager.VerifyUnManaged (array_type, loc))
4176 // and T* is implicitly convertible to the
4177 // pointer type given in the fixed statement.
4179 ArrayPtr array_ptr = new ArrayPtr (e, loc);
4181 Expression converted = Expression.ConvertImplicitRequired (
4182 ec, array_ptr, vi.VariableType, loc);
4183 if (converted == null)
4186 data [i].is_object = false;
4188 data [i].converted = converted;
4198 if (e.Type == TypeManager.string_type){
4199 data [i].is_object = false;
4201 data [i].converted = null;
4207 return statement.Resolve (ec);
4210 protected override bool DoEmit (EmitContext ec)
4212 ILGenerator ig = ec.ig;
4214 bool is_ret = false;
4216 for (int i = 0; i < data.Length; i++) {
4217 VariableInfo vi = data [i].vi;
4220 // Case 1: & object.
4222 if (data [i].is_object) {
4224 // Store pointer in pinned location
4226 data [i].expr.Emit (ec);
4227 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
4229 is_ret = statement.Emit (ec);
4231 // Clear the pinned variable.
4232 ig.Emit (OpCodes.Ldc_I4_0);
4233 ig.Emit (OpCodes.Conv_U);
4234 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
4242 if (data [i].expr.Type.IsArray){
4244 // Store pointer in pinned location
4246 data [i].converted.Emit (ec);
4248 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
4250 is_ret = statement.Emit (ec);
4252 // Clear the pinned variable.
4253 ig.Emit (OpCodes.Ldc_I4_0);
4254 ig.Emit (OpCodes.Conv_U);
4255 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
4263 if (data [i].expr.Type == TypeManager.string_type){
4264 LocalBuilder pinned_string = ig.DeclareLocal (TypeManager.string_type);
4265 TypeManager.MakePinned (pinned_string);
4267 data [i].expr.Emit (ec);
4268 ig.Emit (OpCodes.Stloc, pinned_string);
4270 Expression sptr = new StringPtr (pinned_string, loc);
4271 Expression converted = Expression.ConvertImplicitRequired (
4272 ec, sptr, vi.VariableType, loc);
4274 if (converted == null)
4277 converted.Emit (ec);
4278 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
4280 is_ret = statement.Emit (ec);
4282 // Clear the pinned variable
4283 ig.Emit (OpCodes.Ldnull);
4284 ig.Emit (OpCodes.Stloc, pinned_string);
4292 public class Catch {
4293 public readonly string Name;
4294 public readonly Block Block;
4295 public Expression Clause;
4296 public readonly Location Location;
4298 Expression type_expr;
4299 //Expression clus_expr;
4302 public Catch (Expression type, string name, Block block, Expression clause, Location l)
4311 public Type CatchType {
4317 public bool IsGeneral {
4319 return type_expr == null;
4323 public bool Resolve (EmitContext ec)
4325 if (type_expr != null) {
4326 type = ec.DeclSpace.ResolveType (type_expr, false, Location);
4330 if (type != TypeManager.exception_type && !type.IsSubclassOf (TypeManager.exception_type)){
4331 Report.Error (30665, Location,
4332 "The type caught or thrown must be derived " +
4333 "from System.Exception");
4339 if (Clause != null) {
4340 Clause = Statement.ResolveBoolean (ec, Clause, Location);
4341 if (Clause == null) {
4346 if (!Block.Resolve (ec))
4353 public class Try : Statement {
4354 public readonly Block Fini, Block;
4355 public readonly ArrayList Specific;
4356 public readonly Catch General;
4359 // specific, general and fini might all be null.
4361 public Try (Block block, ArrayList specific, Catch general, Block fini, Location l)
4363 if (specific == null && general == null){
4364 Console.WriteLine ("CIR.Try: Either specific or general have to be non-null");
4368 this.Specific = specific;
4369 this.General = general;
4374 public override bool Resolve (EmitContext ec)
4378 ec.StartFlowBranching (FlowBranchingType.EXCEPTION, Block.StartLocation);
4380 Report.Debug (1, "START OF TRY BLOCK", Block.StartLocation);
4382 bool old_in_try = ec.InTry;
4385 if (!Block.Resolve (ec))
4388 ec.InTry = old_in_try;
4390 FlowBranching.UsageVector vector = ec.CurrentBranching.CurrentUsageVector;
4392 Report.Debug (1, "START OF CATCH BLOCKS", vector);
4394 foreach (Catch c in Specific){
4395 ec.CurrentBranching.CreateSibling ();
4396 Report.Debug (1, "STARTED SIBLING FOR CATCH", ec.CurrentBranching);
4398 if (c.Name != null) {
4399 VariableInfo vi = c.Block.GetVariableInfo (c.Name);
4401 throw new Exception ();
4406 bool old_in_catch = ec.InCatch;
4409 if (!c.Resolve (ec))
4412 ec.InCatch = old_in_catch;
4414 FlowBranching.UsageVector current = ec.CurrentBranching.CurrentUsageVector;
4416 if (!current.AlwaysReturns && !current.AlwaysBreaks)
4417 vector.AndLocals (current);
4420 Report.Debug (1, "END OF CATCH BLOCKS", ec.CurrentBranching);
4422 if (General != null){
4423 ec.CurrentBranching.CreateSibling ();
4424 Report.Debug (1, "STARTED SIBLING FOR GENERAL", ec.CurrentBranching);
4426 bool old_in_catch = ec.InCatch;
4429 if (!General.Resolve (ec))
4432 ec.InCatch = old_in_catch;
4434 FlowBranching.UsageVector current = ec.CurrentBranching.CurrentUsageVector;
4436 if (!current.AlwaysReturns && !current.AlwaysBreaks)
4437 vector.AndLocals (current);
4440 Report.Debug (1, "END OF GENERAL CATCH BLOCKS", ec.CurrentBranching);
4443 ec.CurrentBranching.CreateSiblingForFinally ();
4444 Report.Debug (1, "STARTED SIBLING FOR FINALLY", ec.CurrentBranching, vector);
4446 bool old_in_finally = ec.InFinally;
4447 ec.InFinally = true;
4449 if (!Fini.Resolve (ec))
4452 ec.InFinally = old_in_finally;
4455 FlowReturns returns = ec.EndFlowBranching ();
4457 FlowBranching.UsageVector f_vector = ec.CurrentBranching.CurrentUsageVector;
4459 Report.Debug (1, "END OF FINALLY", ec.CurrentBranching, returns, vector, f_vector);
4460 ec.CurrentBranching.CurrentUsageVector.Or (vector);
4462 Report.Debug (1, "END OF TRY", ec.CurrentBranching);
4467 protected override bool DoEmit (EmitContext ec)
4469 ILGenerator ig = ec.ig;
4473 Label finish = ig.BeginExceptionBlock ();
4474 ec.HasExitLabel = true;
4475 ec.ExitLabel = finish;
4477 bool old_in_try = ec.InTry;
4479 returns = Block.Emit (ec);
4480 ec.InTry = old_in_try;
4483 // System.Reflection.Emit provides this automatically:
4484 // ig.Emit (OpCodes.Leave, finish);
4486 bool old_in_catch = ec.InCatch;
4488 //DeclSpace ds = ec.DeclSpace;
4490 foreach (Catch c in Specific){
4493 ig.BeginCatchBlock (c.CatchType);
4495 if (c.Name != null){
4496 vi = c.Block.GetVariableInfo (c.Name);
4498 throw new Exception ("Variable does not exist in this block");
4500 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
4502 ig.Emit (OpCodes.Pop);
4505 // if when clause is there
4507 if (c.Clause != null) {
4508 if (c.Clause is BoolConstant) {
4509 bool take = ((BoolConstant) c.Clause).Value;
4512 if (!c.Block.Emit (ec))
4515 EmitBoolExpression (ec, c.Clause, finish, false);
4516 if (!c.Block.Emit (ec))
4520 if (!c.Block.Emit (ec))
4524 if (General != null){
4525 ig.BeginCatchBlock (TypeManager.object_type);
4526 ig.Emit (OpCodes.Pop);
4528 if (General.Clause != null) {
4529 if (General.Clause is BoolConstant) {
4530 bool take = ((BoolConstant) General.Clause).Value;
4532 if (!General.Block.Emit (ec))
4535 EmitBoolExpression (ec, General.Clause, finish, false);
4536 if (!General.Block.Emit (ec))
4540 if (!General.Block.Emit (ec))
4544 ec.InCatch = old_in_catch;
4547 ig.BeginFinallyBlock ();
4548 bool old_in_finally = ec.InFinally;
4549 ec.InFinally = true;
4551 ec.InFinally = old_in_finally;
4554 ig.EndExceptionBlock ();
4557 if (!returns || ec.InTry || ec.InCatch)
4564 public class Pending_Assign {
4566 Block block_to_be_inserted;
4567 int statement_index;
4569 public Pending_Assign (Block block, Statement assign, int index)
4571 this.assign = assign;
4572 this.block_to_be_inserted = block;
4573 this.statement_index = index;
4576 public void AddAssign()
4578 block_to_be_inserted.statements.Insert( statement_index, assign );
4582 public class On_Error : Statement {
4583 public readonly Block method_block;
4585 LabeledStatement[] labeledstatements;
4587 public On_Error (Block method_block, Location l)
4590 this.method_block = method_block;
4592 targets = new ArrayList();
4595 public int AddTarget ( string target )
4597 int i = targets.IndexOf( target ) ;
4600 return targets.Add ( target );
4605 public ArrayList Targets {
4611 public override bool Resolve (EmitContext ec)
4613 this.labeledstatements = new LabeledStatement[targets.Count];
4617 ec.StartFlowBranching (FlowBranchingType.EXCEPTION, method_block.StartLocation);
4619 Report.Debug (1, "START OF TRY BLOCK", method_block.StartLocation);
4621 bool old_in_try = ec.InTry;
4624 if (!method_block.Resolve (ec))
4627 ec.InTry = old_in_try;
4629 FlowBranching.UsageVector vector = ec.CurrentBranching.CurrentUsageVector;
4631 ec.EndFlowBranching ();
4633 ec.CurrentBranching.CurrentUsageVector.Or (vector);
4635 Report.Debug (1, "END OF TRY", ec.CurrentBranching);
4637 //This statement has more than one label in cases of more than one 'on error goto' specification.
4638 for ( int i = 0 ; i < targets.Count ; i++ )
4640 labeledstatements[i] = method_block.Parent.LookupLabel ((string) targets[i]);
4642 // If this is a forward goto.
4643 if (!labeledstatements[i].IsDefined)
4644 labeledstatements[i].AddUsageVector (ec.CurrentBranching.CurrentUsageVector);
4646 labeledstatements[i].AddReference ();
4648 ec.CurrentBranching.CurrentUsageVector.Breaks = FlowReturns.ALWAYS;
4652 protected override bool DoEmit (EmitContext ec)
4654 ILGenerator ig = ec.ig;
4662 Label finish = ig.BeginExceptionBlock ();
4663 ec.HasExitLabel = true;
4664 ec.ExitLabel = finish;
4666 bool old_in_try = ec.InTry;
4668 returns = method_block.Emit (ec);
4669 ec.InTry = old_in_try;
4670 bool old_in_catch = ec.InCatch;
4673 Label error = ig.DefineLabel();
4674 Label endfilter = ig.DefineLabel();
4675 Label verification = ig.DefineLabel();
4677 ig.BeginExceptFilterBlock();
4678 ig.Emit (OpCodes.Isinst, Type.GetType("System.Exception") );
4679 ig.Emit (OpCodes.Brtrue_S, verification );
4681 ig.Emit (OpCodes.Br_S, error);
4683 ig.MarkLabel ( verification );
4684 ig.Emit (OpCodes.Ldloc_0);
4685 ig.Emit (OpCodes.Brfalse_S, error);
4687 ig.Emit (OpCodes.Ldloc_1);
4688 ig.Emit (OpCodes.Brtrue_S, error);
4690 ig.Emit (OpCodes.Ldc_I4_1);
4691 ig.Emit (OpCodes.Br_S, endfilter);
4693 ig.MarkLabel (error);
4694 ig.Emit (OpCodes.Ldc_I4_0);
4696 ig.MarkLabel ( endfilter );
4699 Label endcatch = ig.DefineLabel();
4700 Label verification2 = ig.DefineLabel();
4702 ig.BeginCatchBlock (null);
4703 ig.Emit (OpCodes.Castclass, Type.GetType("System.Exception"));
4704 ig.Emit (OpCodes.Dup);
4706 Type t = typeof(Microsoft.VisualBasic.CompilerServices.ProjectData);
4707 MethodInfo mi = t.GetMethod("SetProjectError", new Type[] { typeof(System.Exception) } );
4708 ig.Emit (OpCodes.Call, mi);
4709 ig.Emit (OpCodes.Stloc_3);
4710 ig.Emit (OpCodes.Ldloc_1);
4711 ig.Emit (OpCodes.Brfalse_S, verification2 );
4712 ig.Emit (OpCodes.Leave_S, finish );
4713 ig.MarkLabel ( verification2 );
4714 ig.Emit (OpCodes.Ldc_I4_M1);
4715 ig.Emit (OpCodes.Stloc_1);
4716 ig.Emit (OpCodes.Ldloc_0);
4718 Label[] lbswitch = new Label[targets.Count + 1];
4719 for ( int i = 0; i <= targets.Count; i++ )
4720 lbswitch[i] = ig.DefineLabel();
4722 ig.Emit (OpCodes.Switch, lbswitch);
4723 ig.MarkLabel ( lbswitch[0] ) ;
4724 ig.Emit (OpCodes.Leave_S, endcatch);
4726 Label[] labels = new Label[targets.Count];
4727 for ( int i = 0; i < targets.Count; i++ )
4729 labels[i] = labeledstatements[i].LabelTarget(ec);
4731 ig.MarkLabel ( lbswitch[i+1] ) ;
4732 ig.Emit ( OpCodes.Leave, labels[i] );
4735 ig.MarkLabel ( endcatch );
4736 ig.Emit ( OpCodes.Rethrow );
4738 ec.InCatch = old_in_catch;
4740 ig.EndExceptionBlock ();
4743 Label end = ig.DefineLabel();
4744 //ig.MarkLabel ( finish ) ;
4745 ig.Emit (OpCodes.Ldloc_1);
4746 ig.Emit (OpCodes.Brfalse_S, end );
4748 mi = t.GetMethod("ClearProjectError");
4749 ig.Emit (OpCodes.Call, mi);
4756 // Unfortunately, System.Reflection.Emit automatically emits a leave
4757 // to the end of the finally block. This is a problem if 'returns'
4758 // is true since we may jump to a point after the end of the method.
4759 // As a workaround, emit an explicit ret here.
4761 if (ec.ReturnType != null)
4762 ec.ig.Emit (OpCodes.Ldloc, ec.TemporaryReturn ());
4763 ec.ig.Emit (OpCodes.Ret);
4770 public class Using : Statement {
4771 object expression_or_block;
4772 Statement Statement;
4777 Expression [] converted_vars;
4778 ExpressionStatement [] assign;
4780 public Using (object expression_or_block, Statement stmt, Location l)
4782 this.expression_or_block = expression_or_block;
4788 // Resolves for the case of using using a local variable declaration.
4790 bool ResolveLocalVariableDecls (EmitContext ec)
4792 bool need_conv = false;
4793 expr_type = ec.DeclSpace.ResolveType (expr, false, loc);
4796 if (expr_type == null)
4800 // The type must be an IDisposable or an implicit conversion
4803 converted_vars = new Expression [var_list.Count];
4804 assign = new ExpressionStatement [var_list.Count];
4805 if (!TypeManager.ImplementsInterface (expr_type, TypeManager.idisposable_type)){
4806 foreach (DictionaryEntry e in var_list){
4807 Expression var = (Expression) e.Key;
4809 var = var.ResolveLValue (ec, new EmptyExpression ());
4813 converted_vars [i] = Expression.ConvertImplicitRequired (
4814 ec, var, TypeManager.idisposable_type, loc);
4816 if (converted_vars [i] == null)
4824 foreach (DictionaryEntry e in var_list){
4825 LocalVariableReference var = (LocalVariableReference) e.Key;
4826 Expression new_expr = (Expression) e.Value;
4829 a = new Assign (var, new_expr, loc);
4835 converted_vars [i] = var;
4836 assign [i] = (ExpressionStatement) a;
4843 bool ResolveExpression (EmitContext ec)
4845 if (!TypeManager.ImplementsInterface (expr_type, TypeManager.idisposable_type)){
4846 conv = Expression.ConvertImplicitRequired (
4847 ec, expr, TypeManager.idisposable_type, loc);
4857 // Emits the code for the case of using using a local variable declaration.
4859 bool EmitLocalVariableDecls (EmitContext ec)
4861 ILGenerator ig = ec.ig;
4864 bool old_in_try = ec.InTry;
4866 for (i = 0; i < assign.Length; i++) {
4867 assign [i].EmitStatement (ec);
4869 ig.BeginExceptionBlock ();
4871 Statement.Emit (ec);
4872 ec.InTry = old_in_try;
4874 bool old_in_finally = ec.InFinally;
4875 ec.InFinally = true;
4876 var_list.Reverse ();
4877 foreach (DictionaryEntry e in var_list){
4878 LocalVariableReference var = (LocalVariableReference) e.Key;
4879 Label skip = ig.DefineLabel ();
4882 ig.BeginFinallyBlock ();
4885 ig.Emit (OpCodes.Brfalse, skip);
4886 converted_vars [i].Emit (ec);
4887 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
4888 ig.MarkLabel (skip);
4889 ig.EndExceptionBlock ();
4891 ec.InFinally = old_in_finally;
4896 bool EmitExpression (EmitContext ec)
4899 // Make a copy of the expression and operate on that.
4901 ILGenerator ig = ec.ig;
4902 LocalBuilder local_copy = ig.DeclareLocal (expr_type);
4907 ig.Emit (OpCodes.Stloc, local_copy);
4909 bool old_in_try = ec.InTry;
4911 ig.BeginExceptionBlock ();
4912 Statement.Emit (ec);
4913 ec.InTry = old_in_try;
4915 Label skip = ig.DefineLabel ();
4916 bool old_in_finally = ec.InFinally;
4917 ig.BeginFinallyBlock ();
4918 ig.Emit (OpCodes.Ldloc, local_copy);
4919 ig.Emit (OpCodes.Brfalse, skip);
4920 ig.Emit (OpCodes.Ldloc, local_copy);
4921 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
4922 ig.MarkLabel (skip);
4923 ec.InFinally = old_in_finally;
4924 ig.EndExceptionBlock ();
4929 public override bool Resolve (EmitContext ec)
4931 if (expression_or_block is DictionaryEntry){
4932 expr = (Expression) ((DictionaryEntry) expression_or_block).Key;
4933 var_list = (ArrayList)((DictionaryEntry)expression_or_block).Value;
4935 if (!ResolveLocalVariableDecls (ec))
4938 } else if (expression_or_block is Expression){
4939 expr = (Expression) expression_or_block;
4941 expr = expr.Resolve (ec);
4945 expr_type = expr.Type;
4947 if (!ResolveExpression (ec))
4951 return Statement.Resolve (ec);
4954 protected override bool DoEmit (EmitContext ec)
4956 if (expression_or_block is DictionaryEntry)
4957 return EmitLocalVariableDecls (ec);
4958 else if (expression_or_block is Expression)
4959 return EmitExpression (ec);
4966 /// Implementation of the for each statement
4968 public class Foreach : Statement {
4970 LocalVariableReference variable;
4972 Statement statement;
4973 ForeachHelperMethods hm;
4974 Expression empty, conv;
4975 Type array_type, element_type;
4978 public Foreach (Expression type, LocalVariableReference var, Expression expr,
4979 Statement stmt, Location l)
4986 VariableInfo vi = var.VariableInfo;
4987 this.type = vi.Type;
4989 this.variable = var;
4995 public override bool Resolve (EmitContext ec)
4997 expr = expr.Resolve (ec);
5001 if ( variable.VariableInfo.Alias != null )
5003 FieldBase fb = variable.VariableInfo.GetFieldAlias(ec);
5007 Report.Error (451, loc,"Name '" + variable.VariableInfo.Name + "' is not declared.");
5014 var_type = ec.DeclSpace.ResolveType (type, false, loc);
5015 if (var_type == null)
5019 // We need an instance variable. Not sure this is the best
5020 // way of doing this.
5022 // FIXME: When we implement propertyaccess, will those turn
5023 // out to return values in ExprClass? I think they should.
5025 if (!(expr.eclass == ExprClass.Variable || expr.eclass == ExprClass.Value ||
5026 expr.eclass == ExprClass.PropertyAccess || expr.eclass == ExprClass.IndexerAccess)){
5027 error1579 (expr.Type);
5031 if (expr.Type.IsArray) {
5032 array_type = expr.Type;
5033 element_type = array_type.GetElementType ();
5035 empty = new EmptyExpression (element_type);
5037 hm = ProbeCollectionType (ec, expr.Type);
5039 error1579 (expr.Type);
5043 array_type = expr.Type;
5044 element_type = hm.element_type;
5046 empty = new EmptyExpression (hm.element_type);
5049 ec.StartFlowBranching (FlowBranchingType.LOOP_BLOCK, loc);
5050 ec.CurrentBranching.CreateSibling ();
5054 // FIXME: maybe we can apply the same trick we do in the
5055 // array handling to avoid creating empty and conv in some cases.
5057 // Although it is not as important in this case, as the type
5058 // will not likely be object (what the enumerator will return).
5060 conv = Expression.ConvertExplicit (ec, empty, var_type, false, loc);
5064 if (variable.ResolveLValue (ec, empty) == null)
5067 if (!statement.Resolve (ec))
5070 //FlowReturns returns = ec.EndFlowBranching ();
5071 ec.EndFlowBranching ();
5076 // Retrieves a 'public bool MoveNext ()' method from the Type 't'
5078 static MethodInfo FetchMethodMoveNext (Type t)
5080 MemberList move_next_list;
5082 move_next_list = TypeContainer.FindMembers (
5083 t, MemberTypes.Method,
5084 BindingFlags.Public | BindingFlags.Instance,
5085 Type.FilterName, "MoveNext");
5086 if (move_next_list.Count == 0)
5089 foreach (MemberInfo m in move_next_list){
5090 MethodInfo mi = (MethodInfo) m;
5093 args = TypeManager.GetArgumentTypes (mi);
5094 if (args != null && args.Length == 0){
5095 if (mi.ReturnType == TypeManager.bool_type)
5103 // Retrieves a 'public T get_Current ()' method from the Type 't'
5105 static MethodInfo FetchMethodGetCurrent (Type t)
5107 MemberList move_next_list;
5109 move_next_list = TypeContainer.FindMembers (
5110 t, MemberTypes.Method,
5111 BindingFlags.Public | BindingFlags.Instance,
5112 Type.FilterName, "get_Current");
5113 if (move_next_list.Count == 0)
5116 foreach (MemberInfo m in move_next_list){
5117 MethodInfo mi = (MethodInfo) m;
5120 args = TypeManager.GetArgumentTypes (mi);
5121 if (args != null && args.Length == 0)
5128 // This struct records the helper methods used by the Foreach construct
5130 class ForeachHelperMethods {
5131 public EmitContext ec;
5132 public MethodInfo get_enumerator;
5133 public MethodInfo move_next;
5134 public MethodInfo get_current;
5135 public Type element_type;
5136 public Type enumerator_type;
5137 public bool is_disposable;
5139 public ForeachHelperMethods (EmitContext ec)
5142 this.element_type = TypeManager.object_type;
5143 this.enumerator_type = TypeManager.ienumerator_type;
5144 this.is_disposable = true;
5148 static bool GetEnumeratorFilter (MemberInfo m, object criteria)
5153 if (!(m is MethodInfo))
5156 if (m.Name != "GetEnumerator")
5159 MethodInfo mi = (MethodInfo) m;
5160 Type [] args = TypeManager.GetArgumentTypes (mi);
5162 if (args.Length != 0)
5165 ForeachHelperMethods hm = (ForeachHelperMethods) criteria;
5166 EmitContext ec = hm.ec;
5169 // Check whether GetEnumerator is accessible to us
5171 MethodAttributes prot = mi.Attributes & MethodAttributes.MemberAccessMask;
5173 Type declaring = mi.DeclaringType;
5174 if (prot == MethodAttributes.Private){
5175 if (declaring != ec.ContainerType)
5177 } else if (prot == MethodAttributes.FamANDAssem){
5178 // If from a different assembly, false
5179 if (!(mi is MethodBuilder))
5182 // Are we being invoked from the same class, or from a derived method?
5184 if (ec.ContainerType != declaring){
5185 if (!ec.ContainerType.IsSubclassOf (declaring))
5188 } else if (prot == MethodAttributes.FamORAssem){
5189 if (!(mi is MethodBuilder ||
5190 ec.ContainerType == declaring ||
5191 ec.ContainerType.IsSubclassOf (declaring)))
5193 } if (prot == MethodAttributes.Family){
5194 if (!(ec.ContainerType == declaring ||
5195 ec.ContainerType.IsSubclassOf (declaring)))
5200 // Ok, we can access it, now make sure that we can do something
5201 // with this 'GetEnumerator'
5204 if (mi.ReturnType == TypeManager.ienumerator_type ||
5205 TypeManager.ienumerator_type.IsAssignableFrom (mi.ReturnType) ||
5206 (!RootContext.StdLib && TypeManager.ImplementsInterface (mi.ReturnType, TypeManager.ienumerator_type))) {
5207 hm.move_next = TypeManager.bool_movenext_void;
5208 hm.get_current = TypeManager.object_getcurrent_void;
5213 // Ok, so they dont return an IEnumerable, we will have to
5214 // find if they support the GetEnumerator pattern.
5216 Type return_type = mi.ReturnType;
5218 hm.move_next = FetchMethodMoveNext (return_type);
5219 if (hm.move_next == null)
5221 hm.get_current = FetchMethodGetCurrent (return_type);
5222 if (hm.get_current == null)
5225 hm.element_type = hm.get_current.ReturnType;
5226 hm.enumerator_type = return_type;
5227 hm.is_disposable = TypeManager.ImplementsInterface (
5228 hm.enumerator_type, TypeManager.idisposable_type);
5234 /// This filter is used to find the GetEnumerator method
5235 /// on which IEnumerator operates
5237 static MemberFilter FilterEnumerator;
5241 FilterEnumerator = new MemberFilter (GetEnumeratorFilter);
5244 void error1579 (Type t)
5246 Report.Error (1579, loc,
5247 "foreach statement cannot operate on variables of type '" +
5248 t.FullName + "' because that class does not provide a " +
5249 " GetEnumerator method or it is inaccessible");
5252 static bool TryType (Type t, ForeachHelperMethods hm)
5256 mi = TypeContainer.FindMembers (t, MemberTypes.Method,
5257 BindingFlags.Public | BindingFlags.NonPublic |
5258 BindingFlags.Instance,
5259 FilterEnumerator, hm);
5264 hm.get_enumerator = (MethodInfo) mi [0];
5269 // Looks for a usable GetEnumerator in the Type, and if found returns
5270 // the three methods that participate: GetEnumerator, MoveNext and get_Current
5272 ForeachHelperMethods ProbeCollectionType (EmitContext ec, Type t)
5274 ForeachHelperMethods hm = new ForeachHelperMethods (ec);
5276 if (TryType (t, hm))
5280 // Now try to find the method in the interfaces
5283 Type [] ifaces = t.GetInterfaces ();
5285 foreach (Type i in ifaces){
5286 if (TryType (i, hm))
5291 // Since TypeBuilder.GetInterfaces only returns the interface
5292 // types for this type, we have to keep looping, but once
5293 // we hit a non-TypeBuilder (ie, a Type), then we know we are
5294 // done, because it returns all the types
5296 if ((t is TypeBuilder))
5306 // FIXME: possible optimization.
5307 // We might be able to avoid creating 'empty' if the type is the sam
5309 bool EmitCollectionForeach (EmitContext ec)
5311 ILGenerator ig = ec.ig;
5312 LocalBuilder enumerator, disposable;
5314 enumerator = ig.DeclareLocal (hm.enumerator_type);
5315 if (hm.is_disposable)
5316 disposable = ig.DeclareLocal (TypeManager.idisposable_type);
5321 // Instantiate the enumerator
5323 if (expr.Type.IsValueType){
5324 if (expr is IMemoryLocation){
5325 IMemoryLocation ml = (IMemoryLocation) expr;
5327 ml.AddressOf (ec, AddressOp.Load);
5329 throw new Exception ("Expr " + expr + " of type " + expr.Type +
5330 " does not implement IMemoryLocation");
5331 ig.Emit (OpCodes.Call, hm.get_enumerator);
5334 ig.Emit (OpCodes.Callvirt, hm.get_enumerator);
5336 ig.Emit (OpCodes.Stloc, enumerator);
5339 // Protect the code in a try/finalize block, so that
5340 // if the beast implement IDisposable, we get rid of it
5342 bool old_in_try = ec.InTry;
5344 if (hm.is_disposable) {
5345 ig.BeginExceptionBlock ();
5349 Label end_try = ig.DefineLabel ();
5351 ig.MarkLabel (ec.LoopBegin);
5352 ig.Emit (OpCodes.Ldloc, enumerator);
5353 ig.Emit (OpCodes.Callvirt, hm.move_next);
5354 ig.Emit (OpCodes.Brfalse, end_try);
5357 FieldBase fb = null;
5358 if ( variable.VariableInfo.Alias != null )
5360 fb = variable.VariableInfo.GetFieldAlias(ec);
5362 if( (fb.ModFlags & Modifiers.STATIC) == 0 )
5363 ig.Emit (OpCodes.Ldarg_0);
5366 ig.Emit (OpCodes.Ldloc, enumerator);
5367 ig.Emit (OpCodes.Callvirt, hm.get_current);
5370 variable.EmitAssign (ec, conv);
5372 variable.EmitAssign (ec, conv, fb);
5374 statement.Emit (ec);
5375 ig.Emit (OpCodes.Br, ec.LoopBegin);
5376 ig.MarkLabel (end_try);
5377 ec.InTry = old_in_try;
5379 // The runtime provides this for us.
5380 // ig.Emit (OpCodes.Leave, end);
5383 // Now the finally block
5385 if (hm.is_disposable) {
5386 Label end_finally = ig.DefineLabel ();
5387 bool old_in_finally = ec.InFinally;
5388 ec.InFinally = true;
5389 ig.BeginFinallyBlock ();
5391 ig.Emit (OpCodes.Ldloc, enumerator);
5392 ig.Emit (OpCodes.Isinst, TypeManager.idisposable_type);
5393 ig.Emit (OpCodes.Stloc, disposable);
5394 ig.Emit (OpCodes.Ldloc, disposable);
5395 ig.Emit (OpCodes.Brfalse, end_finally);
5396 ig.Emit (OpCodes.Ldloc, disposable);
5397 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
5398 ig.MarkLabel (end_finally);
5399 ec.InFinally = old_in_finally;
5401 // The runtime generates this anyways.
5402 // ig.Emit (OpCodes.Endfinally);
5404 ig.EndExceptionBlock ();
5407 ig.MarkLabel (ec.LoopEnd);
5412 // FIXME: possible optimization.
5413 // We might be able to avoid creating 'empty' if the type is the sam
5415 bool EmitArrayForeach (EmitContext ec)
5417 int rank = array_type.GetArrayRank ();
5418 ILGenerator ig = ec.ig;
5420 LocalBuilder copy = ig.DeclareLocal (array_type);
5423 // Make our copy of the array
5426 ig.Emit (OpCodes.Stloc, copy);
5429 LocalBuilder counter = ig.DeclareLocal (TypeManager.int32_type);
5433 ig.Emit (OpCodes.Ldc_I4_0);
5434 ig.Emit (OpCodes.Stloc, counter);
5435 test = ig.DefineLabel ();
5436 ig.Emit (OpCodes.Br, test);
5438 loop = ig.DefineLabel ();
5439 ig.MarkLabel (loop);
5441 FieldBase fb = null;
5442 if ( variable.VariableInfo.Alias != null )
5444 fb = variable.VariableInfo.GetFieldAlias(ec);
5446 if( (fb.ModFlags & Modifiers.STATIC) == 0 )
5447 ig.Emit (OpCodes.Ldarg_0);
5450 ig.Emit (OpCodes.Ldloc, copy);
5451 ig.Emit (OpCodes.Ldloc, counter);
5452 ArrayAccess.EmitLoadOpcode (ig, var_type);
5455 variable.EmitAssign (ec, conv);
5457 variable.EmitAssign (ec, conv, fb);
5459 statement.Emit (ec);
5461 ig.MarkLabel (ec.LoopBegin);
5462 ig.Emit (OpCodes.Ldloc, counter);
5463 ig.Emit (OpCodes.Ldc_I4_1);
5464 ig.Emit (OpCodes.Add);
5465 ig.Emit (OpCodes.Stloc, counter);
5467 ig.MarkLabel (test);
5468 ig.Emit (OpCodes.Ldloc, counter);
5469 ig.Emit (OpCodes.Ldloc, copy);
5470 ig.Emit (OpCodes.Ldlen);
5471 ig.Emit (OpCodes.Conv_I4);
5472 ig.Emit (OpCodes.Blt, loop);
5474 LocalBuilder [] dim_len = new LocalBuilder [rank];
5475 LocalBuilder [] dim_count = new LocalBuilder [rank];
5476 Label [] loop = new Label [rank];
5477 Label [] test = new Label [rank];
5480 for (dim = 0; dim < rank; dim++){
5481 dim_len [dim] = ig.DeclareLocal (TypeManager.int32_type);
5482 dim_count [dim] = ig.DeclareLocal (TypeManager.int32_type);
5483 test [dim] = ig.DefineLabel ();
5484 loop [dim] = ig.DefineLabel ();
5487 for (dim = 0; dim < rank; dim++){
5488 ig.Emit (OpCodes.Ldloc, copy);
5489 IntLiteral.EmitInt (ig, dim);
5490 ig.Emit (OpCodes.Callvirt, TypeManager.int_getlength_int);
5491 ig.Emit (OpCodes.Stloc, dim_len [dim]);
5494 for (dim = 0; dim < rank; dim++){
5495 ig.Emit (OpCodes.Ldc_I4_0);
5496 ig.Emit (OpCodes.Stloc, dim_count [dim]);
5497 ig.Emit (OpCodes.Br, test [dim]);
5498 ig.MarkLabel (loop [dim]);
5501 ig.Emit (OpCodes.Ldloc, copy);
5502 for (dim = 0; dim < rank; dim++)
5503 ig.Emit (OpCodes.Ldloc, dim_count [dim]);
5506 // FIXME: Maybe we can cache the computation of 'get'?
5508 Type [] args = new Type [rank];
5511 for (int i = 0; i < rank; i++)
5512 args [i] = TypeManager.int32_type;
5514 ModuleBuilder mb = CodeGen.ModuleBuilder;
5515 get = mb.GetArrayMethod (
5517 CallingConventions.HasThis| CallingConventions.Standard,
5519 ig.Emit (OpCodes.Call, get);
5520 variable.EmitAssign (ec, conv);
5521 statement.Emit (ec);
5522 ig.MarkLabel (ec.LoopBegin);
5523 for (dim = rank - 1; dim >= 0; dim--){
5524 ig.Emit (OpCodes.Ldloc, dim_count [dim]);
5525 ig.Emit (OpCodes.Ldc_I4_1);
5526 ig.Emit (OpCodes.Add);
5527 ig.Emit (OpCodes.Stloc, dim_count [dim]);
5529 ig.MarkLabel (test [dim]);
5530 ig.Emit (OpCodes.Ldloc, dim_count [dim]);
5531 ig.Emit (OpCodes.Ldloc, dim_len [dim]);
5532 ig.Emit (OpCodes.Blt, loop [dim]);
5535 ig.MarkLabel (ec.LoopEnd);
5540 protected override bool DoEmit (EmitContext ec)
5544 ILGenerator ig = ec.ig;
5546 Label old_begin = ec.LoopBegin, old_end = ec.LoopEnd;
5547 bool old_inloop = ec.InLoop;
5548 int old_loop_begin_try_catch_level = ec.LoopBeginTryCatchLevel;
5549 ec.LoopBegin = ig.DefineLabel ();
5550 ec.LoopEnd = ig.DefineLabel ();
5552 ec.LoopBeginTryCatchLevel = ec.TryCatchLevel;
5555 ret_val = EmitCollectionForeach (ec);
5557 ret_val = EmitArrayForeach (ec);
5559 ec.LoopBegin = old_begin;
5560 ec.LoopEnd = old_end;
5561 ec.InLoop = old_inloop;
5562 ec.LoopBeginTryCatchLevel = old_loop_begin_try_catch_level;
5569 /// AddHandler statement
5571 public class AddHandler : Statement {
5573 Expression EvtHandler;
5576 // keeps track whether EvtId is already resolved
5580 public AddHandler (Expression evt_id, Expression evt_handler, Location l)
5583 EvtHandler = Parser.SetAddressOf (evt_handler);
5586 //Console.WriteLine ("Adding handler '" + evt_handler + "' for Event '" + evt_id +"'");
5589 public override bool Resolve (EmitContext ec)
5592 // if EvetId is of EventExpr type that means
5593 // this is already resolved
5595 if (EvtId is EventExpr) {
5600 EvtId = EvtId.Resolve(ec);
5601 EvtHandler = EvtHandler.Resolve(ec,ResolveFlags.MethodGroup);
5602 if (EvtId == null || (!(EvtId is EventExpr))) {
5603 Report.Error (30676, "Need an event designator.");
5607 if (EvtHandler == null)
5609 Report.Error (999, "'AddHandler' statement needs an event handler.");
5616 protected override bool DoEmit (EmitContext ec)
5619 // Already resolved and emitted don't do anything
5625 ArrayList args = new ArrayList();
5626 Argument arg = new Argument (EvtHandler, Argument.AType.Expression);
5631 // The even type was already resolved to a delegate, so
5632 // we must un-resolve its name to generate a type expression
5633 string ts = (EvtId.Type.ToString()).Replace ('+','.');
5634 Expression dtype = Mono.MonoBASIC.Parser.DecomposeQI (ts, Location.Null);
5636 // which we can use to declare a new event handler
5638 d = new New (dtype, args, Location.Null);
5640 e = new CompoundAssign(Binary.Operator.Addition, EvtId, d, Location.Null);
5642 // we resolve it all and emit the code
5655 /// RemoveHandler statement
5657 public class RemoveHandler : Statement
\r
5660 Expression EvtHandler;
5662 public RemoveHandler (Expression evt_id, Expression evt_handler, Location l)
5665 EvtHandler = Parser.SetAddressOf (evt_handler);
5669 public override bool Resolve (EmitContext ec)
5671 EvtId = EvtId.Resolve(ec);
5672 EvtHandler = EvtHandler.Resolve(ec,ResolveFlags.MethodGroup);
5673 if (EvtId == null || (!(EvtId is EventExpr)))
\r
5675 Report.Error (30676, "Need an event designator.");
5679 if (EvtHandler == null)
5681 Report.Error (999, "'AddHandler' statement needs an event handler.");
5687 protected override bool DoEmit (EmitContext ec)
5690 ArrayList args = new ArrayList();
5691 Argument arg = new Argument (EvtHandler, Argument.AType.Expression);
5694 // The even type was already resolved to a delegate, so
5695 // we must un-resolve its name to generate a type expression
5696 string ts = (EvtId.Type.ToString()).Replace ('+','.');
5697 Expression dtype = Mono.MonoBASIC.Parser.DecomposeQI (ts, Location.Null);
5699 // which we can use to declare a new event handler
5701 d = new New (dtype, args, Location.Null);
5704 e = new CompoundAssign(Binary.Operator.Subtraction, EvtId, d, Location.Null);
5706 // we resolve it all and emit the code
5718 public class RedimClause {
5719 private Expression RedimTarget;
5720 private ArrayList NewIndexes;
5721 private Expression AsType;
5723 private LocalTemporary localTmp = null;
5724 private Expression origRedimTarget = null;
5725 private StatementExpression ReDimExpr;
5727 public RedimClause (Expression e, ArrayList args, Expression e_as)
5729 if (e is SimpleName)
5730 ((SimpleName) e).IsInvocation = false;
5731 if (e is MemberAccess)
5732 ((MemberAccess) e).IsInvocation = false;
5739 public bool Resolve (EmitContext ec, bool Preserve, Location loc)
5741 RedimTarget = RedimTarget.Resolve (ec);
5743 if (AsType != null) {
5744 Report.Error (30811, loc, "'ReDim' statements can no longer be used to declare array variables");
5748 if (!RedimTarget.Type.IsArray) {
5749 Report.Error (49, loc, "'ReDim' statement requires an array");
5753 ArrayList args = new ArrayList();
5754 foreach (Argument a in NewIndexes) {
5755 if (a.Resolve(ec, loc))
5759 for (int x = 0; x < args.Count; x++) {
5760 args[x] = new Binary (Binary.Operator.Addition,
5761 (Expression) args[x], new IntLiteral (1), Location.Null);
5765 if (RedimTarget.Type.GetArrayRank() != NewIndexes.Count) {
5766 Report.Error (30415, loc, "'ReDim' cannot change the number of dimensions of an array.");
5770 Type BaseType = RedimTarget.Type.GetElementType();
5771 Expression BaseTypeExpr = MonoBASIC.Parser.DecomposeQI(BaseType.FullName.ToString(), Location.Null);
5772 ArrayCreation acExpr = new ArrayCreation (BaseTypeExpr, NewIndexes, "", null, Location.Null);
5775 ExpressionStatement PreserveExpr = null;
5776 if (RedimTarget is PropertyGroupExpr) {
5777 localTmp = new LocalTemporary (ec, RedimTarget.Type);
5778 PropertyGroupExpr pe = RedimTarget as PropertyGroupExpr;
5779 origRedimTarget = new PropertyGroupExpr (pe.Properties, pe.Arguments, pe.InstanceExpression, loc);
5780 if ((origRedimTarget = origRedimTarget.Resolve (ec)) == null) {
5781 Report.Error (-1, loc, "'ReDim' vs PropertyGroup");
5784 PreserveExpr = (ExpressionStatement) new Preserve(localTmp, acExpr, loc);
5786 PreserveExpr = (ExpressionStatement) new Preserve(RedimTarget, acExpr, loc);
5787 ReDimExpr = (StatementExpression) new StatementExpression ((ExpressionStatement) new Assign (RedimTarget, PreserveExpr, loc), loc);
5790 ReDimExpr = (StatementExpression) new StatementExpression ((ExpressionStatement) new Assign (RedimTarget, acExpr, loc), loc);
5791 ReDimExpr.Resolve(ec);
5795 public void DoEmit (EmitContext ec)
5797 if (ReDimExpr == null)
5800 if (localTmp != null && origRedimTarget != null) {
5801 origRedimTarget.Emit (ec);
5802 localTmp.Store (ec);
5809 public class ReDim : Statement {
5810 ArrayList RedimTargets;
5813 public ReDim (ArrayList targets, bool opt_preserve, Location l)
5816 RedimTargets = targets;
5817 Preserve = opt_preserve;
5820 public override bool Resolve (EmitContext ec)
5823 foreach (RedimClause rc in RedimTargets)
5824 result = rc.Resolve(ec, Preserve, loc) && result;
5828 protected override bool DoEmit (EmitContext ec)
5830 foreach (RedimClause rc in RedimTargets)
5837 public class Erase : Statement {
5838 Expression EraseTarget;
5840 private StatementExpression EraseExpr;
5842 public Erase (Expression expr, Location l)
5848 public override bool Resolve (EmitContext ec)
5850 EraseTarget = EraseTarget.Resolve (ec);
5851 if (!EraseTarget.Type.IsArray)
5852 Report.Error (49, "'Erase' statement requires an array");
5854 EraseExpr = (StatementExpression) new StatementExpression ((ExpressionStatement) new Assign (EraseTarget, NullLiteral.Null, loc), loc);
5855 EraseExpr.Resolve(ec);
5860 protected override bool DoEmit (EmitContext ec)