private ImmutableArray <Edit> GetUnwrapAllEdits(WrappingStyle wrappingStyle)
            {
                var result = ArrayBuilder <Edit> .GetInstance();

                AddTextChangeBetweenOpenAndFirstItem(wrappingStyle, result);

                foreach (var comma in _listItems.GetSeparators())
                {
                    result.Add(Edit.DeleteBetween(comma.GetPreviousToken(), comma));
                    result.Add(Edit.DeleteBetween(comma, comma.GetNextToken()));
                }

                result.Add(Edit.DeleteBetween(_listItems.Last(), _listSyntax.GetLastToken()));
                return(result.ToImmutableAndFree());
            }
        public static void Analyze(SyntaxNodeAnalysisContext context, EnumDeclarationSyntax enumDeclaration)
        {
            SeparatedSyntaxList <EnumMemberDeclarationSyntax> members = enumDeclaration.Members;

            if (members.Count > 1)
            {
                int previousIndex = members[0].GetSpanStartLine();

                for (int i = 1; i < members.Count; i++)
                {
                    if (members[i].GetSpanStartLine() == previousIndex)
                    {
                        TextSpan span = TextSpan.FromBounds(
                            members.First().Span.Start,
                            members.Last().Span.End);

                        context.ReportDiagnostic(
                            DiagnosticDescriptors.FormatEachEnumMemberOnSeparateLine,
                            Location.Create(enumDeclaration.SyntaxTree, span));

                        return;
                    }

                    previousIndex = members[i].GetSpanEndLine();
                }
            }
        }
        private void AnalyzeVariableDeclaration(SyntaxNodeAnalysisContext context)
        {
            if (GeneratedCodeAnalyzer?.IsGeneratedCode(context) == true)
            {
                return;
            }

            var variableDeclaration = (VariableDeclarationSyntax)context.Node;

            if (SplitVariableDeclarationRefactoring.CanRefactor(variableDeclaration))
            {
                SeparatedSyntaxList <VariableDeclaratorSyntax> variables = variableDeclaration.Variables;

                TextSpan span = TextSpan.FromBounds(
                    variables[1].Span.Start,
                    variables.Last().Span.End);

                if (context.Node
                    .DescendantTrivia(span)
                    .All(f => f.IsWhitespaceOrEndOfLineTrivia()))
                {
                    context.ReportDiagnostic(
                        DiagnosticDescriptors.SplitVariableDeclaration,
                        variableDeclaration.GetLocation());
                }
            }
        }
        private static async Task <Document> RemoveRedundantCommaAsync(
            Document document,
            InitializerExpressionSyntax initializer,
            CancellationToken cancellationToken)
        {
            SyntaxNode oldRoot = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);

            SyntaxToken lastComma = initializer.Expressions.GetSeparators().Last();

            SyntaxTriviaList newTrailingTrivia = initializer.Expressions.Last().GetTrailingTrivia()
                                                 .AddRange(lastComma.LeadingTrivia)
                                                 .AddRange(lastComma.TrailingTrivia);

            SeparatedSyntaxList <ExpressionSyntax> newExpressions = initializer
                                                                    .Expressions
                                                                    .ReplaceSeparator(
                lastComma,
                SyntaxFactory.MissingToken(SyntaxKind.CommaToken));

            ExpressionSyntax lastExpression = newExpressions.Last();

            newExpressions = newExpressions
                             .Replace(lastExpression, lastExpression.WithTrailingTrivia(newTrailingTrivia));

            InitializerExpressionSyntax newInitializer = initializer
                                                         .WithExpressions(newExpressions);

            SyntaxNode newRoot = oldRoot.ReplaceNode(initializer, newInitializer);

            return(document.WithSyntaxRoot(newRoot));
        }
        private static void AnalyzeBaseArgumentList(SyntaxNodeAnalysisContext context)
        {
            if (context.Node.ContainsDiagnostics)
            {
                return;
            }

            var argumentList = (BaseArgumentListSyntax)context.Node;

            SeparatedSyntaxList <ArgumentSyntax> arguments = argumentList.Arguments;

            int index = IndexOfFirstFixableParameter(argumentList, arguments, context.SemanticModel, context.CancellationToken);

            if (index == -1)
            {
                return;
            }

            TextSpan span = TextSpan.FromBounds(arguments[index].SpanStart, arguments.Last().Span.End);

            if (argumentList.ContainsDirectives(span))
            {
                return;
            }

            DiagnosticHelpers.ReportDiagnostic(context,
                                               DiagnosticDescriptors.OrderNamedArguments,
                                               Location.Create(argumentList.SyntaxTree, span));
        }
