private static SyntaxNode CalculateNewRoot(SyntaxNode root, SyntaxNode currentNode, TryStatementSyntax tryStatement)
        {
            var isTryRemovable = tryStatement.Catches.Count == 1 && tryStatement.Finally == null;

            return isTryRemovable
                ? root.ReplaceNode(
                    tryStatement,
                    tryStatement.Block.Statements.Select(st => st.WithAdditionalAnnotations(Formatter.Annotation)))
                : root.RemoveNode(currentNode, SyntaxRemoveOptions.KeepNoTrivia);
        }
 private static CodeAction CreateActionWithRemovedTryStatement(CodeFixContext context, SyntaxNode root, TryStatementSyntax tryStatement)
 {
     return CodeAction.Create(
         Title,
         c =>
         {
             var newRoot = root.ReplaceNode(tryStatement, tryStatement.Block.Statements)
                 .WithAdditionalAnnotations(Formatter.Annotation);
             return Task.FromResult(context.Document.WithSyntaxRoot(newRoot));
         });
 }
        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;            
            }
        }
Example #4
0
 public static CatchClauseSyntax GetFirstCatchClauseByType(this TryStatementSyntax parentTryStatement, SemanticModel semanticModel, Type exceptionType, CancellationToken cancellationToken = default(CancellationToken))
 {
     foreach (var e in parentTryStatement.Catches)
     {
         var errorType = semanticModel.GetTypeInfo(e.Declaration.Type, cancellationToken).Type as INamedTypeSymbol;
         if (errorType == null)
         {
             continue;
         }
         var fullName = errorType.ToDisplayString(SymbolDisplayFormat);
         if (exceptionType.FullName.Contains(fullName))
         {
             return(e);
         }
     }
     return(null);
 }
Example #5
0
        public static void Go(OutputWriter writer, TryStatementSyntax tryStatement)
        {
            writer.WriteLine("try");
            Core.Write(writer, tryStatement.Block);

            var catches = tryStatement.Catches.Where(o => Program.DoNotWrite.ContainsKey(o) == false).ToList();

            if (catches.Count > 0)
            {
                foreach (var catchClause in catches)
                {
                    if (catchClause.Declaration == null)
                    {
                        writer.WriteLine("catch(Exception __ex)");
                    }
                    else
                    {
                        writer.WriteLine("catch(" + TypeProcessor.ConvertType(catchClause.Declaration.Type) + " " +
                                         (string.IsNullOrWhiteSpace(catchClause.Declaration.Identifier.Text)
                                             ? "__ex"
                                             : WriteIdentifierName.TransformIdentifier(
                                              catchClause.Declaration.Identifier.Text)) + ")");
                    }
                    writer.OpenBrace();

                    Core.WriteBlock(writer, catchClause.Block, false);
                    //                    foreach (var statement in catchClause.Block.Statements)
                    //                        Core.Write(writer, statement);
                    writer.CloseBrace();
                }
            }

            if (tryStatement.Finally != null)
            {
                writer.WriteLine("finally");
                //                Core.Write(writer, tryStatement.Finally.Block);

                writer.OpenBrace();

                Core.WriteBlock(writer, tryStatement.Finally.Block, false);
                //                    foreach (var statement in catchClause.Block.Statements)
                //                        Core.Write(writer, statement);
                writer.CloseBrace();
            }
        }
Example #6
0
        public override void VisitTryStatement(TryStatementSyntax node)
        {
            _returningFromCx.Push(new HashSet <int>());
            Visit(node.Block);

            var allCatchesOrEmpty = node.Catches.Cast <SyntaxNode>().ToList();

            allCatchesOrEmpty.Add(SyntaxFactory.EmptyStatement());
            RecordNodesInParallel(allCatchesOrEmpty);

            var returnedFrom = _returningFromCx.Pop();

            _currentPathParents.UnionWith(returnedFrom);
            if (node.Finally != null)
            {
                Visit(node.Finally);
            }
        }
Example #7
0
        public override void VisitTryStatement(TryStatementSyntax node)
        {
            var catchesHandlers =
                node.Catches.Select <CatchClauseSyntax, Action>(
                    catchClause => (() =>
            {
                var catchDeclaration = catchClause.Declaration;
                if (catchDeclaration != null)          // you may use "catch { .. }" without a declaration
                {
                    RecordVariableDeclaration(catchDeclaration, catchDeclaration.Identifier.ValueText,
                                              catchDeclaration, false);
                }
                Visit(catchClause.Block);
            }));

            HandleParallelBlocks(new Action[] { () => Visit(node.Block) }.Concat(catchesHandlers));
            Visit(node.Finally);
        }
Example #8
0
        public static Doc Print(TryStatementSyntax node)
        {
            var docs = new List <Doc>
            {
                ExtraNewLines.Print(node),
                AttributeLists.Print(node, node.AttributeLists),
                Token.Print(node.TryKeyword),
                Block.Print(node.Block),
                Doc.HardLine,
                Doc.Join(Doc.HardLine, node.Catches.Select(CatchClause.Print))
            };

            if (node.Finally != null)
            {
                docs.Add(Doc.HardLine, FinallyClause.Print(node.Finally));
            }
            return(Doc.Concat(docs));
        }
