private static async Task <Document> RefactorAsync(
            Document document,
            ArgumentSyntax argument,
            ArgumentListSyntax argumentList,
            CancellationToken cancellationToken)
        {
            SyntaxNode oldRoot = await document.GetSyntaxRootAsync(cancellationToken);

            SeparatedSyntaxList <ArgumentSyntax> arguments = argumentList.Arguments;

            int index = arguments.IndexOf(argument);

            ArgumentSyntax nextArgument = arguments[index + 1]
                                          .WithTriviaFrom(argument);

            arguments = arguments
                        .Replace(argument, nextArgument);

            arguments = arguments
                        .Replace(arguments[index + 1], argument.WithTriviaFrom(nextArgument));

            ArgumentListSyntax newNode = argumentList.WithArguments(arguments);

            SyntaxNode newRoot = oldRoot.ReplaceNode(argumentList, newNode);

            return(document.WithSyntaxRoot(newRoot));
        }
        private static async Task <Document> RefactorAsync(
            Document document,
            ParameterSyntax parameter,
            ParameterListSyntax parameterList,
            CancellationToken cancellationToken)
        {
            SyntaxNode oldRoot = await document.GetSyntaxRootAsync(cancellationToken);

            SeparatedSyntaxList <ParameterSyntax> parameters = parameterList.Parameters;

            int index = parameters.IndexOf(parameter);

            ParameterSyntax nextParameter = parameters[index + 1]
                                            .WithTriviaFrom(parameter);

            parameters = parameters
                         .Replace(parameter, nextParameter);

            parameters = parameters
                         .Replace(parameters[index + 1], parameter.WithTriviaFrom(nextParameter));

            ParameterListSyntax newNode = parameterList.WithParameters(parameters);

            SyntaxNode newRoot = oldRoot.ReplaceNode(parameterList, newNode);

            return(document.WithSyntaxRoot(newRoot));
        }
        public override SyntaxNode VisitVariableDeclaration(VariableDeclarationSyntax node)
        {
            // determination of the type of the variable(s)
            var typeSymbol = (ITypeSymbol)this.SemanticModel.GetSymbolInfo(node.Type).Symbol;

            bool changed = false;

            // you could declare more than one variable with one expression
            SeparatedSyntaxList <VariableDeclaratorSyntax> vs = node.Variables;
            // we create a space to improve readability
            SyntaxTrivia space = SyntaxFactory.SyntaxTrivia(SyntaxKind.WhitespaceTrivia, " ");

            for (var i = 0; i < node.Variables.Count; i++)
            {
                // there is not an initialization
                if (this.SemanticModel.GetSymbolInfo(node.Type).Symbol.ToString() == "int" &&
                    node.Variables[i].Initializer == null)
                {
                    // we create a new espression "42"
                    // preceded by the space we create earlier
                    ExpressionSyntax es = SyntaxFactory.ParseExpression("42")
                                          .WithLeadingTrivia(Space);

                    // basically we create an assignment to the espression we just created
                    EqualsValueClauseSyntax evc = SyntaxFactory.EqualsValueClause(es)
                                                  .WithLeadingTrivia(space);

                    // we replace the null initializer with ours
                    vs = vs.Replace(vs.ElementAt(i), vs.ElementAt(i).WithInitializer(evc));

                    changed = true;
                }

                // there is an initialization but it's not to 42
                if (this.SemanticModel.GetSymbolInfo(node.Type).Symbol.ToString() == "int" &&
                    node.Variables[i].Initializer != null &&
                    !node.Variables[i].Initializer.Value.IsEquivalentTo(SyntaxFactory.ParseExpression("42")))
                {
                    ExpressionSyntax es = SyntaxFactory.ParseExpression("42")
                                          .WithLeadingTrivia(Space);

                    EqualsValueClauseSyntax evc = SyntaxFactory.EqualsValueClause(es);

                    vs = vs.Replace(vs.ElementAt(i), vs.ElementAt(i).WithInitializer(evc));

                    changed = true;
                }
            }

            if (changed == true)
            {
                return(node.WithVariables(vs));
            }

            return(base.VisitVariableDeclaration(node));
        }
