コード例 #1
0
        public static InitializerExpressionSyntax ToMultiLine(InitializerExpressionSyntax initializer, CancellationToken cancellationToken)
        {
            SyntaxNode parent = initializer.Parent;

            if (parent.IsKind(SyntaxKind.ObjectCreationExpression) &&
                !initializer.IsKind(SyntaxKind.CollectionInitializerExpression))
            {
                return(initializer
                       .WithExpressions(
                           SeparatedList(
                               initializer.Expressions.Select(expression => expression.WithLeadingTrivia(NewLine())))));
            }
            else
            {
                SyntaxTrivia trivia = initializer.GetIndentation(cancellationToken);

                SyntaxTriviaList braceTrivia      = TriviaList(NewLine(), trivia);
                SyntaxTriviaList expressionTrivia = TriviaList(NewLine(), trivia, SingleIndentation(trivia));

                return(initializer
                       .WithExpressions(
                           SeparatedList(
                               initializer.Expressions.Select(expression => expression.WithLeadingTrivia(expressionTrivia))))
                       .WithOpenBraceToken(initializer.OpenBraceToken.WithLeadingTrivia(braceTrivia))
                       .WithCloseBraceToken(initializer.CloseBraceToken.WithLeadingTrivia(braceTrivia)));
            }
        }
コード例 #2
0
        public static InitializerExpressionSyntax ToMultiLine(InitializerExpressionSyntax initializer, CancellationToken cancellationToken)
        {
            SyntaxNode parent = initializer.Parent;

            if (parent.IsKind(SyntaxKind.ObjectCreationExpression) &&
                !initializer.IsKind(SyntaxKind.CollectionInitializerExpression))
            {
                return(initializer
                       .WithExpressions(
                           SeparatedList(
                               initializer.Expressions.Select(expression => expression.WithLeadingTrivia(NewLine())))));
            }
            else
            {
                string indent = GetLineIndent(initializer, cancellationToken);

                SyntaxTriviaList braceTrivia      = ParseLeadingTrivia(Environment.NewLine + indent);
                SyntaxTriviaList expressionTrivia = ParseLeadingTrivia(Environment.NewLine + IncreaseIndent(indent));

                return(initializer
                       .WithExpressions(
                           SeparatedList(
                               initializer.Expressions.Select(expression => expression.WithLeadingTrivia(expressionTrivia))))
                       .WithOpenBraceToken(initializer.OpenBraceToken.WithLeadingTrivia(braceTrivia))
                       .WithCloseBraceToken(initializer.CloseBraceToken.WithLeadingTrivia(braceTrivia)));
            }
        }
コード例 #3
0
        private static InitializerExpressionSyntax GetMultilineInitializer(InitializerExpressionSyntax initializer)
        {
            SyntaxNode parent = initializer.Parent;

            if (parent.IsKind(SyntaxKind.ObjectCreationExpression) &&
                !initializer.IsKind(SyntaxKind.CollectionInitializerExpression))
            {
                return(initializer
                       .WithExpressions(
                           SeparatedList(
                               initializer.Expressions.Select(expression => expression.WithLeadingTrivia(SyntaxHelper.NewLine))))
                       .WithAdditionalAnnotations(Formatter.Annotation));
            }

            SyntaxTriviaList indent  = initializer.GetIndentTrivia();
            SyntaxTriviaList indent2 = indent.Add(SyntaxHelper.DefaultIndent);

            indent  = indent.Insert(0, SyntaxHelper.NewLine);
            indent2 = indent2.Insert(0, SyntaxHelper.NewLine);

            return(initializer
                   .WithExpressions(
                       SeparatedList(
                           initializer.Expressions.Select(expression => expression.WithLeadingTrivia(indent2))))
                   .WithOpenBraceToken(initializer.OpenBraceToken.WithLeadingTrivia(indent))
                   .WithCloseBraceToken(initializer.CloseBraceToken.WithLeadingTrivia(indent))
                   .WithAdditionalAnnotations(Formatter.Annotation));
        }