Example #9
0
        public override void VisitTryStatement(TryStatementSyntax node)
        {
            if (null != node.Block)
            {
                string retVar     = string.Format("__compiler_try_ret_{0}", GetSourcePosForVar(node));
                string errVar     = string.Format("__compiler_try_err_{0}", GetSourcePosForVar(node));
                string handledVar = string.Format("__compiler_try_handled_{0}", GetSourcePosForVar(node));

                CodeBuilder.AppendFormat("{0}local {1}, {2} = luatry((function()", GetIndentString(), retVar, errVar);
                CodeBuilder.AppendLine();
                ++m_Indent;
                VisitBlock(node.Block);
                --m_Indent;
                CodeBuilder.AppendFormat("{0}end));", GetIndentString());
                CodeBuilder.AppendLine();

                if (node.Catches.Count > 0)
                {
                    CodeBuilder.AppendFormat("{0}local {1} = false;", GetIndentString(), handledVar);
                    CodeBuilder.AppendLine();
                    foreach (var clause in node.Catches)
                    {
                        CodeBuilder.AppendFormat("{0}{1} = luacatch({1}, {2}, {3},", GetIndentString(), handledVar, retVar, errVar);
                        CodeBuilder.AppendLine();
                        ++m_Indent;
                        VisitCatchClause(clause);
                        --m_Indent;
                        CodeBuilder.AppendFormat("{0});", GetIndentString());
                        CodeBuilder.AppendLine();
                    }
                    if (node.Catches.Count > 1)
                    {
                        if (SymbolTable.EnableTranslationCheck)
                        {
                            Logger.Instance.Log("Translation Warning", "try have multiple catch ! location: {0}", GetSourcePosForLog(node));
                        }
                    }
                }
            }
            if (null != node.Finally)
            {
                VisitFinallyClause(node.Finally);
            }
        }
        public static void Go(OutputWriter writer, TryStatementSyntax tryStatement)
        {
            writer.WriteLine("try");
            Core.Write(writer, tryStatement.Block);

            var catches = tryStatement.Catches.Where(o => Program.DoNotWrite.ContainsKey(o) == false).ToList();

            if (catches.Count > 0)
            {
                foreach (var catchClause in catches)
                {
                    if (catchClause.Declaration == null)
                        writer.WriteLine("catch(Exception __ex)");
                    else
                    {
                        writer.WriteLine("catch(" + TypeProcessor.ConvertType(catchClause.Declaration.Type) + " " +
                                         (string.IsNullOrWhiteSpace(catchClause.Declaration.Identifier.Text)
                                             ? "__ex"
                                             : WriteIdentifierName.TransformIdentifier(
                                                 catchClause.Declaration.Identifier.Text)) + ")");
                    }
                    writer.OpenBrace();

                    Core.WriteBlock(writer, catchClause.Block, false);
                    //                    foreach (var statement in catchClause.Block.Statements)
                    //                        Core.Write(writer, statement);
                    writer.CloseBrace();
                }
            }

            if (tryStatement.Finally != null)
            {
                writer.WriteLine("finally");
                //                Core.Write(writer, tryStatement.Finally.Block);

                writer.OpenBrace();

                Core.WriteBlock(writer, tryStatement.Finally.Block, false);
                //                    foreach (var statement in catchClause.Block.Statements)
                //                        Core.Write(writer, statement);
                writer.CloseBrace();
            }
        }
Example #11
0
        public override void VisitTryStatement(TryStatementSyntax node)
        {
            if (!PreVisit(node))
            {
                return;
            }

            node.Block.Accept(this);
            foreach (CatchClauseSyntax clauseSyntax in node.Catches)
            {
                clauseSyntax.Accept(this);
            }

            node.Finally?.Accept(this);

            base.VisitTryStatement(node);

            PostVisit(node);
        }
Example #12
0
        public override void VisitTryStatement(TryStatementSyntax node)
        {
            if (null != node.Block)
            {
                MethodInfo mi = m_MethodInfoStack.Peek();

                string retVar     = string.Format("__try_ret_{0}", GetSourcePosForVar(node));
                string errVar     = string.Format("__try_err_{0}", GetSourcePosForVar(node));
                string handledVar = string.Format("__try_handled_{0}", GetSourcePosForVar(node));

                CodeBuilder.AppendFormat("{0}local({1}, {2}); multiassign({1}, {2}) = dsltry(function(){{", GetIndentString(), retVar, errVar);
                CodeBuilder.AppendLine();
                ++m_Indent;
                ++mi.TryCatchLayer;
                VisitBlock(node.Block);
                --mi.TryCatchLayer;
                --m_Indent;
                CodeBuilder.AppendFormat("{0}}});", GetIndentString());
                CodeBuilder.AppendLine();

                if (node.Catches.Count > 0)
                {
                    CodeBuilder.AppendFormat("{0}local({1}); {1} = false;", GetIndentString(), handledVar);
                    CodeBuilder.AppendLine();
                    foreach (var clause in node.Catches)
                    {
                        CodeBuilder.AppendFormat("{0}{1} = dslcatch({1}, {2}, {3},", GetIndentString(), handledVar, retVar, errVar);
                        CodeBuilder.AppendLine();
                        ++m_Indent;
                        ++mi.TryCatchLayer;
                        VisitCatchClause(clause);
                        --mi.TryCatchLayer;
                        --m_Indent;
                        CodeBuilder.AppendFormat("{0});", GetIndentString());
                        CodeBuilder.AppendLine();
                    }
                }
            }
            if (null != node.Finally)
            {
                VisitFinallyClause(node.Finally);
            }
        }
Example #13
0
        public override SyntaxNode VisitTryStatement(TryStatementSyntax node)
        {
            // Goal: Inject instruction counter, but also inject an auto catcher for all exceptions that have been marked
            // as unblockable in the compiler.

            var blockResumeLocation     = GetBlockResumeLocation(node.Block);
            var successiveBlockLocation = GetBlockResumeLocation((SyntaxNode)node.Catches.FirstOrDefault() ?? node.Finally);
            var catchClauseLocations    = node.Catches.Select(c => GetBlockResumeLocation(c.Block)).ToArray();
            var finallyLocation         = node.Finally != null?GetBlockResumeLocation(node.Finally.Block) : new FileLinePositionSpan();

            node = (TryStatementSyntax)base.VisitTryStatement(node);

            node = node.WithBlock(InjectedBlock(node.Block, blockResumeLocation));

            var catches = new SyntaxList <CatchClauseSyntax>();

            foreach (var exceptionType in m_compiler.UnblockableIngameExceptions)
            {
                catches = catches.Add(Barricaded(successiveBlockLocation.Path, successiveBlockLocation.StartLinePosition, SyntaxFactory.CatchClause(
                                                     SyntaxFactory.CatchDeclaration(AnnotatedIdentifier(exceptionType.FullName)),
                                                     null,
                                                     SyntaxFactory.Block(
                                                         SyntaxFactory.ThrowStatement())
                                                     )));
            }

            for (var i = 0; i < node.Catches.Count; i++)
            {
                var catchClause    = node.Catches[i];
                var resumeLocation = catchClauseLocations[i];
                catches = catches.Add(catchClause.WithBlock(InjectedBlock(catchClause.Block, resumeLocation)));
            }

            node = node.WithCatches(catches);

            if (node.Finally != null)
            {
                node = node.WithFinally(node.Finally.WithBlock(InjectedBlock(node.Finally.Block, finallyLocation)));
            }

            return(node);
        }