示例#6
0
        private static void AnalyzeEnumDeclaration(SyntaxNodeAnalysisContext context)
        {
            var enumDeclaration = (EnumDeclarationSyntax)context.Node;

            SeparatedSyntaxList <EnumMemberDeclarationSyntax> members = enumDeclaration.Members;

            if (members.Count <= 1)
            {
                return;
            }

            int previousIndex = members[0].GetSpanStartLine();

            for (int i = 1; i < members.Count; i++)
            {
                if (members[i].GetSpanStartLine() == previousIndex)
                {
                    TextSpan span = TextSpan.FromBounds(
                        members[0].SpanStart,
                        members.Last().Span.End);

                    DiagnosticHelpers.ReportDiagnostic(context,
                                                       DiagnosticDescriptors.AddNewLineBeforeEnumMember,
                                                       Location.Create(enumDeclaration.SyntaxTree, span));

                    return;
                }

                previousIndex = members[i].GetSpanEndLine();
            }
        }
        public static async Task <Document> RefactorAsync(
            Document document,
            InitializerExpressionSyntax initializer,
            CancellationToken cancellationToken)
        {
            SyntaxToken lastComma = initializer.Expressions.GetSeparators().Last();

            SyntaxTriviaList newTrailingTrivia = initializer.Expressions.Last().GetTrailingTrivia()
                                                 .AddRange(lastComma.LeadingTrivia)
                                                 .AddRange(lastComma.TrailingTrivia);

            SeparatedSyntaxList <ExpressionSyntax> newExpressions = initializer
                                                                    .Expressions
                                                                    .ReplaceSeparator(
                lastComma,
                SyntaxFactory.MissingToken(SyntaxKind.CommaToken));

            ExpressionSyntax lastExpression = newExpressions.Last();

            newExpressions = newExpressions
                             .Replace(lastExpression, lastExpression.WithTrailingTrivia(newTrailingTrivia));

            InitializerExpressionSyntax newInitializer = initializer
                                                         .WithExpressions(newExpressions);

            return(await document.ReplaceNodeAsync(initializer, newInitializer, cancellationToken).ConfigureAwait(false));
        }
        public static bool IsApplicableSpan(InitializerExpressionSyntax initializer, TextSpan span)
        {
            SeparatedSyntaxList <ExpressionSyntax> expressions = initializer.Expressions;

            if (!expressions.Any())
            {
                return(true);
            }

            if (span.IsEmpty)
            {
                if (expressions.Count == expressions.SeparatorCount &&
                    TextSpan.FromBounds(expressions.GetSeparator(expressions.Count - 1).Span.End, initializer.CloseBraceToken.SpanStart).Contains(span))
                {
                    return(true);
                }

                TextSpan span2 = TextSpan.FromBounds(expressions.Last().Span.End, initializer.CloseBraceToken.SpanStart);

                if (span2.Length > 0)
                {
                    span2 = new TextSpan(span2.Start + 1, span2.Length - 1);

                    if (span2.Contains(span))
                    {
                        return(true);
                    }
                }
            }

            return(false);
        }
示例#9
0
        /// <summary>
        /// Generates an array intializer
        /// </summary>
        /// <param name="node">The expression</param>
        public override void Generate(InitializerExpressionSyntax node)
        {
            SeparatedSyntaxList <ExpressionSyntax> children = node.Expressions;

            m_context.Writer.Append("{");
            foreach (ExpressionSyntax child in children)
            {
                m_context.Generators.Expression.Generate(child);

                if (child != children.Last())
                {
                    m_context.Writer.Append(", ");
                }
            }
            m_context.Writer.Append("}");
        }
