コード例 #1
0
        private static SyntaxTriviaList GetTrivia(SyntaxNode node, SyntaxTokenList modifiers, SyntaxToken modifier, int i)
        {
            SyntaxTriviaList leading  = modifier.LeadingTrivia;
            SyntaxTriviaList trailing = modifier.TrailingTrivia;

            if (leading.Any())
            {
                if (trailing.All(f => f.IsWhitespaceTrivia()))
                {
                    return(leading);
                }
                else
                {
                    return(leading.Concat(trailing).ToSyntaxTriviaList());
                }
            }
            else
            {
                SyntaxToken previousToken = (i == 0)
                    ? FindPreviousToken(node, modifier)
                    : modifiers[i - 1];

                if (!previousToken.IsKind(SyntaxKind.None) &&
                    previousToken.TrailingTrivia.Any() &&
                    trailing.All(f => f.IsWhitespaceTrivia()))
                {
                    return(default(SyntaxTriviaList));
                }
                else
                {
                    return(trailing);
                }
            }
        }
コード例 #2
0
        private static bool IsStandardTriviaBetweenLines(SyntaxTriviaList trailingTrivia, SyntaxTriviaList leadingTrivia)
        {
            if (leadingTrivia.Any() &&
                leadingTrivia.All(f => f.IsWhitespaceTrivia()))
            {
                SyntaxTriviaList.Enumerator en = trailingTrivia.GetEnumerator();

                while (en.MoveNext())
                {
                    SyntaxKind kind = en.Current.Kind();

                    if (kind == SyntaxKind.WhitespaceTrivia)
                    {
                        continue;
                    }

                    if (kind == SyntaxKind.EndOfLineTrivia &&
                        !en.MoveNext())
                    {
                        return(true);
                    }

                    break;
                }
            }

            return(false);
        }
コード例 #3
0
        private static void Analyze(
            SyntaxNodeAnalysisContext context,
            SyntaxToken token,
            SyntaxNode node)
        {
            SyntaxTriviaList trailingTrivia = token.TrailingTrivia;
            SyntaxTriviaList leadingTrivia  = node.GetLeadingTrivia();

            if (!IsStandardTriviaBetweenLines(trailingTrivia, leadingTrivia) &&
                token
                .SyntaxTree
                .GetLineSpan(TextSpan.FromBounds(token.Span.End, node.Span.Start), context.CancellationToken)
                .GetLineCount() == 3)
            {
                SyntaxTrivia trivia = leadingTrivia
                                      .SkipWhile(f => f.IsWhitespaceTrivia())
                                      .FirstOrDefault();

                if (trivia.IsEndOfLineTrivia() &&
                    trailingTrivia.All(f => f.IsWhitespaceOrEndOfLineTrivia()) &&
                    leadingTrivia.All(f => f.IsWhitespaceOrEndOfLineTrivia()))
                {
                    context.ReportDiagnostic(
                        DiagnosticDescriptors.RemoveRedundantEmptyLine,
                        Location.Create(token.SyntaxTree, TextSpan.FromBounds(node.FullSpan.Start, trivia.Span.End)));
                }
            }
        }
コード例 #4
0
        private AstWriter WriteTrivia(string name, SyntaxTriviaList triviaList)
        {
            if (triviaList.All(x => IsIgnoredEmpty(x)))
            {
                return(this);
            }

            if (triviaList.Any())
            {
                switch (this.settings.Format)
                {
                case AstFormat.Light:
                    this.Write(" ").Write(name).Write(": [ ");
                    break;

                case AstFormat.Json:
                    this.Write(", \"").Write(name).Write("\": [ ");
                    break;

                default:
                    throw new ArgumentOutOfRangeException();
                }

                var wrote = false;
                foreach (var trivia in triviaList)
                {
                    if (!IsIgnoredEmpty(trivia))
                    {
                        if (wrote)
                        {
                            this.Write(", ");
                        }

                        wrote = true;
                        _     = this.Write(trivia);
                    }
                }

                if (wrote)
                {
                    this.Write(" ]");
                }
            }

            return(this);

            bool IsIgnoredEmpty(SyntaxTrivia trivia)
            {
                return(this.settings.IgnoreEmptyTrivia &&
                       trivia.IsKind(SyntaxKind.WhitespaceTrivia) &&
                       trivia.Span.IsEmpty);
            }
        }