Example #14
0
        public override UstNode VisitTryStatement(TryStatementSyntax node)
        {
            var tryBlock     = (BlockStatement)VisitBlock(node.Block);
            var catchClauses = node.Catches.Select(c => (CatchClause)VisitAndReturnNullIfError(c))
                               .ToList();
            BlockStatement finallyStatement = null;

            if (node.Finally != null)
            {
                finallyStatement = (BlockStatement)VisitFinallyClause(node.Finally);
            }

            var result = new TryCatchStatement(tryBlock, node.GetTextSpan(), FileNode)
            {
                CatchClauses = catchClauses,
                FinallyBlock = finallyStatement
            };

            return(result);
        }
Example #15
0
        private static SyntaxNode GetNewRoot(SyntaxNode oldRoot, FinallyClauseSyntax finallyClause)
        {
            if (finallyClause.GetLeadingTrivia().All(f => f.IsWhitespaceOrEndOfLineTrivia()))
            {
                var tryStatement = (TryStatementSyntax)finallyClause.Parent;

                CatchClauseSyntax lastCatch = tryStatement.Catches[tryStatement.Catches.Count - 1];

                if (lastCatch.GetTrailingTrivia().All(f => f.IsWhitespaceOrEndOfLineTrivia()))
                {
                    TryStatementSyntax newTryStatement = tryStatement
                                                         .WithCatches(tryStatement.Catches.Replace(lastCatch, lastCatch.WithTrailingTrivia(finallyClause.GetTrailingTrivia())))
                                                         .WithFinally(null);

                    return(oldRoot.ReplaceNode(tryStatement, newTryStatement));
                }
            }

            return(oldRoot.RemoveNode(finallyClause, SyntaxRemoveOptions.KeepExteriorTrivia));
        }
Example #16
0
        private CatchClause AnalyzeCatchClause(TryStatementSyntax tryStatementSyntax, CatchClauseSyntax catchClauseSyntax, AnalyzeContext context)
        {
            var catchClause = new CatchClause();

            catchClause.HasIdentifier = catchClauseSyntax.Declaration?.Identifier.Kind() != SyntaxKind.None;
            if (catchClauseSyntax.Declaration?.Type != null)
            {
                catchClause.ExceptionType = context.DocumentSemanticModel
                                            .GetTypeInfo(catchClauseSyntax.Declaration.Type)
                                            .Type
                                            ?.Name;
            }

            catchClause.StatementsCount = catchClauseSyntax.Block.Statements.Count;

            catchClause.Comments = catchClauseSyntax
                                   .DescendantTrivia()
                                   .Where(s => s.Kind() == SyntaxKind.SingleLineCommentTrivia ||
                                          s.Kind() == SyntaxKind.MultiLineCommentTrivia)
                                   .OfType <SyntaxTrivia>()
                                   .Select(s => s.ToString())
                                   .ToArray();

            var invocationExpressions = catchClauseSyntax.Block?.DescendantNodes()
                                        .OfType <InvocationExpressionSyntax>();

            var identifiers = invocationExpressions
                              .SelectMany(n => n.DescendantNodes().OfType <IdentifierNameSyntax>());

            catchClause.ContainsLog = identifiers.Any(n => n.Identifier.ValueText.ToLower().Contains("log") ||
                                                      n.Identifier.ValueText.ToLower().Contains("WriteLine"));


            catchClause.RuleViolations = new CatchClauseComments().AnalyzeSyntaxNode(catchClauseSyntax)
                                         .Concat(new CatchClauseEmptyBody().AnalyzeSyntaxNode(catchClauseSyntax))
                                         .Concat(new CatchClauseGeneralExceptionAnalyzer().AnalyzeSyntaxNode(catchClauseSyntax))
                                         .Concat(new CatchClauseLosingStackTraceThrows().AnalyzeSyntaxNode(catchClauseSyntax))
                                         .Concat(new CatchClauseNoDeclaration().AnalyzeSyntaxNode(catchClauseSyntax));

            return(catchClause);
        }
Example #17
0
        public AnalyzeContext AnalyzeTryStatements(TryStatementSyntax tryStatementSyntax)
        {
            var tryContext = new AnalyzeContext(Project, Document);

            var tryStatement = new TryStatement();

            tryContext.Node         = tryStatementSyntax;
            tryContext.TryStatement = tryStatement;

            var(@class, declaration) = GetPlaceOfTryStatement(tryStatementSyntax, tryContext);
            tryContext.Class         = @class;
            tryContext.Declaration   = declaration;

            tryStatement.CatchClauses  = AnalyzeCatchClauses(tryStatementSyntax, tryContext);
            tryStatement.FinallyClause = AnalyzeFinallyClause(tryStatementSyntax, tryContext);

            RuleViolations.AddRange(tryContext.TryStatement.CatchClauses.SelectMany(c => c.RuleViolations));
            AnalyzedContexts.Add(tryContext);

            return(tryContext);
        }
