コード例 #1
0
        public override void VisitTryStatement(TryStatementSyntax node)
        {
            if (!YieldChecker.HasSpecialStatement(node))
            {
                currentState.Add(StateMachineThisFixer.Fix(node));
            }
            else
            {
                if (node.Catches.Any())
                {
                    throw new Exception("Yield statements cannot be contained inside try/catch blocks.");
                }

                var nextState = GetNextState(node);

                MaybeCreateNewState();

                var tryState = currentState;
                tryState.NextState = nextState;

                var exceptionName = SyntaxFactory.Identifier("_ex" + exceptionNameCounter++);
                var finallyState  = new State(this)
                {
                    NextState = nextState, BreakState = nextState
                };
                foreach (var finallyStatement in node.Finally.Block.Statements)
                {
                    finallyState.Add(finallyStatement);
                }
                finallyState.Add(Cs.If(Cs.This().Member(exceptionName).NotEqualTo(Cs.Null()), Cs.Throw(Cs.This().Member(exceptionName))));
                Close(finallyState);

                node = (TryStatementSyntax)HoistVariable(node, exceptionName, SyntaxFactory.ParseTypeName("System.Exception"));

                tryState.NextState = finallyState;
                tryState.Germ      = yieldState =>
                {
                    var gotoFinally = SyntaxFactory.Block(
                        Cs.Express(Cs.This().Member(exceptionName).Assign(SyntaxFactory.IdentifierName(exceptionName))),
                        ChangeState(finallyState),
                        GotoTop()
                        );

                    var statements = yieldState.Statements.ToArray();
                    yieldState.Statements.Clear();
                    yieldState.Statements.Add(Cs.Try().WithBlock(Cs.Block(statements)).WithCatches(SyntaxFactory.List(new[] {
                        SyntaxFactory.CatchClause(SyntaxFactory.CatchDeclaration(SyntaxFactory.ParseTypeName("System.Exception"), exceptionName), null, gotoFinally)
                    })));
                };

                node.Block.Accept(this);

                if (!tryState.IsClosed)
                {
                    CloseTo(tryState, finallyState);
                }

                currentState = nextState;
            }
        }