コード例 #4
0
        public override SyntaxNode VisitInitializerExpression(InitializerExpressionSyntax node)
        {
            var containingProperty = node.FirstAncestorOrSelf <PropertyDeclarationSyntax>();

            if (containingProperty != null && containingProperty.Identifier.ToString() == "SelectorExpression" &&
                containingProperty.FirstAncestorOrSelf <ClassDeclarationSyntax>().Identifier.ToString().Contains("Mapper"))
            {
                if (node.Expressions.Count == 0)
                {
                    node = node.WithOpenBraceToken(GetOpenBraceTokenWithEmptyCustomCode());
                }
                else if (node.Expressions.Count == 1)
                {
                    var newExpression = AddLeadingTriviaComment(AddTrailingTriviaComment(node.Expressions.Single()));
                    node = node.WithExpressions(node.Expressions.RemoveAt(0).Add(newExpression));
                }
                else
                {
                    var firstExpression = AddLeadingTriviaComment(node.Expressions.First());

                    var lastExpression      = AddTrailingTriviaComment(node.Expressions.Last());
                    var lastExpressionIndex = node.Expressions.Count - 1;

                    node = node.WithExpressions(node.Expressions.RemoveAt(lastExpressionIndex).RemoveAt(0).Insert(0, firstExpression).Add(lastExpression));
                }
            }

            return(base.VisitInitializerExpression(node));
        }
        private static InitializerExpressionSyntax GetMultilineInitializer(InitializerExpressionSyntax initializer)
        {
            SyntaxNode parent = initializer.Parent;

            if (parent.IsKind(SyntaxKind.ObjectCreationExpression) &&
                !initializer.IsKind(SyntaxKind.CollectionInitializerExpression))
            {
                return(initializer
                       .WithExpressions(
                           SeparatedList(
                               initializer.Expressions.Select(expression => expression.WithLeadingTrivia(CSharpFactory.NewLineTrivia()))))
                       .WithFormatterAnnotation());
            }

            SyntaxTriviaList indent  = SyntaxUtility.GetIndentTrivia(initializer);
            SyntaxTriviaList indent2 = indent.Add(CSharpFactory.IndentTrivia());

            indent  = indent.Insert(0, CSharpFactory.NewLineTrivia());
            indent2 = indent2.Insert(0, CSharpFactory.NewLineTrivia());

            return(initializer
                   .WithExpressions(
                       SeparatedList(
                           initializer.Expressions.Select(expression => expression.WithLeadingTrivia(indent2))))
                   .WithOpenBraceToken(initializer.OpenBraceToken.WithLeadingTrivia(indent))
                   .WithCloseBraceToken(initializer.CloseBraceToken.WithLeadingTrivia(indent))
                   .WithFormatterAnnotation());
        }
コード例 #6
0
        public static InitializerExpressionSyntax ToMultiLine(InitializerExpressionSyntax initializer, CancellationToken cancellationToken)
        {
            SyntaxNode parent = initializer.Parent;

            SyntaxTrivia endOfLine = DetermineEndOfLine(initializer);

            if (parent.IsKind(SyntaxKind.ObjectCreationExpression) &&
                !initializer.IsKind(SyntaxKind.CollectionInitializerExpression))
            {
                return(initializer
                       .WithExpressions(
                           SeparatedList(
                               initializer.Expressions.Select(expression => expression.WithLeadingTrivia(endOfLine)))));
            }
            else
            {
                IndentationAnalysis indentationAnalysis = AnalyzeIndentation(initializer, cancellationToken);

                SyntaxTriviaList braceTrivia      = TriviaList(endOfLine, indentationAnalysis.Indentation);
                SyntaxTriviaList expressionTrivia = TriviaList(endOfLine, indentationAnalysis.GetIncreasedIndentationTrivia());

                return(initializer
                       .WithExpressions(
                           SeparatedList(
                               initializer.Expressions.Select(expression => expression.WithLeadingTrivia(expressionTrivia))))
                       .WithOpenBraceToken(initializer.OpenBraceToken.WithLeadingTrivia(braceTrivia))
                       .WithCloseBraceToken(initializer.CloseBraceToken.WithLeadingTrivia(braceTrivia)));
            }
        }
コード例 #7
0
        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));
        }