Example #18
0
        private Doc PrintTryStatementSyntax(TryStatementSyntax node)
        {
            var parts = new Parts();

            parts.Push(this.PrintExtraNewLines(node));
            parts.Push(this.PrintAttributeLists(node, node.AttributeLists));
            parts.Push(
                this.PrintSyntaxToken(node.TryKeyword),
                this.PrintBlockSyntax(node.Block),
                HardLine,
                Join(HardLine, node.Catches.Select(this.PrintCatchClauseSyntax))
                );
            if (node.Finally != null)
            {
                parts.Push(
                    HardLine,
                    this.PrintFinallyClauseSyntax(node.Finally)
                    );
            }
            return(Concat(parts));
        }
Example #19
0
 public override void VisitTryStatement(TryStatementSyntax node)
 {
     if (null != node.Block)
     {
         CodeBuilder.AppendFormat("{0}do", GetIndentString());
         CodeBuilder.AppendLine();
         ++m_Indent;
         VisitBlock(node.Block);
         --m_Indent;
         CodeBuilder.AppendFormat("{0}end;", GetIndentString());
         CodeBuilder.AppendLine();
     }
     foreach (var clause in node.Catches)
     {
         VisitCatchClause(clause);
     }
     if (null != node.Finally)
     {
         VisitFinallyClause(node.Finally);
     }
 }
            public override SyntaxNode VisitMethodDeclaration(MethodDeclarationSyntax node)
            {
                var visitedNode = (MethodDeclarationSyntax)base.VisitMethodDeclaration(node);

                if (_semanticModel.GetTypeInfo(node.ReturnType).Type is INamedTypeSymbol type &&
                    type.ConstructedFrom.Equals(_taskTypeSymbol) &&
                    type.TypeArguments[0] is INamedTypeSymbol argumentType &&
                    argumentType.IsGenericType &&
                    _returnTypeSymbols.Contains(argumentType.ConstructedFrom))
                {
                    visitedNode = visitedNode.AddModifiers(Token(SyntaxKind.AsyncKeyword));

                    var invocation = visitedNode.DescendantNodes().OfType <InvocationExpressionSyntax>().First();

                    TryStatementSyntax tryStatementSyntax = TryStatement(
                        Block(ReturnStatement(AwaitExpression(invocation))),
                        SingletonList <CatchClauseSyntax>(
                            CatchClause()
                            .WithDeclaration(
                                CatchDeclaration(
                                    IdentifierName("System.Exception"))
                                .WithIdentifier(
                                    Identifier("ex")))
                            .WithBlock(
                                Block(
                                    SeparatedList <StatementSyntax>(
                                        new StatementSyntax[]
                    {
                        ExpressionStatement(InvocationExpression(IdentifierName("ProcessException")).AddArgumentListArguments(Argument(IdentifierName("ex")))),
                        ThrowStatement(),
                    })))),
                        null);

                    visitedNode = visitedNode.WithBody(Block(tryStatementSyntax));

                    return(visitedNode);
                }

                return(visitedNode);
            }
Example #21
0
        public void Test_Profile()
        {
            // turn on profiling
            FunctionModel isIntEvenFunction = CreateIsIntEvenFunction();

            // enable profiling for this function
            isIntEvenFunction.EnableProfiling = true;

            // needed to set the owning function of each stack
            new PortInitializationTraversal().VisitGraph(GraphModel);

            // compile graph
            var        roslynTr = new RoslynTranslator(Stencil);
            var        ast      = roslynTr.Translate(GraphModel, CompilationOptions.Profiling);
            SyntaxNode astRoot  = ast.GetRoot();

            // check there's only one IsIntEven method
            IEnumerable <MethodDeclarationSyntax> methods = astRoot.DescendantNodes().OfType <MethodDeclarationSyntax>().ToList();

            Assert.That(methods.Count, Is.EqualTo(1));
            MethodDeclarationSyntax method = methods.First();

            // check there's only a CustomSampler declaration and then a try/finally statement including everything
            BlockSyntax body = method.Body;

            Assert.That(body.Statements.Count, Is.EqualTo(2));
            StatementSyntax statement1 = body.Statements[0];

            Assert.That(statement1, Is.TypeOf(typeof(LocalDeclarationStatementSyntax)));

            StatementSyntax statement2 = body.Statements[1];

            Assert.That(statement2, Is.TypeOf(typeof(TryStatementSyntax)));

            TryStatementSyntax tryStatement = (TryStatementSyntax)statement2;

            // check that there is code inside the try and finally statements
            Assert.That(tryStatement.Block.Statements.Count, Is.GreaterThan(0));
            Assert.That(tryStatement.Finally.Block.Statements.Count, Is.GreaterThan(0));
        }
Example #22
0
            public AwaitCatchFrame(
                SyntheticBoundNodeFactory F,
                TryStatementSyntax tryStatementSyntax
                )
            {
                this.pendingCaughtException = new SynthesizedLocal(
                    F.CurrentFunction,
                    TypeWithAnnotations.Create(F.SpecialType(SpecialType.System_Object)),
                    SynthesizedLocalKind.TryAwaitPendingCaughtException,
                    tryStatementSyntax
                    );
                this.pendingCatch = new SynthesizedLocal(
                    F.CurrentFunction,
                    TypeWithAnnotations.Create(F.SpecialType(SpecialType.System_Int32)),
                    SynthesizedLocalKind.TryAwaitPendingCatch,
                    tryStatementSyntax
                    );

                this.handlers         = new List <BoundBlock>();
                _hoistedLocals        = new Dictionary <LocalSymbol, LocalSymbol>();
                _orderedHoistedLocals = new List <LocalSymbol>();
            }
        private static TryStatementSyntax addCatches(ConversionContext context, CatchClause ctch,
                                                     string typeName, TryStatementSyntax trySyn)
        {
            var block            = ctch.getCatchBlock();
            var catchStatements  = block.getStmts().ToList <Statement>();
            var catchConverted   = StatementVisitor.VisitStatements(context, catchStatements);
            var catchBlockSyntax = SyntaxFactory.Block(catchConverted);

            var type = TypeHelper.ConvertType(typeName);

            trySyn = trySyn.AddCatches(
                SyntaxFactory.CatchClause(
                    SyntaxFactory.CatchDeclaration(
                        SyntaxFactory.ParseTypeName(type),
                        SyntaxFactory.ParseToken(ctch.getParam().getId().toString())
                        ),
                    filter: null,
                    block: catchBlockSyntax
                    )
                );
            return(trySyn);
        }
            public override void VisitTryStatement(TryStatementSyntax node)
            {
                BlockSyntax block = node.Block;

                if (block != null)
                {
                    _usingOrTryStatementDepth++;
                    VisitBlock(block);
                    _usingOrTryStatementDepth--;
                }

                foreach (CatchClauseSyntax catchClause in node.Catches)
                {
                    VisitCatchClause(catchClause);
                }

                FinallyClauseSyntax finallyClause = node.Finally;

                if (finallyClause != null)
                {
                    VisitFinallyClause(finallyClause);
                }
            }