Esempio n. 4
0
        public override SyntaxNode VisitArgumentList(ArgumentListSyntax node)
        {
            SeparatedSyntaxList <ArgumentSyntax> arguments = node.Arguments;

            for (int i = 0; i < arguments.Count; i++)
            {
                ArgumentSyntax arg = arguments[i];
                if (arg.IsKind(SyntaxKind.RangeArgument))
                {
                    SyntaxToken tokn = arguments[i].GetFirstToken();
                    if (tokn.IsKind(SyntaxKind.IntegerLiteralToken))
                    {
                        if (tokn.ValueText == "1")
                        {
                            var newIndexStart = SyntaxFactory.IntegerLiteralToken(
                                "0", LiteralBase.Decimal, TypeCharacter.IntegerLiteral, 0);

                            var newArrayArgument = arg.ReplaceToken(tokn, newIndexStart);
                            arguments = arguments.Replace(arg, newArrayArgument);
                        }
                    }
                }
            }

            return(node.WithArguments(arguments));
        }
        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));
        }
        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));
        }
        private SeparatedSyntaxList <ArgumentSyntax> GetArgumentsWithFirstAsPairIdentifierArgument(SeparatedSyntaxList <ArgumentSyntax> arguments)
        {
            var argument     = arguments[0];
            var memberAccess = (MemberAccessExpressionSyntax)argument.Expression;
            var identifier   = (IdentifierNameSyntax)memberAccess.Expression;

            return(arguments.Replace(argument, argument.WithExpression(identifier)));
        }
Esempio n. 8
0
        public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context)
        {
            if (!Settings.IsCodeFixEnabled(CodeFixIdentifiers.MoveBaseClassBeforeAnyInterface))
            {
                return;
            }

            SyntaxNode root = await context.GetSyntaxRootAsync().ConfigureAwait(false);

            BaseListSyntax baseList = root
                                      .FindNode(context.Span, getInnermostNodeForTie: true)?
                                      .FirstAncestorOrSelf <BaseListSyntax>();

            Debug.Assert(baseList != null, $"{nameof(baseList)} is null");

            if (baseList == null ||
                baseList.ContainsDiagnostics)
            {
                return;
            }

            foreach (Diagnostic diagnostic in context.Diagnostics)
            {
                switch (diagnostic.Id)
                {
                case CompilerDiagnosticIdentifiers.BaseClassMustComeBeforeAnyInterface:
                {
                    SeparatedSyntaxList <BaseTypeSyntax> types = baseList.Types;

                    if (types.Count > 1)
                    {
                        BaseTypeSyntax baseType = types.First(f => context.Span.Contains(f.Span));

                        CodeAction codeAction = CodeAction.Create(
                            $"Move '{baseType.Type}' before any interface",
                            cancellationToken =>
                            {
                                BaseTypeSyntax firstType = types[0];

                                SeparatedSyntaxList <BaseTypeSyntax> newTypes = types
                                                                                .Replace(baseType, firstType.WithTriviaFrom(baseType))
                                                                                .ReplaceAt(0, baseType.WithTriviaFrom(firstType));

                                BaseListSyntax newBaseList = baseList.WithTypes(newTypes);

                                return(context.Document.ReplaceNodeAsync(baseList, newBaseList, context.CancellationToken));
                            },
                            GetEquivalenceKey(diagnostic));

                        context.RegisterCodeFix(codeAction, diagnostic);
                    }

                    break;
                }
                }
            }
        }
        private static StructDeclarationSyntax AddBaseType(StructDeclarationSyntax structDeclaration, BaseTypeSyntax baseType)
        {
            BaseListSyntax baseList = structDeclaration.BaseList;

            if (baseList == null)
            {
                baseList = BaseList(baseType);

                TypeParameterListSyntax typeParameterList = structDeclaration.TypeParameterList;

                if (typeParameterList != null)
                {
                    return(structDeclaration
                           .WithTypeParameterList(typeParameterList.WithoutTrailingTrivia())
                           .WithBaseList(baseList.WithTrailingTrivia(typeParameterList.GetTrailingTrivia())));
                }
                else
                {
                    SyntaxToken identifier = structDeclaration.Identifier;

                    return(structDeclaration
                           .WithIdentifier(identifier.WithoutTrailingTrivia())
                           .WithBaseList(baseList.WithTrailingTrivia(identifier.TrailingTrivia)));
                }
            }
            else
            {
                SeparatedSyntaxList <BaseTypeSyntax> types = baseList.Types;

                BaseTypeSyntax lastType = types.LastOrDefault();

                if (lastType == null ||
                    (types.Count == 1 && types[0].IsMissing))
                {
                    SyntaxToken colonToken = baseList.ColonToken;

                    baseType = baseType
                               .WithLeadingTrivia(Space)
                               .WithTrailingTrivia(colonToken.TrailingTrivia);

                    baseList = baseList
                               .WithColonToken(colonToken.WithoutTrailingTrivia())
                               .WithTypes(SingletonSeparatedList(baseType));

                    return(structDeclaration.WithBaseList(baseList));
                }
                else
                {
                    types = types
                            .Replace(lastType, lastType.WithoutTrailingTrivia())
                            .Add(baseType.WithTrailingTrivia(lastType.GetTrailingTrivia()));

                    return(structDeclaration.WithBaseList(baseList.WithTypes(types)));
                }
            }
        }