コード例 #8
0
ファイル: CodeFixProvider.cs プロジェクト: gamert/libGithub
        private static async Task <Document> PopulateMissingAssignmentsAsync(Document document,
                                                                             InitializerExpressionSyntax objectInitializer, string[] unassignedMemberNames, CancellationToken ct)
        {
            // Can't manipulate syntax without a syntax root
            SyntaxNode oldRoot = await document.GetSyntaxRootAsync(ct).ConfigureAwait(false);

            if (oldRoot == null)
            {
                return(document);
            }

            SeparatedSyntaxList <ExpressionSyntax> expressions = objectInitializer.Expressions;

            // Add missing member assignments in object initializer
            SeparatedSyntaxList <ExpressionSyntax> newExpressions =
                expressions.AddRange(
                    unassignedMemberNames.Select(
                        memberName => SyntaxFactory.AssignmentExpression(SyntaxKind.SimpleAssignmentExpression,
                                                                         SyntaxFactory.IdentifierName(memberName), SyntaxFactory.IdentifierName(string.Empty))));

            InitializerExpressionSyntax newObjectInitializer = objectInitializer.WithExpressions(
                newExpressions);

            // Reformat fails due to the codefix code not compiling..
            //            newObjectInitializer =
            //                (InitializerExpressionSyntax) Formatter.Format(newObjectInitializer, MSBuildWorkspace.Create());

            SyntaxNode newRoot = oldRoot.ReplaceNode(objectInitializer, newObjectInitializer);

            return(document.WithSyntaxRoot(newRoot));
        }
コード例 #9
0
        private static async Task <Document> PopulateMissingAssignmentsAsync(Document document,
                                                                             InitializerExpressionSyntax objectInitializer,
                                                                             string[] unassignedMemberNames,
                                                                             CancellationToken ct)
        {
            // Can't manipulate syntax without a syntax root
            SyntaxNode oldRoot = await document.GetSyntaxRootAsync(ct).ConfigureAwait(false);

            if (oldRoot == null)
            {
                return(document);
            }

            SeparatedSyntaxList <ExpressionSyntax> expressions = objectInitializer.Expressions;

            // Add missing member assignments in object initializer.
            // End of line honors .editorconfig and/or system preferences, but it does NOT honor if a different EOL used in the file.
            SeparatedSyntaxList <ExpressionSyntax> newExpressions = expressions
                                                                    .AddRange(unassignedMemberNames.Select(CreateEmptyMemberAssignmentExpression));

            InitializerExpressionSyntax newObjectInitializer = objectInitializer.WithExpressions(newExpressions);

            SyntaxNode newRoot = oldRoot.ReplaceNode(objectInitializer, newObjectInitializer);

            return(document.WithSyntaxRoot(newRoot));
        }
        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));
        }
コード例 #11
0
        public override SyntaxNode VisitInitializerExpression(InitializerExpressionSyntax node)
        {
            TypeSyntax typeToCast = null;
            var        rankCount  = 0;

            if (node.Parent is ArrayCreationExpressionSyntax array)
            {
                typeToCast = array.Type.ElementType;
                rankCount  = array.Type.RankSpecifiers.Count - 1;
            }
            else if (node.IsKind(SyntaxKind.CollectionInitializerExpression) && node.Parent is ObjectCreationExpressionSyntax obj) // e.g. List<int> { document.Field }
            {
                var name = obj.Type as GenericNameSyntax;
                if (name == null && obj.Type is QualifiedNameSyntax qualifiedName)
                {
                    name = qualifiedName.Right as GenericNameSyntax;
                }

                if (name != null)
                {
                    var arguments = name.TypeArgumentList.Arguments;
                    if (arguments.Count == 1)
                    {
                        typeToCast = arguments[0];
                    }
                }
            }

            if (typeToCast != null)
            {
                var castedExpression = new SeparatedSyntaxList <ExpressionSyntax>();
                foreach (var expression in node.Expressions)
                {
                    if (expression is InitializerExpressionSyntax initializerExpression) // e.g. List<int> { document.Field }
                    {
                        var expressions = initializerExpression.Expressions;
                        if (expressions.Count == 1)
                        {
                            var innerExpression = expressions[0];

                            expressions           = expressions.Replace(innerExpression, CastExpression(typeToCast, rankCount, innerExpression));
                            initializerExpression = initializerExpression.WithExpressions(expressions);
                        }

                        castedExpression = castedExpression.Add(initializerExpression);
                        continue;
                    }

                    castedExpression = castedExpression.Add(CastExpression(typeToCast, rankCount, expression));
                }

                return(node.WithExpressions(castedExpression));
            }

            return(node);
        }