Example #25
0
        private static async Task <Document> RemoveEmptyFinallyClauseAsync(
            Document document,
            FinallyClauseSyntax finallyClause,
            CancellationToken cancellationToken)
        {
            var tryStatement = (TryStatementSyntax)finallyClause.Parent;

            SyntaxList <CatchClauseSyntax> catches = tryStatement.Catches;

            if (catches.Any())
            {
                if (finallyClause.GetLeadingTrivia().IsEmptyOrWhitespace())
                {
                    CatchClauseSyntax lastCatch = catches.Last();

                    if (lastCatch.GetTrailingTrivia().IsEmptyOrWhitespace())
                    {
                        TryStatementSyntax newTryStatement = tryStatement
                                                             .WithCatches(catches.Replace(lastCatch, lastCatch.WithTrailingTrivia(finallyClause.GetTrailingTrivia())))
                                                             .WithFinally(null);

                        return(await document.ReplaceNodeAsync(tryStatement, newTryStatement, cancellationToken).ConfigureAwait(false));
                    }
                }

                return(await document.RemoveNodeAsync(finallyClause, SyntaxRemoveOptions.KeepExteriorTrivia, cancellationToken).ConfigureAwait(false));
            }
            else
            {
                IEnumerable <StatementSyntax> newNodes = tryStatement
                                                         .Block
                                                         .Statements
                                                         .Select(f => f.WithFormatterAnnotation());

                return(await document.ReplaceNodeAsync(tryStatement, newNodes, cancellationToken).ConfigureAwait(false));
            }
        }
Example #26
0
        private void RunTry(TryStatementSyntax node)
        {
            bool hasCatches = node.Catches.Count > 0;

            if (hasCatches)
            {
                Catches.Push(new CatchFrame(this, node));
            }
            try
            {
                RunBlock(node.Block);
            }
            finally
            {
                if (node.Finally != null)
                {
                    Run(node.Finally.Block);
                }
            }
            if (hasCatches)
            {
                Catches.Pop();
            }
        }
        public static async Task <Document> RefactorAsync(
            Document document,
            FinallyClauseSyntax finallyClause,
            CancellationToken cancellationToken)
        {
            if (finallyClause.GetLeadingTrivia().IsEmptyOrWhitespace())
            {
                var tryStatement = (TryStatementSyntax)finallyClause.Parent;

                SyntaxList <CatchClauseSyntax> catches = tryStatement.Catches;
                CatchClauseSyntax lastCatch            = catches[catches.Count - 1];

                if (lastCatch.GetTrailingTrivia().IsEmptyOrWhitespace())
                {
                    TryStatementSyntax newTryStatement = tryStatement
                                                         .WithCatches(catches.Replace(lastCatch, lastCatch.WithTrailingTrivia(finallyClause.GetTrailingTrivia())))
                                                         .WithFinally(null);

                    return(await document.ReplaceNodeAsync(tryStatement, newTryStatement, cancellationToken).ConfigureAwait(false));
                }
            }

            return(await document.RemoveNodeAsync(finallyClause, SyntaxRemoveOptions.KeepExteriorTrivia, cancellationToken).ConfigureAwait(false));
        }
        public override void VisitTryStatement(TryStatementSyntax node)
        {
            var tryStatement = new ApexTryStatementSyntax();

            if (node.Block != null)
            {
                node.Block.Accept(this);
                tryStatement.Block = LastBlock;
            }

            foreach (var @catch in node.Catches.EmptyIfNull())
            {
                @catch.Accept(this);
                tryStatement.Catches.Add(LastCatch);
            }

            if (node.Finally != null)
            {
                node.Finally.Accept(this);
                tryStatement.Finally = LastFinally;
            }

            LastStatement = tryStatement;
        }
 public override void VisitTryStatement(TryStatementSyntax node) => this.counter.CheckNesting(node.TryKeyword, () => base.VisitTryStatement(node));
 public override void VisitTryStatement(TryStatementSyntax node)
 {
     ControlFlowNode end = builder.CreateEndNode(node, addToNodeList: false);
     HandleEmbeddedStatement(node.Block, curNode);
     var edge = Connect(curNode, end);
     if (node.Finally?.Block != null)
         edge.AddJumpOutOfTryFinally(node);
     var tryEndPoint = curNode;
     foreach (var cc in node.Catches) {
         HandleEmbeddedStatement(cc.Block, tryEndPoint);
         edge = Connect(tryEndPoint, end);
         if (node.Finally?.Block != null)
             edge.AddJumpOutOfTryFinally(node);
     }
     if (node.Finally?.Block != null) {
         // Don't connect the end of the try-finally block to anything.
         // Consumers of the CFG will have to special-case try-finally.
         HandleEmbeddedStatement(node.Finally.Block, curNode);
     }
     builder.nodes.Add(end);
     curNode = end;
 }
            public AwaitFinallyFrame(AwaitFinallyFrame parent, HashSet<LabelSymbol> labelsOpt, TryStatementSyntax tryStatementSyntax)
            {
                Debug.Assert(parent != null);
                Debug.Assert(tryStatementSyntax != null);

                this.ParentOpt = parent;
                this.LabelsOpt = labelsOpt;
                _tryStatementSyntaxOpt = tryStatementSyntax;
            }
            public AwaitCatchFrame(SyntheticBoundNodeFactory F, TryStatementSyntax tryStatementSyntax)
            {
                this.pendingCaughtException = new SynthesizedLocal(F.CurrentMethod, F.SpecialType(SpecialType.System_Object), SynthesizedLocalKind.TryAwaitPendingCaughtException, tryStatementSyntax);
                this.pendingCatch = new SynthesizedLocal(F.CurrentMethod, F.SpecialType(SpecialType.System_Int32), SynthesizedLocalKind.TryAwaitPendingCatch, tryStatementSyntax);

                this.handlers = new List<BoundBlock>();
                _hoistedLocals = new Dictionary<LocalSymbol, LocalSymbol>();
                _orderedHoistedLocals = new List<LocalSymbol>();
            }