Esempio n. 10
0
        public override async Task RegisterCodeFixesAsync(CodeFixContext context)
        {
            SyntaxNode root = await context.GetSyntaxRootAsync().ConfigureAwait(false);

            if (!TryFindFirstAncestorOrSelf(root, context.Span, out BaseListSyntax baseList))
            {
                return;
            }

            if (baseList.ContainsDiagnostics)
            {
                return;
            }

            foreach (Diagnostic diagnostic in context.Diagnostics)
            {
                switch (diagnostic.Id)
                {
                case CompilerDiagnosticIdentifiers.BaseClassMustComeBeforeAnyInterface:
                {
                    if (!Settings.IsEnabled(diagnostic.Id, CodeFixIdentifiers.MoveBaseClassBeforeAnyInterface))
                    {
                        return;
                    }

                    SeparatedSyntaxList <BaseTypeSyntax> types = baseList.Types;

                    if (types.Count > 1)
                    {
                        BaseTypeSyntax baseType = types.First(f => context.Span.Contains(f.Span));

                        CodeAction codeAction = CodeAction.Create(
                            $"Move '{baseType.Type}' before any interface",
                            cancellationToken =>
                            {
                                BaseTypeSyntax firstType = types[0];

                                SeparatedSyntaxList <BaseTypeSyntax> newTypes = types
                                                                                .Replace(baseType, firstType.WithTriviaFrom(baseType))
                                                                                .ReplaceAt(0, baseType.WithTriviaFrom(firstType));

                                BaseListSyntax newBaseList = baseList.WithTypes(newTypes);

                                return(context.Document.ReplaceNodeAsync(baseList, newBaseList, cancellationToken));
                            },
                            GetEquivalenceKey(diagnostic));

                        context.RegisterCodeFix(codeAction, diagnostic);
                    }

                    break;
                }

                case CompilerDiagnosticIdentifiers.StaticClassCannotDeriveFromType:
                case CompilerDiagnosticIdentifiers.StaticClassCannotImplementInterfaces:
                {
                    if (!(baseList.Parent is ClassDeclarationSyntax classDeclaration))
                    {
                        break;
                    }

                    if (Settings.IsEnabled(diagnostic.Id, CodeFixIdentifiers.MakeClassNonStatic))
                    {
                        ModifiersCodeFixRegistrator.RemoveModifier(
                            context,
                            diagnostic,
                            classDeclaration,
                            SyntaxKind.StaticKeyword,
                            title: "Make class non-static",
                            additionalKey: CodeFixIdentifiers.MakeClassNonStatic);
                    }

                    if (Settings.IsEnabled(diagnostic.Id, CodeFixIdentifiers.RemoveBaseList))
                    {
                        CodeAction codeAction = CodeAction.Create(
                            "Remove base list",
                            cancellationToken =>
                            {
                                SyntaxToken token = baseList.GetFirstToken().GetPreviousToken();

                                SyntaxTriviaList trivia = token.TrailingTrivia.EmptyIfWhitespace()
                                                          .AddRange(baseList.GetLeadingTrivia().EmptyIfWhitespace())
                                                          .AddRange(baseList.GetTrailingTrivia());

                                ClassDeclarationSyntax newNode = classDeclaration
                                                                 .ReplaceToken(token, token.WithTrailingTrivia(trivia))
                                                                 .WithBaseList(null);

                                return(context.Document.ReplaceNodeAsync(classDeclaration, newNode, cancellationToken));
                            },
                            base.GetEquivalenceKey(diagnostic, CodeFixIdentifiers.RemoveBaseList));

                        context.RegisterCodeFix(codeAction, diagnostic);
                    }

                    break;
                }
                }
            }
        }