コード例 #5
0
        public static void Analyze(SyntaxNodeAnalysisContext context, SwitchStatementSyntax switchStatement)
        {
            SyntaxList <SwitchSectionSyntax> sections = switchStatement.Sections;

            if (sections.Any())
            {
                AnalyzeStart(context, sections.First(), switchStatement.OpenBraceToken);
                AnalyzeEnd(context, sections.Last(), switchStatement.CloseBraceToken);

                if (sections.Count > 1)
                {
                    SwitchSectionSyntax prevSection = sections.First();

                    for (int i = 1; i < sections.Count; i++)
                    {
                        if (prevSection.Statements.LastOrDefault()?.IsKind(SyntaxKind.Block) == true)
                        {
                            SwitchSectionSyntax section = sections[i];

                            SyntaxTriviaList trailingTrivia = prevSection.GetTrailingTrivia();
                            SyntaxTriviaList leadingTrivia  = section.GetLeadingTrivia();

                            if (!IsStandardTriviaBetweenSections(trailingTrivia, leadingTrivia) &&
                                switchStatement
                                .SyntaxTree
                                .GetLineSpan(TextSpan.FromBounds(prevSection.Span.End, section.Span.Start), context.CancellationToken)
                                .GetLineCount() == 3)
                            {
                                SyntaxTrivia trivia = leadingTrivia
                                                      .SkipWhile(f => f.IsWhitespaceTrivia())
                                                      .FirstOrDefault();

                                if (trivia.IsEndOfLineTrivia() &&
                                    trailingTrivia.All(f => f.IsWhitespaceOrEndOfLineTrivia()) &&
                                    leadingTrivia.All(f => f.IsWhitespaceOrEndOfLineTrivia()))
                                {
                                    context.ReportDiagnostic(
                                        DiagnosticDescriptors.RemoveRedundantEmptyLine,
                                        Location.Create(switchStatement.SyntaxTree, TextSpan.FromBounds(section.FullSpan.Start, trivia.Span.End)));
                                }
                            }
                        }

                        prevSection = sections[i];
                    }
                }
            }
        }
コード例 #6
0
        private static bool IsFixable(ExpressionSyntax expression, SyntaxToken token)
        {
            SyntaxTriviaList expressionTrailing = expression.GetTrailingTrivia();

            if (expressionTrailing.All(f => f.IsWhitespaceOrEndOfLineTrivia()))
            {
                SyntaxTriviaList tokenLeading = token.LeadingTrivia;

                if (tokenLeading.All(f => f.IsWhitespaceOrEndOfLineTrivia()))
                {
                    SyntaxTriviaList tokenTrailing = token.TrailingTrivia;

                    int count = tokenTrailing.Count;

                    if (count == 1)
                    {
                        if (tokenTrailing[0].IsEndOfLineTrivia())
                        {
                            return(true);
                        }
                    }
                    else if (count > 1)
                    {
                        for (int i = 0; i < count - 1; i++)
                        {
                            if (!tokenTrailing[i].IsWhitespaceTrivia())
                            {
                                return(false);
                            }
                        }

                        if (tokenTrailing.Last().IsEndOfLineTrivia())
                        {
                            return(true);
                        }
                    }
                }
            }

            return(false);
        }
コード例 #7
0
        public static Task <Document> RefactorAsync(
            Document document,
            InitializerExpressionSyntax initializer,
            CancellationToken cancellationToken)
        {
            SeparatedSyntaxList <ExpressionSyntax> expressions = initializer.Expressions;
            SyntaxTriviaList openBraceTrailing = initializer.OpenBraceToken.TrailingTrivia;
            SyntaxTriviaList closeBraceLeading = initializer.CloseBraceToken.LeadingTrivia;

            SyntaxToken openBracket = Token(
                initializer.OpenBraceToken.LeadingTrivia,
                SyntaxKind.OpenBracketToken,
                (openBraceTrailing.All(f => f.IsWhitespaceTrivia())) ? default(SyntaxTriviaList) : openBraceTrailing);

            ImplicitElementAccessSyntax implicitElementAccess = ImplicitElementAccess(
                BracketedArgumentList(
                    openBracket,
                    SingletonSeparatedList(Argument(expressions[0])),
                    CloseBracketToken()));

            SyntaxToken comma = initializer.ChildTokens().FirstOrDefault(f => f.IsKind(SyntaxKind.CommaToken));

            SyntaxTriviaList commaLeading = comma.LeadingTrivia;

            SyntaxToken equalsToken = Token(
                (commaLeading.Any()) ? commaLeading : TriviaList(Space),
                SyntaxKind.EqualsToken,
                comma.TrailingTrivia);

            ExpressionSyntax valueExpression = expressions[1];

            if (closeBraceLeading.Any(f => !f.IsWhitespaceTrivia()))
            {
                valueExpression = valueExpression.AppendToTrailingTrivia(closeBraceLeading);
            }

            AssignmentExpressionSyntax assignment = SimpleAssignmentExpression(implicitElementAccess, equalsToken, valueExpression)
                                                    .WithTriviaFrom(initializer);

            return(document.ReplaceNodeAsync(initializer, assignment, cancellationToken));
        }