Example #33
0
        public override SyntaxNode VisitTryStatement(TryStatementSyntax node)
        {
            _output.WriteLine(node.TryKeyword, "try {");

            _output.IncreaseIndent();
            this.Visit(node.Block);
            _output.DecreaseIndent();

            _output.TrivialWrite('}');

            string catchedName = null;
            if (node.Catches.Count > 0)
            {
                foreach (var c in node.Catches)
                {
                    if (c.Filter != null)
                        this.AppendCompileIssue(c, IssueType.Error, IssueId.ExceptionFilter);

                    if (c.Declaration != null)
                    {
                        var id = c.Declaration.Identifier;
                        if (id != null && id.Kind() != SyntaxKind.None)
                        {
                            if (string.IsNullOrEmpty(catchedName))
                                catchedName = id.ValueText;
                            else
                            {
                                if (catchedName != id.ValueText)
                                    this.AppendCompileIssue(node, IssueType.Error, IssueId.CatchSameName);
                            }
                        }
                    }
                }


                _output.WriteLine(node.Catches[0], " catch (" + (catchedName ?? "e") + ") {");
                _output.IncreaseIndent();
                if (node.Catches.Count == 1)
                {
                    this.Visit(node.Catches[0].Block);
                }
                else
                {
                    var count = 0;
                    for (int i = 0; i < node.Catches.Count; i++)
                    {
                        if (count > 0)
                            _output.Write(node.Catches[i].CatchKeyword, " else ");

                        var c = node.Catches[i];
                        if (c.Declaration != null)
                        {
                            var info = _semanticModel.GetSymbolInfo(c.Declaration.Type);
                            var typename = info.Symbol.GetTypeSymbolName();

                            if (count == 0)
                                _output.Write(c.Declaration, "if ({0}.name == \"{1}\") ", catchedName, typename);
                            else
                                _output.Write(c.Declaration, "if ({0}.name == \"{1}\") ", catchedName, typename);
                            _output.TrivialWriteLine('{');
                            _output.IncreaseIndent();
                            this.Visit(c.Block);
                            _output.DecreaseIndent();
                            _output.TrivialWrite('}');
                        }
                        else
                        {
                            _output.TrivialWriteLine('{');
                            _output.IncreaseIndent();
                            this.Visit(c.Block);
                            _output.DecreaseIndent();
                            _output.TrivialWrite('}');
                        }

                        count++;
                    }
                }
                if (node.Catches.Count > 1)
                    _output.TrivialWriteLine();
                _output.DecreaseIndent();
                _output.TrivialWrite('}');
            }

            if (node.Finally != null)
            {
                _output.WriteLine(node.Finally.FinallyKeyword, " finally {");

                _output.IncreaseIndent();
                this.Visit(node.Finally.Block);
                _output.DecreaseIndent();

                _output.TrivialWrite('}');
            }

            return node;
        }
 /// <summary>
 /// 
 /// </summary>
 /// <param name="node"></param>
 /// <remarks>
 /// Statements will cause an AST walker to be created, thus we don't need to go further deeper in the
 /// tree by visiting the node.
 /// </remarks>
 public override void VisitTryStatement(TryStatementSyntax node)
 {
     this.VisitStatement(node);
 }
Example #35
0
        public override void VisitTryStatement(TryStatementSyntax node)
        {
            if (node.Catches.Any())
            {
                // NOTE: We're going to cheat a bit - we know that the block is definitely going 
                // to get a map entry, so we don't need to worry about the WithAdditionalFlags
                // binder being dropped.  That is, there's no point in adding the WithAdditionalFlags
                // binder to the map ourselves and having VisitBlock unconditionally overwrite it.
                Visit(node.Block, _enclosing.WithAdditionalFlags(BinderFlags.InTryBlockOfTryCatch));
            }
            else
            {
                Visit(node.Block, _enclosing);
            }

            foreach (var c in node.Catches)
            {
                Visit(c, _enclosing);
            }

            if (node.Finally != null)
            {
                Visit(node.Finally, _enclosing);
            }
        }
 /// <summary>
 /// 
 /// </summary>
 /// <param name="node"></param>
 public override sealed void VisitTryStatement(TryStatementSyntax node)
 {
     this.OnNodeVisited(node, this.type.IsInstanceOfType(node));
     base.VisitTryStatement(node);
 }
            public AwaitFinallyFrame(AwaitFinallyFrame parent, HashSet <LabelSymbol> labelsOpt, TryStatementSyntax tryStatementSyntax)
            {
                Debug.Assert(parent != null);
                Debug.Assert(tryStatementSyntax != null);

                this.ParentOpt         = parent;
                this.LabelsOpt         = labelsOpt;
                _tryStatementSyntaxOpt = tryStatementSyntax;
            }
 internal void AddJumpOutOfTryFinally(TryStatementSyntax tryFinally)
 {
     if (jumpOutOfTryFinally == null)
         jumpOutOfTryFinally = new List<TryStatementSyntax>();
     jumpOutOfTryFinally.Add(tryFinally);
 }
 public TryStatementInterpreter(StatementInterpreterHandler statementInterpreterHandler, TryStatementSyntax tryStatementSyntax)
 {
     this.statementInterpreterHandler = statementInterpreterHandler;
     this.tryStatementSyntax          = tryStatementSyntax;
 }
 /// <summary>
 /// 
 /// </summary>
 /// <param name="node"></param>
 public override sealed void VisitTryStatement(TryStatementSyntax node)
 {
     this.OnNodeVisited(node);
     if (!this.traverseRootOnly) base.VisitTryStatement(node);
 }