コード例 #12
0
        private static Document RemoveElementInitializer(
            ExpressionSyntax elementInitializer,
            InitializerExpressionSyntax objectInitializer,
            SyntaxNode root,
            Document document)
        {
            var newElementInitializers = objectInitializer.Expressions.Remove(elementInitializer);
            var newRoot = root.ReplaceNode(objectInitializer, objectInitializer.WithExpressions(newElementInitializers));

            return(document.WithSyntaxRoot(newRoot));
        }
コード例 #13
0
        public static Task <Document> RefactorAsync(
            Document document,
            InitializerExpressionSyntax initializer,
            CancellationToken cancellationToken)
        {
            SeparatedSyntaxList <ExpressionSyntax> expressions = initializer.Expressions;

            for (int i = 0; i < expressions.Count; i++)
            {
                expressions = expressions.ReplaceAt(i, CreateNewExpression((InitializerExpressionSyntax)expressions[i]));
            }

            InitializerExpressionSyntax newInitializer = initializer.WithExpressions(expressions);

            return(document.ReplaceNodeAsync(initializer, newInitializer, cancellationToken));
        }
コード例 #14
0
        public override SyntaxNode VisitInitializerExpression(InitializerExpressionSyntax node)
        {
            var parentProperty   = node.FirstAncestorOrSelf <PropertyDeclarationSyntax>();
            var parentInvocation = node.FirstAncestorOrSelf <InvocationExpressionSyntax>();

            if (parentProperty != null && parentProperty.Identifier.Text == "SelectorExpression" ||
                parentInvocation != null && parentInvocation.ToString().Contains("SelectorExpression"))
            {
                var initializerExpressions    = GenerateInitializerExpressions(_metadata, "", "p.").ToList();
                var expressionsWithSeparators = node.AddExpressions(initializerExpressions.ToArray()).Expressions.GetWithSeparators();

                // This section is here only to format code well. Namely, in initializer expression, to add comma token after each expression and newline after comma.
                var list = new List <SyntaxNodeOrToken>();
                var expressionTrailingTrivia = new List <SyntaxTrivia>();

                foreach (var item in expressionsWithSeparators.ToList())
                {
                    // This is required if we have a custom code trivia which is attached to expression node, but should be attached after comma-token.
                    if (item.IsToken)
                    {
                        expressionTrailingTrivia.Add(SyntaxExtenders.EndOfLineTrivia);
                        list.Add(item.AsToken().WithTrailingTrivia(expressionTrailingTrivia.ToArray()));
                        expressionTrailingTrivia.Clear();
                    }

                    else
                    {
                        expressionTrailingTrivia = item.GetTrailingTrivia().ToList();
                        list.Add(item.WithTrailingTrivia());
                    }
                }

                if (list.Any() && list.Last().IsNode)
                {
                    var item = list.Last();
                    list.Remove(item);
                    list.Add(item.WithTrailingTrivia(expressionTrailingTrivia));
                }

                return(node.WithExpressions(SyntaxFactory.SeparatedList <ExpressionSyntax>(list)));
            }

            return(base.VisitInitializerExpression(node));
        }
コード例 #15
0
        public static async Task <Document> RefactorAsync(
            Document document,
            InitializerExpressionSyntax initializer,
            CancellationToken cancellationToken = default(CancellationToken))
        {
            SyntaxNode oldRoot = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);

            InitializerExpressionSyntax newInitializer = initializer
                                                         .WithExpressions(
                SeparatedList(
                    initializer.Expressions.Select(expression => expression.WithoutTrivia())))
                                                         .WithOpenBraceToken(Token(SyntaxKind.OpenBraceToken))
                                                         .WithCloseBraceToken(Token(SyntaxKind.CloseBraceToken))
                                                         .WithFormatterAnnotation();

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

            return(document.WithSyntaxRoot(newRoot));
        }
