protected override bool TreatAsReturn(Document document, int position, CancellationToken cancellationToken)
        {
            var root = document.GetSyntaxRootSynchronously(cancellationToken);

            var endToken = root.FindToken(position);

            if (endToken.IsMissing)
            {
                return(false);
            }

            var tokenToLeft = root.FindTokenOnLeftOfPosition(position);
            var startToken  = endToken.GetPreviousToken();

            // case 1:
            //      Consider code like so: try {|}
            //      With auto brace completion on, user types `{` and `Return` in a hurry.
            //      During typing, it is possible that shift was still down and not released after typing `{`.
            //      So we've got an unintentional `shift + enter` and also we have nothing to complete this,
            //      so we put in a newline,
            //      which generates code like so : try { }
            //                                     |
            //      which is not useful as : try {
            //                                  |
            //                               }
            //      To support this, we treat `shift + enter` like `enter` here.
            var afterOpenBrace = startToken.Kind() == SyntaxKind.OpenBraceToken &&
                                 endToken.Kind() == SyntaxKind.CloseBraceToken &&
                                 tokenToLeft == startToken &&
                                 endToken.Parent.IsKind(SyntaxKind.Block) &&
                                 FormattingRangeHelper.AreTwoTokensOnSameLine(startToken, endToken);

            return(afterOpenBrace);
        }
        public void TestAreTwoTokensOnSameLineFalse()
        {
            var root   = SyntaxFactory.ParseSyntaxTree("{Fizz();\nBuzz();}").GetRoot();
            var token1 = root.GetFirstToken();
            var token2 = root.GetLastToken();

            Assert.False(FormattingRangeHelper.AreTwoTokensOnSameLine(token1, token2));
        }
Esempio n. 3
0
        protected void AddBraceSuppressOperations(List <SuppressOperation> list, SyntaxNode node, SyntaxToken lastToken)
        {
            var bracePair = node.GetBracePair();

            if (!bracePair.IsValidBracePair())
            {
                return;
            }

            var firstTokenOfNode = node.GetFirstToken(includeZeroWidth: true);

            if (node is MemberDeclarationSyntax memberDeclNode)
            {
                var firstAndLastTokens = memberDeclNode.GetFirstAndLastMemberDeclarationTokensAfterAttributes();
                firstTokenOfNode = firstAndLastTokens.Item1;
            }

            if (node.IsLambdaBodyBlock())
            {
                // include lambda itself.
                firstTokenOfNode = node.Parent.GetFirstToken(includeZeroWidth: true);
            }

            // We may think we have a complete set of braces, but that may not actually be the case
            // due incomplete code.  i.e. we have something like:
            //
            // class C
            // {
            //      int Blah {
            //          get { return blah
            // }
            //
            // In this case the parse will think that the get-accessor is actually on two lines
            // (because it will consume the close curly that more accurately belongs to the class.
            //
            // Now there are different behaviors we want depending on what the user is doing
            // and what we are formatting.  For example, if the user hits semicolon at the end of
            // "blah", then we want to keep the accessor on a single line.  In this scenario we
            // effectively want to ignore the following close curly as it may not be important to
            // this construct in the mind of the user.
            //
            // However, say the user hits semicolon, then hits enter, then types a close curly.
            // In this scenario we would actually want the get-accessor to be formatted over multiple
            // lines.  The difference here is that because the user just hit close-curly here we can
            // consider it as being part of the closest construct and we can consider its placement
            // when deciding if the construct is on a single line.

            var endToken = bracePair.Item2;

            if (lastToken.Kind() != SyntaxKind.CloseBraceToken &&
                lastToken.Kind() != SyntaxKind.EndOfFileToken &&
                !endToken.IsMissing)
            {
                // The user didn't just type the close brace.  So any close brace we have may
                // actually belong to a containing construct.  See if any containers are missing
                // a close brace, and if so, act as if our own close brace is missing.

                if (SomeParentHasMissingCloseBrace(node.Parent))
                {
                    if (node.IsKind(SyntaxKind.Block) && ((BlockSyntax)node).Statements.Count >= 1)
                    {
                        // In the case of a block, see if the first statement is on the same line
                        // as the open curly.  If so then we'll want to consider the end of the
                        // block as the end of the first statement.  i.e. if you have:
                        //
                        //  try { }
                        //  catch { return;     // <-- the end of this block is the end of the return statement.
                        //  Method();
                        var firstStatement = ((BlockSyntax)node).Statements[0];
                        if (FormattingRangeHelper.AreTwoTokensOnSameLine(firstTokenOfNode, firstStatement.GetFirstToken()))
                        {
                            endToken = firstStatement.GetLastToken();
                        }
                    }
                    else
                    {
                        endToken = endToken.GetPreviousToken();
                    }
                }
            }

            // suppress wrapping on whole construct that owns braces and also brace pair itself if
            // it is on same line
            AddSuppressWrappingIfOnSingleLineOperation(list, firstTokenOfNode, endToken);
            AddSuppressWrappingIfOnSingleLineOperation(list, bracePair.Item1, endToken);
        }
        private static SyntaxNode SimplifyBlock(
            BlockSyntax node,
            SemanticModel semanticModel,
            OptionSet optionSet,
            CancellationToken cancellationToken)
        {
            if (node.Statements.Count != 1)
            {
                return(node);
            }

            if (!CanHaveEmbeddedStatement(node.Parent))
            {
                return(node);
            }

            switch (optionSet.GetOption(CSharpCodeStyleOptions.PreferBraces).Value)
            {
            case PreferBracesPreference.Always:
            default:
                return(node);

            case PreferBracesPreference.WhenMultiline:
                // Braces are optional in several scenarios for 'when_multiline', but are only automatically removed
                // in a subset of cases where all of the following are met:
                //
                // 1. This is an 'if' statement
                // 1. The 'if' statement does not have an 'else' clause and is not part of a larger 'if'/'else if'/'else' sequence
                // 2. The 'if' statement is not considered multiline
                if (!node.Parent.IsKind(SyntaxKind.IfStatement))
                {
                    // Braces are only removed for 'if' statements
                    return(node);
                }

                if (node.Parent.IsParentKind(SyntaxKind.IfStatement, SyntaxKind.ElseClause))
                {
                    // Braces are not removed from more complicated 'if' sequences
                    return(node);
                }

                if (!FormattingRangeHelper.AreTwoTokensOnSameLine(node.Statements[0].GetFirstToken(), node.Statements[0].GetLastToken()))
                {
                    // Braces are not removed when the embedded statement is multiline
                    return(node);
                }

                if (!FormattingRangeHelper.AreTwoTokensOnSameLine(node.Parent.GetFirstToken(), node.GetFirstToken().GetPreviousToken()))
                {
                    // Braces are not removed when the part of the 'if' statement preceding the embedded statement
                    // is multiline.
                    return(node);
                }

                break;

            case PreferBracesPreference.None:
                break;
            }

            return(node.Statements[0]);
        }
        public void TestAreTwoTokensOnSameLineWithEqualTokensWithoutSyntaxTree()
        {
            var token = SyntaxFactory.ParseToken("else");

            Assert.True(FormattingRangeHelper.AreTwoTokensOnSameLine(token, token));
        }
        public void TestAreTwoTokensOnSameLineWithEqualTokens()
        {
            var token = SyntaxFactory.ParseSyntaxTree("else\nFoo();").GetRoot().GetFirstToken();

            Assert.True(FormattingRangeHelper.AreTwoTokensOnSameLine(token, token));
        }