Example #41
0
        public void Flatten(TryStatementSyntax node, List<FlatStatement> instructions)
        {
            // set new exception handler
            string tryPrefix = this.MakeUniqueLabelPrefix("try");
            string ehbeginLabel = tryPrefix + "begin";
            string ehendLabel = tryPrefix + "end";
            string finallyLabel = tryPrefix + "finally";

            if (node.Finally != null)
            {
                instructions.Add(FlatStatement.TRY(FlatOperand.LabelRef(ehbeginLabel),FlatOperand.LabelRef(finallyLabel)));
            }
            else
            {
                instructions.Add(FlatStatement.TRY(FlatOperand.LabelRef(ehbeginLabel),ehendLabel));
            }

            Flatten(node.Block, instructions);

            // leave will be injected later!
            /*
            if (node.Finally != null)
            {
                instructions.Add(FlatStatement.LEAVE());
            }
            /**/

            // jump past exception handler
            instructions.Add(FlatStatement.JMP(FlatOperand.LabelRef(ehendLabel)));

            // flatten exception handler
            instructions.Add(FlatStatement.LABEL(FlatOperand.LabelRef(ehbeginLabel)));

            // get exception type
            if (node.Catches != null && node.Catches.Count>0)
            {
                FlatOperand fop_exceptionType = this.AllocateRegister("");
                {
                    FlatOperand lvalue_exceptionType = fop_exceptionType.GetLValue(this, instructions);
                    instructions.Add(FlatStatement.TYPEOF(lvalue_exceptionType, FlatOperand.ExceptionRef()));
                }

                foreach (CatchClauseSyntax ccs in node.Catches)
                {
                    this.Flatten(ccs, fop_exceptionType, ehendLabel, instructions);
                }
            }

            // leave will be injected later
            /*
            if (node.Finally != null)
            {
                instructions.Add(FlatStatement.LEAVE());
            }
            /**/

            instructions.Add(FlatStatement.THROW(FlatOperand.ExceptionRef()));

            if (node.Finally != null)
            {
                instructions.Add(FlatStatement.LABEL(FlatOperand.LabelRef(finallyLabel)));

                this.Flatten(node.Finally.Block, instructions);

                instructions.Add(FlatStatement.ENDFINALLY());
            }

            instructions.Add(FlatStatement.LABEL(FlatOperand.LabelRef(ehendLabel)));
        }
 public override void VisitTryStatement(TryStatementSyntax node) => CheckNesting(node.TryKeyword, () => base.VisitTryStatement(node));
Example #43
0
        private static SyntaxNode CalculateNewRoot(SyntaxNode root, SyntaxNode currentNode, TryStatementSyntax tryStatement)
        {
            var isTryRemovable = tryStatement.Catches.Count == 1 && tryStatement.Finally == null;

            return(isTryRemovable
                ? root.ReplaceNode(
                       tryStatement,
                       tryStatement.Block.Statements.Select(st => st.WithAdditionalAnnotations(Formatter.Annotation)))
                : root.RemoveNode(currentNode, SyntaxRemoveOptions.KeepNoTrivia));
        }
Example #44
0
        private BoundTryStatement BindTryStatement(TryStatementSyntax node, DiagnosticBag diagnostics)
        {
            Debug.Assert(node != null);

            var tryBlock = this.BindBlock(node.Block, diagnostics);
            var catchBlocks = this.BindCatchBlocks(node.Catches, diagnostics);
            var finallyBlockOpt = (node.Finally != null) ? this.BindBlock(node.Finally.Block, diagnostics) : null;
            return new BoundTryStatement(node, tryBlock, catchBlocks, finallyBlockOpt);
        }
Example #45
0
        /// <summary>
        /// Handles the given try statement.
        /// </summary>
        /// <param name="stmt">Statement</param>
        /// <param name="successor">Successor</param>
        private void HandleTryStatement(TryStatementSyntax stmt, ControlFlowGraphNode successor)
        {
            if (Configuration.AnalyzeExceptionHandling)
            {
                var catchSuccessors = new List<ControlFlowGraphNode>();
                foreach (var catchBlock in stmt.Catches)
                {
                    var catchSucc = new ControlFlowGraphNode(this.Summary);
                    catchSucc.Construct(catchBlock.Block.Statements, 0, false, successor);
                    catchSuccessors.Add(catchSucc);
                }

                ControlFlowGraphNode pred = null;
                for (int idx = 0; idx < stmt.Block.Statements.Count; idx++)
                {
                    var tryNode = new ControlFlowGraphNode(this.Summary);
                    tryNode.IsJumpNode = true;

                    if (idx == 0)
                    {
                        tryNode = this;
                    }

                    if (idx + 1 == stmt.Block.Statements.Count)
                    {
                        tryNode.Construct(stmt.Block.Statements, idx, true, successor);
                    }
                    else
                    {
                        tryNode.Construct(stmt.Block.Statements, idx, true, null);
                    }

                    foreach (var catchNode in catchSuccessors)
                    {
                        tryNode.ISuccessors.Add(catchNode);
                        catchNode.IPredecessors.Add(tryNode);
                    }

                    if (pred != null)
                    {
                        pred.ISuccessors.Add(tryNode);
                        tryNode.IPredecessors.Add(pred);
                    }

                    pred = tryNode;
                }
            }
            else
            {
                this.Construct(stmt.Block.Statements, 0, false, successor);
            }
        }