コード例 #16
0
        private InitializerExpressionSyntax RewriteInitializer(InitializerExpressionSyntax initializer)
        {
            var expressions = new List <ExpressionSyntax>();

            foreach (var expression in initializer.Expressions)
            {
                var expr = expression.WithLeadingTrivia(SyntaxHelper.Whitespace(20));
                expressions.Add(expr);
            }

            initializer = initializer.WithExpressions(
                SyntaxFactory.SeparatedList(
                    expressions,
                    Enumerable.Repeat(
                        SyntaxFactory.Token(SyntaxKind.CommaToken).WithTrailingTrivia(SyntaxHelper.EndOfLineTrivia),
                        expressions.Count - 1)));

            return(initializer);
        }
コード例 #17
0
        private static async Task <Document> FormatInitializerOnSingleLineAsync(
            Document document,
            InitializerExpressionSyntax initializer,
            CancellationToken cancellationToken)
        {
            SyntaxNode oldRoot = await document.GetSyntaxRootAsync(cancellationToken);

            InitializerExpressionSyntax newInitializer = initializer
                                                         .WithExpressions(
                SeparatedList(
                    initializer.Expressions.Select(expression => expression.WithoutTrivia())))
                                                         .WithOpenBraceToken(Token(SyntaxKind.OpenBraceToken))
                                                         .WithCloseBraceToken(Token(SyntaxKind.CloseBraceToken))
                                                         .WithAdditionalAnnotations(Formatter.Annotation);

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

            return(document.WithSyntaxRoot(newRoot));
        }
コード例 #18
0
        private async Task <Document> AddMissingVariables(Document document, InitializerExpressionSyntax initializerNode, CancellationToken c)
        {
            var model = await document.GetSemanticModelAsync();

            var type        = model.GetTypeInfo(initializerNode.Parent).Type;
            var all         = model.LookupSymbols(initializerNode.SpanStart, type).Where(m => m.Kind == SymbolKind.Field || m.Kind == SymbolKind.Property);
            var foundOnes   = initializerNode.Expressions.Where(e => e is AssignmentExpressionSyntax).Select(e => e as AssignmentExpressionSyntax).Select(e => e.Left.ToString());
            var missingOnes = all.Select(s => s.Name).Except(foundOnes);

            var newOnes = missingOnes.Select(missingName =>
            {
                var fieldOrPropertySymbol = all.Where(s => s.Name == missingName).Single();
                var declarationSyntax     = fieldOrPropertySymbol.DeclaringSyntaxReferences.Single().GetSyntax();

                TypeSyntax typeSyntax = null;
                switch (declarationSyntax.Kind())
                {
                case SyntaxKind.VariableDeclarator:
                    typeSyntax = ((declarationSyntax as VariableDeclaratorSyntax).Parent as VariableDeclarationSyntax).Type;
                    break;

                case SyntaxKind.FieldDeclaration:
                    typeSyntax = (declarationSyntax as PropertyDeclarationSyntax).Type;
                    break;
                }

                var name         = SyntaxFactory.IdentifierName(missingName);
                var defaultValue = SyntaxFactory.DefaultExpression(typeSyntax);

                return(SyntaxFactory.AssignmentExpression(SyntaxKind.SimpleAssignmentExpression, name, defaultValue));
            });

            var newInitializerList = initializerNode.Expressions.AddRange(newOnes);
            var newInitializerNode = initializerNode.WithExpressions(newInitializerList);

            var root = await document.GetSyntaxRootAsync();

            var newRoot = root.ReplaceNode(initializerNode, newInitializerNode);

            var newDocument = document.WithSyntaxRoot(newRoot);

            return(newDocument);
        }
コード例 #19
0
        private static SyntaxNode RewriteInitializer(InitializerExpressionSyntax initializer)
        {
            var existingItems = new List <ExpressionSyntax>(initializer.Expressions);
            var last          = existingItems.Last();

            existingItems.Remove(last);
            existingItems.Add(last.WithoutTrailingTrivia());

            var existingSeparators = initializer.Expressions.GetSeparators();
            var newSeparators      = new List <SyntaxToken>(existingSeparators);

            newSeparators.Add(SyntaxFactory.Token(SyntaxKind.CommaToken).WithTrailingTrivia(last.GetTrailingTrivia()));

            var newInitializerExpressions = SyntaxFactory.SeparatedList(
                existingItems,
                newSeparators);

            var fixedInitializer = initializer.WithExpressions(newInitializerExpressions);

            return(fixedInitializer);
        }