示例#10
0
        public static bool SpanContainsDirectives <TNode>(this SeparatedSyntaxList <TNode> list) where TNode : SyntaxNode
        {
            if (!list.Any())
            {
                return(false);
            }

            for (int i = 1; i < list.Count - 1; i++)
            {
                if (list[i].ContainsDirectives)
                {
                    return(true);
                }
            }

            return(list.First().SpanOrLeadingTriviaContainsDirectives() ||
                   list.Last().SpanOrTrailingTriviaContainsDirectives());
        }
示例#11
0
        private static void AnalyzeVariableDeclaration(SyntaxNodeAnalysisContext context)
        {
            var variableDeclaration = (VariableDeclarationSyntax)context.Node;

            if (SplitVariableDeclarationAnalysis.IsFixable(variableDeclaration))
            {
                SeparatedSyntaxList <VariableDeclaratorSyntax> variables = variableDeclaration.Variables;

                TextSpan span = TextSpan.FromBounds(variables[1].SpanStart, variables.Last().Span.End);

                if (context.Node
                    .DescendantTrivia(span)
                    .All(f => f.IsWhitespaceOrEndOfLineTrivia()))
                {
                    DiagnosticHelpers.ReportDiagnostic(context, DiagnosticRules.SplitVariableDeclaration, variableDeclaration);
                }
            }
        }
        private static void AnalyzeVariableDeclaration(
            SyntaxNodeAnalysisContext context,
            VariableDeclarationSyntax variableDeclaration)
        {
            SeparatedSyntaxList <VariableDeclaratorSyntax> variables = variableDeclaration.Variables;

            if (variables.Count > 1)
            {
                TextSpan span = TextSpan.FromBounds(
                    variables[1].Span.Start,
                    variables.Last().Span.End);

                if (context.Node
                    .DescendantTrivia(span)
                    .All(f => f.IsWhitespaceOrEndOfLine()))
                {
                    context.ReportDiagnostic(
                        DiagnosticDescriptors.SplitDeclarationIntoMultipleDeclarations,
                        Location.Create(context.Node.SyntaxTree, span));
                }
            }
        }
        private static void AnalyzeDeclaration<TMember>(
            SyntaxNodeAnalysisContext context,
            SeparatedSyntaxList<TMember> members,
            SyntaxToken openBrace,
            SyntaxToken closeBrace) where TMember : MemberDeclarationSyntax
        {
            if (members.Any())
            {
                AnalyzeStart(context, members[0], openBrace);

                int count = members.SeparatorCount;

                SyntaxNodeOrToken nodeOrToken = (count == members.Count)
                    ? members.GetSeparator(count - 1)
                    : members.Last();

                AnalyzeEnd(context, nodeOrToken, closeBrace);
            }
            else
            {
                AnalyzeEmptyBraces(context, openBrace, closeBrace);
            }
        }