Example #46
0
        public void VisitTryStatement(TryStatementSyntax node)
        {
            if (node == null)
                throw new ArgumentNullException("node");

            node.Validate();

            WriteLeadingTrivia(node);

            _writer.WriteIndent();
            _writer.WriteKeyword(PrinterKeyword.Try);

            if (node.Catches.Count > 0)
            {
                if (!_writer.Configuration.LineBreaksAndWrapping.PlaceOnNewLine.PlaceCatchOnNewLine)
                    _writer.PushBraceFormatting(_writer.Configuration.BracesLayout.Other, false);
            }
            else if (node.Finally != null)
            {
                if (!_writer.Configuration.LineBreaksAndWrapping.PlaceOnNewLine.PlaceFinallyOnNewLine)
                    _writer.PushBraceFormatting(_writer.Configuration.BracesLayout.Other, false);
            }

            node.Block.Accept(this);

            for (int i = 0; i < node.Catches.Count; i++)
            {
                if (i == node.Catches.Count - 1)
                {
                    if (!_writer.Configuration.LineBreaksAndWrapping.PlaceOnNewLine.PlaceCatchOnNewLine)
                        _writer.PopBraceFormatting();
                    if (
                        node.Finally != null &&
                        !_writer.Configuration.LineBreaksAndWrapping.PlaceOnNewLine.PlaceFinallyOnNewLine
                    )
                        _writer.PushBraceFormatting(_writer.Configuration.BracesLayout.Other, false);
                }

                node.Catches[i].Accept(this);
            }

            if (node.Finally != null)
            {
                if (!_writer.Configuration.LineBreaksAndWrapping.PlaceOnNewLine.PlaceFinallyOnNewLine)
                    _writer.PopBraceFormatting();

                node.Finally.Accept(this);
            }

            WriteTrailingTrivia(node);
        }
Example #47
0
        public override void VisitTryStatement(TryStatementSyntax node)
        {
            Emit("try");
            using (IndentedBracketScope())
            {
                VisitBlock(node.Block);
            }
            foreach (var @catch in node.Catches)
            {
                string arguments = String.Empty;
                if (!(@catch.Declaration == null))
                {
                    if (@catch.Declaration.Identifier != null)
                        arguments = string.Format(" ({0})", @catch.Declaration.Identifier.Text);
                }

                Emit("catch" + arguments);
                using (IndentedBracketScope())
                {
                    VisitBlock(@catch.Block);
                }
            }
        }
Example #48
0
        private Block BuildTryStatement(TryStatementSyntax tryStatement, Block currentBlock)
        {
            // successor - either finally of next block after try statement
            var catchSuccessor = currentBlock;

            var hasFinally = tryStatement.Finally?.Block != null;

            if (hasFinally)
            {
                // Create a finally block for the happy path where no exceptions are thrown
                catchSuccessor = BuildBlock(tryStatement.Finally.Block, CreateBlock(catchSuccessor));

                // Wire another finally block to the exit target stack in case we have a return inside the try/catch block
                ExitTarget.Push(BuildBlock(tryStatement.Finally.Block, CreateBlock(ExitTarget.Peek())));
            }

            var catchBlocks = tryStatement.Catches
                              .Reverse()
                              .Select(catchClause =>
            {
                Block catchBlock = BuildBlock(catchClause.Block, CreateBlock(catchSuccessor));
                if (catchClause.Filter?.FilterExpression != null)
                {
                    catchBlock = BuildExpression(catchClause.Filter.FilterExpression,
                                                 CreateBinaryBranchBlock(catchClause.Filter, catchBlock, catchSuccessor));
                }
                return(catchBlock);
            })
                              .ToList();

            // If there is a catch with no Exception filter or equivalent we don't want to
            // join the tryStatement start/end blocks with the exit block because all
            // exceptions will be caught before going to finally
            var areAllExceptionsCaught = tryStatement.Catches.Any(CSharpSyntaxHelper.IsCatchingAllExceptions);

            // try end
            var tryEndStatementConnections = catchBlocks.ToList();

            tryEndStatementConnections.Add(catchSuccessor); // happy path, no exceptions thrown
            if (!areAllExceptionsCaught)                    // unexpected exception thrown, go to exit (through finally if present)
            {
                tryEndStatementConnections.Add(ExitTarget.Peek());
            }

            var tryBody = BuildBlock(tryStatement.Block,
                                     CreateBranchBlock(tryStatement, tryEndStatementConnections.Distinct()));

            var tryStartStatementConnections = catchBlocks.ToList();

            tryStartStatementConnections.Add(tryBody); // try body

            if (!areAllExceptionsCaught)               // unexpected exception thrown, go to exit (through finally if present)
            {
                tryStartStatementConnections.Add(ExitTarget.Peek());
            }

            var tryStartBlock = CreateBranchBlock(tryStatement, tryStartStatementConnections.Distinct());

            if (hasFinally)
            {
                ExitTarget.Pop();
            }

            return(tryStartBlock);
        }
 public TryStatementTranslation(TryStatementSyntax syntax, SyntaxTranslation parent) : base(syntax, parent)
 {
     Block = syntax.Block.Get<BlockTranslation>(this);
     Catches = syntax.Catches.Get<CatchClauseSyntax, CatchClauseTranslation>(this);
     Finally = syntax.Finally.Get<FinallyClauseTranslation>(this);
 }
Example #50
0
 public override void VisitTryStatement(TryStatementSyntax node)
 {
     base.VisitTryStatement(node);
     Count += node.Catches.Count;
 }
Example #51
0
 public override void VisitTryStatement(TryStatementSyntax node)
 {
     this.Logic.Add(this.nodeFactory.CreateTry(node));
 }