Esempio n. 11
0
 public static SeparatedSyntaxList <TNode> ReplaceAt <TNode>(this SeparatedSyntaxList <TNode> list, int index, TNode newNode) where TNode : SyntaxNode
 {
     return(list.Replace(list[index], newNode));
 }
Esempio n. 12
0
            /// <inheritdoc />
            public override SyntaxNode VisitClassDeclaration(ClassDeclarationSyntax node)
            {
                CancellationToken token  = cancellationToken;
                INamedTypeSymbol  symbol = semanticModel.GetDeclaredSymbol(node, token);

                if (symbol == null)
                {
                    return(node);
                }

                int totalAttributes = 0;
                ImmutableArray <AttributeData> attrs = symbol.GetAttributes();

                if (attrs.IsDefaultOrEmpty)
                {
                    return(node);
                }

                SyntaxList <AttributeListSyntax> attributeLists = node.AttributeLists;

                for (int i = 0; i < attributeLists.Count; i++)
                {
                    AttributeListSyntax attributeList = attributeLists[i];
                    SeparatedSyntaxList <AttributeSyntax> attributes = attributeList.Attributes;

                    for (int j = 0; j < attributes.Count; j++, totalAttributes++)
                    {
                        AttributeSyntax attr     = attributes[j];
                        string          attrName = attr.Name.ToString();

                        if (attrName == "Component" || attrName == nameof(ComponentAttribute))
                        {
                            // There is a 'Component' attribute: Specify its content.
                            string contentStr = node.ToString();

                            // TODO: Use b64 and serialization
                            // It works, except Roslyn <= 2.0.0 has a bug with serialization
                            //using (MemoryStream ms = new MemoryStream())
                            //{
                            //    node.SerializeTo(ms, cancellationToken);

                            //    contentStr = ms.TryGetBuffer(out ArraySegment<byte> buffer)
                            //        ? Convert.ToBase64String(buffer.Array, buffer.Offset, buffer.Count)
                            //        : Convert.ToBase64String(ms.ToArray());
                            //}

                            AttributeArgumentSyntax contentArg = SyntaxFactory.AttributeArgument(
                                SyntaxFactory.LiteralExpression(
                                    SyntaxKind.StringLiteralExpression,
                                    SyntaxFactory.Literal(contentStr)
                                    )
                                );

                            node = node.WithAttributeLists(
                                attributeLists.Replace(
                                    attributeList,
                                    attributeList.WithAttributes(
                                        attributes.Replace(attr, attr.WithArgumentList(
                                                               SyntaxFactory.AttributeArgumentList().AddArguments(contentArg)
                                                               ))
                                        )
                                    )
                                );
                        }

                        // Maybe a component?
                        AttributeData attrData = attrs[totalAttributes];

                        if (attrData.AttributeClass.MetadataName == nameof(CopyFromAttribute))
                        {
                            // CopyFrom component: copy members
                            node = CopyMembers(node, attrData, token);
                        }
                        else if (InheritsCompositionAttribute(attrData.AttributeClass))
                        {
                            // Component: apply it
                            CompositionAttribute builtAttr = attrData.Construct <CompositionAttribute>();

                            try
                            {
                                node = builtAttr.Component.Apply(node, symbol, token);

                                if (node == null)
                                {
                                    throw new NullReferenceException("A component cannot return null.");
                                }
                            }
                            catch (Exception e)
                            {
                                throw new DiagnosticException($"Error applying the {builtAttr.Component} component.", e, attr.GetLocation());
                            }
                        }
                    }
                }

                return(node);
            }
        private DeclarationNodeContainer VisitMethodTree(MethodDeclarationSyntax node, int currentDepth, int maxDepth = 10)
        {
            if (!_semanticModels.TryGetValue(node.SyntaxTree, out SemanticModel semanticModel))
            {
                throw new Exception($"Couldn't find semantic model for node {node.ToFullString()}");
            }

            IMethodSymbol symbol = semanticModel.GetDeclaredSymbol(node);
            string        methodDocumenationCommentId = symbol.GetDocumentationCommentId();

            if (_visitedNodes.TryGetValue(methodDocumenationCommentId, out DeclarationNodeContainer visitedNode))
            {
                return(visitedNode);
            }

            if (symbol.IsExtern || symbol.IsAbstract)
            {
                DeclarationNodeContainer _result = new DeclarationNodeContainer(node, false);
                _visitedNodes.Add(methodDocumenationCommentId, _result);
                return(_result);
            }

            List <string> notNullParameters = new List <string>();
            IEnumerable <InvocationExpressionSyntax> invocationNodes = node.DescendantNodes().OfType <InvocationExpressionSyntax>();

            if (symbol.DeclaredAccessibility == Accessibility.Internal || symbol.DeclaredAccessibility == Accessibility.Private)
            {
                notNullParameters = AnalyzeDebugAsserts(invocationNodes, semanticModel);
            }

            IEnumerable <IfStatementSyntax> ifStatementNodes = node.DescendantNodes().OfType <IfStatementSyntax>();
            bool hasArgumentValidation = false;

            foreach (IfStatementSyntax ifNode in ifStatementNodes)
            {
                SyntaxNode tmpNode = ifNode.Statement;
                if (tmpNode.IsKind(SyntaxKind.Block))
                {
                    if (tmpNode.ChildNodes().Count() != 1)
                    {
                        continue;
                    }

                    tmpNode = tmpNode.ChildNodes().First();
                }

                if (tmpNode is ExpressionStatementSyntax expression)
                {
                    tmpNode = expression.Expression;
                }

                if (tmpNode is InvocationExpressionSyntax invocationExpression)
                {
                    var access = invocationExpression.Expression as MemberAccessExpressionSyntax;
                    if (access == null)
                    {
                        continue;
                    }

                    var methodSymbol = semanticModel.GetSymbolInfo(access).Symbol as IMethodSymbol;
                    if (methodSymbol.ContainingAssembly != symbol.ContainingAssembly ||
                        methodSymbol.ContainingType.DeclaredAccessibility == Accessibility.Public ||
                        !string.Equals(methodSymbol.ContainingType.Name, "ThrowHelper", StringComparison.Ordinal))
                    {
                        continue;
                    }
                }
                else
                {
                    if (!(tmpNode is ThrowStatementSyntax))
                    {
                        continue;
                    }
                }

                if (!hasArgumentValidation && symbol.DeclaredAccessibility == Accessibility.Private || symbol.DeclaredAccessibility == Accessibility.Internal)
                {
                    hasArgumentValidation = IfConditionHasArgumentValidation(ifNode, semanticModel);
                }

                if (ifNode.Condition is BinaryExpressionSyntax binaryExpression)
                {
                    if (binaryExpression.IsKind(SyntaxKind.EqualsExpression))
                    {
                        if (TryGetParameterIdentifierFromBinaryExpression(binaryExpression, semanticModel, out IParameterSymbol parameter))
                        {
                            notNullParameters.Add(parameter.Name);
                        }
                    }
                }
            }

            foreach (InvocationExpressionSyntax invocationNode in invocationNodes)
            {
                if (semanticModel.GetSymbolInfo(invocationNode).Symbol is IMethodSymbol symbolModel)
                {
                    // Interlocked gives a lot of false positives, so if the method is using Interlocked, let's not annotate it.
                    if (symbolModel.ContainingType.Name == "Interlocked")
                    {
                        var _result = new DeclarationNodeContainer(node, true);
                        _visitedNodes.Add(methodDocumenationCommentId, _result);
                        return(_result);
                    }

                    DeclarationNodeContainer           visitedInvocationNode = default;
                    IEnumerable <IdentifierNameSyntax> invocationIdentifiers = invocationNode.ArgumentList.DescendantNodes().OfType <IdentifierNameSyntax>().Where(idn => idn.Parent is ArgumentSyntax);
                    string invocationDocumentationId = symbolModel.GetDocumentationCommentId();

                    if (string.Equals(methodDocumenationCommentId, invocationDocumentationId))
                    {
                        continue;
                    }

                    if (symbolModel.ContainingType != symbol.ContainingType)
                    {
                        continue;
                    }

                    if (!symbolModel.Name.Contains(symbol.Name))
                    {
                        if (symbol.DeclaredAccessibility != Accessibility.Public || symbolModel.DeclaredAccessibility != Accessibility.Public)
                        {
                            continue;
                        }
                    }

                    if (!_visitedNodes.TryGetValue(invocationDocumentationId, out visitedInvocationNode))
                    {
                        if (currentDepth < maxDepth)
                        {
                            if (ShouldVisitInvocationMember(invocationIdentifiers, semanticModel))
                            {
                                if (_allMethodDeclarations.TryGetValue(invocationDocumentationId, out MethodDeclarationSyntax declarationToVisit))
                                {
                                    // Visit declaration method recursively
                                    visitedInvocationNode = VisitMethodTree(declarationToVisit, ++currentDepth);
                                }
                                else
                                {
                                    throw new Exception("Couldn't find method declaration in _allMethodDeclarations");
                                }
                            }
                        }
                    }

                    if (visitedInvocationNode.Node != null && visitedInvocationNode.ShouldRelyOnArgumentValidation)
                    {
                        int i = 0;
                        foreach (ArgumentSyntax argument in invocationNode.ArgumentList.Arguments)
                        {
                            if (argument.Expression is IdentifierNameSyntax identifier)
                            {
                                if (TryGetParameterIdentifier(identifier, semanticModel, out IParameterSymbol parameter))
                                {
                                    if (!visitedInvocationNode.Node.ParameterList.Parameters[i].Type.ToFullString().TrimEnd().EndsWith("?"))
                                    {
                                        notNullParameters.Add(parameter.Name);
                                    }
                                }
                            }

                            i++;
                        }
                    }
                }
            }

            SeparatedSyntaxList <ParameterSyntax> newParamList = node.ParameterList.Parameters;
            int index = 0;

            foreach (ParameterSyntax parameterSyntax in node.ParameterList.Parameters)
            {
                IParameterSymbol parameterSymbol = symbol.Parameters[index++];
                ParameterSyntax  ps            = newParamList.Where(p => string.Equals(p.Identifier.Value, parameterSyntax.Identifier.Value)).FirstOrDefault();
                string           parameterType = ps.Type.ToFullString().TrimEnd();
                if (parameterSymbol.Type.IsReferenceType && !notNullParameters.Contains(parameterSymbol.Name))
                {
                    if (!parameterType.EndsWith("?"))
                    {
                        newParamList = newParamList.Replace(ps, ps.WithType(SyntaxFactory.ParseTypeName(parameterType + "? ")));
                    }
                }
                else
                {
                    // shouldn't contain ? so if we added it for some reason, let's remove it.
                    if (parameterType.EndsWith("?"))
                    {
                        newParamList = newParamList.Replace(ps, ps.WithType(SyntaxFactory.ParseTypeName(parameterType.Substring(0, parameterType.Length - 1) + " ")));
                    }
                }
            }

            bool shouldRelyOnArgumentValidation = symbol.DeclaredAccessibility == Accessibility.Private || symbol.DeclaredAccessibility == Accessibility.Internal ? hasArgumentValidation : true;
            DeclarationNodeContainer result     = new DeclarationNodeContainer(node.WithParameterList(node.ParameterList.WithParameters(newParamList)), shouldRelyOnArgumentValidation);

            _visitedNodes.Add(methodDocumenationCommentId, result);
            return(result);
        }
Esempio n. 14
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));
        }
 public SeparatedSyntaxList <TItem> Replace(SeparatedSyntaxList <TItem> list, TItem oldItem, TItem newItem)
 {
     return(list.Replace(oldItem, newItem));
 }
 public override SeparatedSyntaxListWrapper <TNode> Replace(TNode nodeInList, TNode newNode)
 => new AutoWrapSeparatedSyntaxList <TSyntax>(syntaxList.Replace((TSyntax)SyntaxWrapper.Unwrap(nodeInList), (TSyntax)SyntaxWrapper.Unwrap(newNode)));