コード例 #20
0
        private async Task <Document> InitizalizeWithLocals(Document document, InitializerExpressionSyntax objectInitializer, CancellationToken cancellationToken)
        {
            var semanticModel = await document.GetSemanticModelAsync(cancellationToken);

            var objectCreationExpression = objectInitializer.FindContainer <ObjectCreationExpressionSyntax>();
            var createdObjectType        = ModelExtensions.GetTypeInfo(semanticModel, objectCreationExpression).Type;
            var mappingSourceFinder      = new LocalScopeMappingSourceFinder(semanticModel, objectInitializer);
            var propertiesToSet          = ObjectHelper.GetPublicPropertySymbols(createdObjectType).Where(x => x.SetMethod?.DeclaredAccessibility == Accessibility.Public);
            var initExpressions          = propertiesToSet.Aggregate(objectInitializer.Expressions, (expr, property) =>
            {
                var mappingSource = mappingSourceFinder.FindMappingSource(property.Name, property.Type);
                if (mappingSource != null)
                {
                    var assignmentExpression = SyntaxFactory.AssignmentExpression(SyntaxKind.SimpleAssignmentExpression, SyntaxFactory.IdentifierName(property.Name), mappingSource.Expression);
                    return(expr.Add(assignmentExpression));
                }
                return(expr);
            });

            return(await document.ReplaceNodes(objectInitializer, objectInitializer.WithExpressions(initExpressions), cancellationToken));
        }
コード例 #21
0
        private static InitializerExpressionSyntax RemoveTrailingComma(InitializerExpressionSyntax initializer)
        {
            SeparatedSyntaxList <ExpressionSyntax> expressions = initializer.Expressions;

            SyntaxToken trailingComma = expressions.GetTrailingSeparator();

            SeparatedSyntaxList <ExpressionSyntax> newExpressions = expressions.ReplaceSeparator(
                trailingComma,
                SyntaxFactory.MissingToken(SyntaxKind.CommaToken));

            int lastIndex = expressions.Count - 1;

            SyntaxTriviaList newTrailingTrivia = expressions[lastIndex]
                                                 .GetTrailingTrivia()
                                                 .AddRange(trailingComma.LeadingTrivia)
                                                 .AddRange(trailingComma.TrailingTrivia);

            ExpressionSyntax newExpression = newExpressions[lastIndex].WithTrailingTrivia(newTrailingTrivia);

            newExpressions = newExpressions.ReplaceAt(lastIndex, newExpression);

            return(initializer.WithExpressions(newExpressions));
        }
コード例 #22
0
        private static Task <Document> RefactorAsync(
            Document document,
            InitializerExpressionSyntax initializer,
            IEnumerable <IPropertySymbol> propertySymbols,
            bool initializeToDefault,
            CancellationToken cancellationToken)
        {
            IdentifierNameSyntax missingIdentifierName = (initializeToDefault)
                ? null
                : IdentifierName(MissingToken(TriviaList(), SyntaxKind.IdentifierToken, TriviaList(Space)));

            IEnumerable <AssignmentExpressionSyntax> newExpressions = propertySymbols
                                                                      .OrderBy(f => f.Name)
                                                                      .Select(propertySymbol =>
            {
                return(SimpleAssignmentExpression(
                           IdentifierName(propertySymbol.Name),
                           (initializeToDefault)
                            ? propertySymbol.Type.GetDefaultValueSyntax(document.GetDefaultSyntaxOptions())
                            : missingIdentifierName));
            });

            InitializerExpressionSyntax newInitializer = initializer
                                                         .WithExpressions(initializer.Expressions.AddRange(newExpressions));

            if (initializer.IsMultiLine())
            {
                newInitializer = newInitializer.ReplaceNode(
                    newInitializer.Expressions.Last(),
                    newInitializer.Expressions.Last().AppendToTrailingTrivia(NewLine()));
            }

            newInitializer = newInitializer.WithFormatterAnnotation();

            return(document.ReplaceNodeAsync(initializer, newInitializer, cancellationToken));
        }