コード例 #8
0
ファイル: BqlRewriter.cs プロジェクト: interastar/Acuminator
        private SyntaxTriviaList GetWhitespaceTrivia(SyntaxTriviaList input)
        {
            if (input.All(t => t.IsKind(SyntaxKind.WhitespaceTrivia)))
            {
                return(input);
            }

            // If there are some unexpected trivias (non-whitespace), calculate approximate indent
            int totalLength  = input.FullSpan.Length;
            int indentLength = IndentationTrivia.FullSpan.Length;
            var trivia       = new List <SyntaxTrivia>();
            int repeatCount  = totalLength / indentLength;

            if (totalLength % indentLength > 0 || indentLength % totalLength > 0)
            {
                repeatCount++;
            }
            for (int i = 0; i < repeatCount; i++)
            {
                trivia.AddRange(IndentationTrivia);
            }
            return(trivia.ToSyntaxTriviaList());
        }
コード例 #9
0
 static bool AnalyzeTrivia(SyntaxTriviaList trivia)
 {
     return(trivia.All(f => f.IsKind(SyntaxKind.WhitespaceTrivia, SyntaxKind.EndOfLineTrivia, SyntaxKind.SingleLineCommentTrivia)));
 }
コード例 #10
0
 static bool HasNoneWhitespaceTrivia(SyntaxTriviaList getLeadingTrivia)
 {
     return(getLeadingTrivia.All(t => t.IsKind(SyntaxKind.EndOfLineTrivia) || t.IsKind(SyntaxKind.WhitespaceTrivia)));
 }
コード例 #11
0
        public override async Task RegisterCodeFixesAsync(CodeFixContext context)
        {
            SyntaxNode root = await context.GetSyntaxRootAsync().ConfigureAwait(false);

            if (!TryFindFirstAncestorOrSelf(root, context.Span, out CompilationUnitSyntax compilationUnit))
            {
                return;
            }

            Document   document   = context.Document;
            Diagnostic diagnostic = context.Diagnostics[0];

            switch (diagnostic.Id)
            {
            case DiagnosticIdentifiers.NormalizeWhitespaceAtEndOfFile:
            {
                bool preferNewLineAtEndOfFile = document.GetConfigOptions(compilationUnit.SyntaxTree).PreferNewLineAtEndOfFile() ?? false;

                CodeAction codeAction = CodeAction.Create(
                    (preferNewLineAtEndOfFile) ? CodeFixTitles.AddNewLine : CodeFixTitles.RemoveNewLine,
                    ct =>
                    {
                        SyntaxToken endOfFile    = compilationUnit.EndOfFileToken;
                        SyntaxTriviaList leading = endOfFile.LeadingTrivia;
                        SyntaxToken oldToken;
                        SyntaxToken newToken;

                        if (!preferNewLineAtEndOfFile)
                        {
                            if (leading.Any())
                            {
                                SyntaxTrivia last = leading.Last();

                                if (last.GetStructure() is DirectiveTriviaSyntax directive)
                                {
                                    SyntaxTriviaList trailing = directive.GetTrailingTrivia();

                                    DirectiveTriviaSyntax newDirective = directive.WithTrailingTrivia(trailing.RemoveAt(trailing.Count - 1));

                                    return(document.ReplaceNodeAsync(directive, newDirective, ct));
                                }
                                else
                                {
                                    oldToken  = endOfFile;
                                    int index = leading.Count - 1;

                                    for (int i = leading.Count - 2; i >= 0; i--)
                                    {
                                        if (leading[i].IsWhitespaceOrEndOfLineTrivia())
                                        {
                                            index--;
                                        }
                                    }

                                    newToken = oldToken.WithLeadingTrivia(leading.RemoveRange(index, leading.Count - index));
                                }
                            }
                            else
                            {
                                oldToken = endOfFile.GetPreviousToken();
                                SyntaxTriviaList trailing = oldToken.TrailingTrivia;
                                newToken = oldToken.WithTrailingTrivia(trailing.RemoveAt(trailing.Count - 1));
                            }
                        }
                        else if (leading.Any())
                        {
                            oldToken = endOfFile;

                            if (leading.Span.Start == 0 &&
                                leading.All(f => f.IsWhitespaceOrEndOfLineTrivia()))
                            {
                                newToken = oldToken.WithoutLeadingTrivia();
                            }
                            else
                            {
                                newToken = oldToken.AppendEndOfLineToLeadingTrivia();
                            }
                        }
                        else
                        {
                            oldToken = endOfFile.GetPreviousToken();
                            newToken = oldToken.AppendEndOfLineToTrailingTrivia();
                        }

                        return(document.ReplaceTokenAsync(oldToken, newToken, ct));
                    },
                    GetEquivalenceKey(diagnostic));

                context.RegisterCodeFix(codeAction, diagnostic);
                break;
            }
            }
        }