示例#14
0
 public static bool IsLast <TNode>(this SeparatedSyntaxList <TNode> list, TNode node) where TNode : SyntaxNode
 {
     return(list.Any() &&
            list.Last() == node);
 }
        private static void AnalyzePragmaWarningDirectiveTrivia(SyntaxNodeAnalysisContext context)
        {
            var directive = (PragmaWarningDirectiveTriviaSyntax)context.Node;

            SeparatedSyntaxList <ExpressionSyntax> errorCodes = directive.ErrorCodes;

            int codeCount = errorCodes.Count;

            if (codeCount == 0)
            {
                return;
            }

            if (codeCount == errorCodes.SeparatorCount)
            {
                if (!errorCodes.GetSeparator(codeCount - 1).TrailingTrivia.IsEmptyOrWhitespace())
                {
                    return;
                }
            }
            else if (!errorCodes.Last().GetTrailingTrivia().IsEmptyOrWhitespace())
            {
                return;
            }

            if (IsSuppressingThisAnalyzer(errorCodes))
            {
                return;
            }

            SyntaxTrivia trivia = directive.ParentTrivia;

            if (!trivia.TryGetContainingList(out SyntaxTriviaList list))
            {
                return;
            }

            int count = list.Count;

            if (count == 1)
            {
                return;
            }

            int index = list.IndexOf(trivia);

            if (index == count - 1)
            {
                return;
            }

            int i = index - 1;

            while (i >= 0 &&
                   list[i].IsWhitespaceOrEndOfLineTrivia())
            {
                i--;
            }

            if (i >= 0)
            {
                SyntaxTrivia directiveTrivia = list[i];

                if (directiveTrivia.IsKind(SyntaxKind.PragmaWarningDirectiveTrivia))
                {
                    var previousDirective = (PragmaWarningDirectiveTriviaSyntax)directiveTrivia.GetStructure();

                    if (!IsSuppressingThisAnalyzer(previousDirective.ErrorCodes))
                    {
                        return;
                    }
                }
            }

            i = index + 1;

            while (i < count &&
                   list[i].IsWhitespaceOrEndOfLineTrivia())
            {
                i++;
            }

            if (i == count)
            {
                return;
            }

            if (!list[i].IsKind(SyntaxKind.PragmaWarningDirectiveTrivia))
            {
                return;
            }

            if (list[i].GetStructure() is not PragmaWarningDirectiveTriviaSyntax nextDirective)
            {
                return;
            }

            SyntaxToken disableOrRestoreKeyword = directive.DisableOrRestoreKeyword;

            SyntaxKind keywordKind = disableOrRestoreKeyword.Kind();

            if (keywordKind != nextDirective.DisableOrRestoreKeyword.Kind())
            {
                return;
            }

            if (keywordKind == SyntaxKind.DisableKeyword &&
                IsSuppressingThisAnalyzer(nextDirective.ErrorCodes))
            {
                return;
            }

            DiagnosticHelpers.ReportDiagnostic(context, DiagnosticRules.MergePreprocessorDirectives, directive);
        }
        private static void Analyze <TNode>(SyntaxNodeAnalysisContext context, SeparatedSyntaxList <TNode> nodes, SyntaxToken token) where TNode : SyntaxNode
        {
            int count = nodes.Count;

            if (count <= 1)
            {
                return;
            }

            SyntaxTree syntaxTree = nodes[0].SyntaxTree;

            bool isSingleLine = true;

            for (int i = 1; i < count; i++)
            {
                TNode node1 = nodes[i - 1];
                TNode node2 = nodes[i];

                bool isSingleLine1       = IsSingleLine(node1.Span);
                bool isSingleLine2       = IsSingleLine(node2.Span);
                bool isSingleLineBetween = IsSingleLine(TextSpan.FromBounds(node1.Span.End, node2.SpanStart));

                if (isSingleLine1)
                {
                    if (isSingleLine2)
                    {
                        if (i > 1 &&
                            isSingleLineBetween != isSingleLine)
                        {
                            ReportDiagnostic();
                            return;
                        }
                    }
                    else if (isSingleLineBetween)
                    {
                        if (i < count - 1 ||
                            !(node2 is ArgumentSyntax argument) ||
                            !argument.Expression.IsKind(SyntaxKind.AnonymousMethodExpression, SyntaxKind.SimpleLambdaExpression, SyntaxKind.ParenthesizedLambdaExpression))
                        {
                            ReportDiagnostic();
                            return;
                        }
                    }
                    else if (i > 1 &&
                             isSingleLine)
                    {
                        ReportDiagnostic();
                        return;
                    }
                }
                else if (isSingleLine2)
                {
                    if (isSingleLineBetween)
                    {
                        ReportDiagnostic();
                        return;
                    }
                    else if (i > 1 &&
                             isSingleLine)
                    {
                        ReportDiagnostic();
                        return;
                    }
                }
                else if (isSingleLineBetween)
                {
                    ReportDiagnostic();
                    return;
                }
                else
                {
                    isSingleLine = false;
                }

                if (isSingleLine)
                {
                    isSingleLine = isSingleLine1 && isSingleLine2 && isSingleLineBetween;
                }
            }

            bool IsSingleLine(TextSpan span)
            {
                return(syntaxTree.GetLineSpan(span, context.CancellationToken).IsSingleLine());
            }

            void ReportDiagnostic()
            {
                context.ReportDiagnostic(
                    DiagnosticDescriptors.WrapAndIndentEachNodeInList,
                    Location.Create(syntaxTree, TextSpan.FromBounds(nodes[0].SpanStart, nodes.Last().Span.End)));
            }
        }