コード例 #23
0
        public override SyntaxNode VisitInitializerExpression(InitializerExpressionSyntax node)
        {
            var parentProperty   = node.FirstAncestorOrSelf <PropertyDeclarationSyntax>();
            var parentInvocation = node.FirstAncestorOrSelf <InvocationExpressionSyntax>();

            if (parentProperty != null && parentProperty.Identifier.Text == "SelectorExpression" ||
                parentInvocation != null && parentInvocation.ToString().Contains("SelectorExpression"))
            {
                var initializerExpressions = GenerateInitializerExpressions(_metadata, "", "p.").ToList();
                var nodeTokenList          = SyntaxFactory.NodeOrTokenList(node.ChildNodesAndTokens())
                                             .RemoveAt(node.ChildNodesAndTokens().Count - 1)
                                             .RemoveAt(0);

                foreach (var exp in initializerExpressions)
                {
                    nodeTokenList = nodeTokenList.Add(exp);
                    nodeTokenList = nodeTokenList.Add(SyntaxFactory.Token(SyntaxKind.CommaToken).AppendNewLine());
                }

                return(node.WithExpressions(SyntaxFactory.SeparatedList <ExpressionSyntax>(nodeTokenList)));
            }

            return(base.VisitInitializerExpression(node));
        }
コード例 #24
0
        private static Task <Document> FormatInitializerOnSingleLineAsync(
            Document document,
            InitializerExpressionSyntax initializer,
            CancellationToken cancellationToken)
        {
            cancellationToken.ThrowIfCancellationRequested();

            SyntaxToken trailingComma = initializer.Expressions.GetTrailingSeparator();

            if (trailingComma == default)
            {
                return(SyntaxFormatter.ToSingleLineAsync(document, initializer, cancellationToken));
            }

            SyntaxNode parent = initializer.Parent;

            initializer = initializer
                          .ReplaceWhitespace(SyntaxFactory.ElasticMarker, TextSpan.FromBounds(initializer.FullSpan.Start, initializer.Span.End))
                          .WithFormatterAnnotation();

            SeparatedSyntaxList <ExpressionSyntax> expressions = initializer.Expressions;

            expressions = expressions.ReplaceAt(0, expressions.First().WithTrailingTrivia(SyntaxFactory.Space));

            expressions = expressions.ReplaceSeparator(expressions.GetSeparator(0), SyntaxFactory.MissingToken(SyntaxKind.CommaToken));

            initializer = initializer.WithExpressions(expressions);

            SyntaxNode newParent = GetNewParent();

            return(document.ReplaceNodeAsync(parent, newParent, cancellationToken));

            SyntaxNode GetNewParent()
            {
                switch (parent)
                {
                case ObjectCreationExpressionSyntax objectCreation:
                {
                    objectCreation = objectCreation.WithInitializer(initializer);

                    ArgumentListSyntax argumentList = objectCreation.ArgumentList;

                    if (argumentList != null)
                    {
                        return(objectCreation.WithArgumentList(argumentList.WithoutTrailingTrivia()));
                    }
                    else
                    {
                        return(objectCreation.WithType(objectCreation.Type.WithoutTrailingTrivia()));
                    }
                }

                case ArrayCreationExpressionSyntax arrayCreation:
                {
                    return(arrayCreation
                           .WithInitializer(initializer)
                           .WithType(arrayCreation.Type.WithoutTrailingTrivia()));
                }

                case ImplicitArrayCreationExpressionSyntax implicitArrayCreation:
                {
                    return(implicitArrayCreation
                           .WithInitializer(initializer)
                           .WithCloseBracketToken(implicitArrayCreation.CloseBracketToken.WithoutTrailingTrivia()));
                }
                }

                throw new InvalidOperationException();
            }
        }
コード例 #25
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));
        }
コード例 #26
0
        private static SyntaxNode RewriteInitializer(InitializerExpressionSyntax initializer)
        {
            var existingItems = new List<ExpressionSyntax>(initializer.Expressions);
            var last = existingItems.Last();
            existingItems.Remove(last);
            existingItems.Add(last.WithoutTrailingTrivia());

            var existingSeparators = initializer.Expressions.GetSeparators();
            var newSeparators = new List<SyntaxToken>(existingSeparators);
            newSeparators.Add(SyntaxFactory.Token(SyntaxKind.CommaToken).WithTrailingTrivia(last.GetTrailingTrivia()));

            var newInitializerExpressions = SyntaxFactory.SeparatedList(
                existingItems,
                newSeparators);

            var fixedInitializer = initializer.WithExpressions(newInitializerExpressions);
            return fixedInitializer;
        }