示例#17
0
        public static Task <Document> ToSingleLineAsync(
            Document document,
            InitializerExpressionSyntax initializer,
            bool removeTrailingComma            = false,
            CancellationToken cancellationToken = default(CancellationToken))
        {
            InitializerExpressionSyntax newInitializer = initializer
                                                         .ReplaceWhitespace(ElasticSpace, TextSpan.FromBounds(initializer.Span.Start, initializer.Span.End))
                                                         .WithFormatterAnnotation();

            newInitializer = newInitializer.WithOpenBraceToken(newInitializer.OpenBraceToken.WithoutLeadingTrivia().WithTrailingTrivia(Space));

            newInitializer = newInitializer.WithCloseBraceToken(newInitializer.CloseBraceToken.WithoutLeadingTrivia());

            SeparatedSyntaxList <ExpressionSyntax> expressions = newInitializer.Expressions;

            if (expressions.Any())
            {
                ExpressionSyntax firstExpression = expressions.First();

                newInitializer = newInitializer.WithExpressions(expressions.Replace(firstExpression, firstExpression.WithoutLeadingTrivia()));

                expressions = newInitializer.Expressions;

                SyntaxToken trailingComma = expressions.GetTrailingSeparator();

                if (trailingComma.IsKind(SyntaxKind.CommaToken))
                {
                    if (removeTrailingComma)
                    {
                        expressions = expressions.ReplaceSeparator(trailingComma, MissingToken(SyntaxKind.CommaToken));

                        ExpressionSyntax lastExpression = expressions.Last();

                        expressions = expressions.Replace(lastExpression, lastExpression.WithTrailingTrivia(Space));

                        newInitializer = newInitializer.WithExpressions(expressions);
                    }
                    else
                    {
                        newInitializer = newInitializer.WithExpressions(expressions.ReplaceSeparator(trailingComma, trailingComma.WithTrailingTrivia(Space)));
                    }
                }
                else
                {
                    ExpressionSyntax lastExpression = expressions.Last();

                    newInitializer = newInitializer.WithExpressions(expressions.Replace(lastExpression, lastExpression.WithTrailingTrivia(Space)));
                }
            }

            SyntaxNode parent = initializer.Parent;

            SyntaxNode newParent;

            switch (parent.Kind())
            {
            case SyntaxKind.ObjectCreationExpression:
            {
                var expression = (ObjectCreationExpressionSyntax)parent;

                expression = expression.WithInitializer(newInitializer);

                ArgumentListSyntax argumentList = expression.ArgumentList;

                if (argumentList != null)
                {
                    newParent = expression.WithArgumentList(argumentList.WithTrailingTrivia(Space));
                }
                else
                {
                    newParent = expression.WithType(expression.Type.WithTrailingTrivia(Space));
                }

                break;
            }

            case SyntaxKind.ArrayCreationExpression:
            {
                var expression = (ArrayCreationExpressionSyntax)parent;

                newParent = expression
                            .WithInitializer(newInitializer)
                            .WithType(expression.Type.WithTrailingTrivia(Space));

                break;
            }

            case SyntaxKind.ImplicitArrayCreationExpression:
            {
                var expression = (ImplicitArrayCreationExpressionSyntax)parent;

                newParent = expression
                            .WithInitializer(newInitializer)
                            .WithCloseBracketToken(expression.CloseBracketToken.WithTrailingTrivia(Space));

                break;
            }

            case SyntaxKind.EqualsValueClause:
            {
                var equalsValueClause = (EqualsValueClauseSyntax)parent;

                newParent = equalsValueClause
                            .WithValue(newInitializer)
                            .WithEqualsToken(equalsValueClause.EqualsToken.WithTrailingTrivia(Space));

                break;
            }

            case SyntaxKind.SimpleAssignmentExpression:
            {
                var simpleAssignment = (AssignmentExpressionSyntax)parent;

                newParent = simpleAssignment
                            .WithRight(newInitializer)
                            .WithOperatorToken(simpleAssignment.OperatorToken.WithTrailingTrivia(Space));

                break;
            }

            default:
            {
                Debug.Fail(parent.Kind().ToString());

                return(document.ReplaceNodeAsync(initializer, newInitializer, cancellationToken));
            }
            }

            return(document.ReplaceNodeAsync(parent, newParent, cancellationToken));
        }
示例#18
0
 public override TNode Last()
 => SyntaxWrapper.Wrap(SyntaxList.Last());