Exemple #1
0
        public override SyntaxNode VisitAttributeArgument(AttributeArgumentSyntax node)
        {
            if (!node.IsKind(SyntaxKind.StringLiteralToken))
            {
                return(node);
            }

            var attributeSyntax = (AttributeSyntax)node.Parent.Parent;

            SyntaxNode result = node;

            var currentValue = node.ToString().Trim('"');

            switch (attributeSyntax.Name.ToString())
            {
            case "AssemblyVersion":
                if (_assemblyVersion == null)
                {
                    break;
                }

                result = node.WithExpression(SyntaxFactory.LiteralExpression(SyntaxKind.StringLiteralExpression,
                                                                             SyntaxFactory.Literal(VersionHelper.ProcessVersionString(currentValue, _assemblyVersion, "AssemblyVersion")
                                                                                                   )));

                break;

            case "AssemblyFileVersion":
                if (_assemblyFileVersion == null)
                {
                    break;
                }

                result = node.WithExpression(SyntaxFactory.LiteralExpression(SyntaxKind.StringLiteralExpression,
                                                                             SyntaxFactory.Literal(VersionHelper.ProcessVersionString(currentValue, _assemblyFileVersion, "AssemblyFileVersion")
                                                                                                   )));

                break;

            case "AssemblyInformationalVersion":
                if (_assemblyInformationalVersion != null)
                {
                    throw new NotImplementedException("Cannot patch AssemblyInformationalVersion yet.");
                }

                break;
            }

            return(result);
        }
        private static async Task <Document> RefactorAsync(
            Document document,
            AttributeSyntax attribute,
            CancellationToken cancellationToken)
        {
            TypeDeclarationSyntax typeDeclaration = attribute.FirstAncestor <TypeDeclarationSyntax>();

            SemanticModel semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);

            string propertyName = NameGenerator.Default.EnsureUniqueName(DefaultNames.DebuggerDisplayPropertyName, semanticModel, typeDeclaration.OpenBraceToken.Span.End);

            AttributeArgumentSyntax argument = attribute.ArgumentList.Arguments.First();

            TypeDeclarationSyntax newTypeDeclaration = typeDeclaration.ReplaceNode(
                argument,
                argument.WithExpression(
                    StringLiteralExpression($"{{{propertyName},nq}}")).WithTriviaFrom(argument.Expression));

            string value = semanticModel
                           .GetDeclaredSymbol(typeDeclaration, cancellationToken)
                           .GetAttribute(MetadataNames.System_Diagnostics_DebuggerDisplayAttribute)
                           .ConstructorArguments[0]
                           .Value
                           .ToString();

            bool isVerbatim = SyntaxInfo.StringLiteralExpressionInfo(argument.Expression).IsVerbatim;

            ExpressionSyntax returnExpression = GetReturnExpression(value, isVerbatim);

            PropertyDeclarationSyntax propertyDeclaration = MarkTypeWithDebuggerDisplayAttributeRefactoring.DebuggerDisplayPropertyDeclaration(propertyName, returnExpression);

            newTypeDeclaration = MemberDeclarationInserter.Default.Insert(newTypeDeclaration, propertyDeclaration);

            return(await document.ReplaceNodeAsync(typeDeclaration, newTypeDeclaration, cancellationToken).ConfigureAwait(false));
        }
Exemple #3
0
        private async Task <Document> MakeStringLengthSufficientForAutoNumberingAsync(Document document, TextSpan diagnosticSpan,
                                                                                      int minLengthForAutoNumbering, CancellationToken cancellationToken)
        {
            SyntaxNode root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);

            AttributeArgumentSyntax attributeArgument = GetAttributeArgumentNodeToBeReplaced(root, diagnosticSpan);

            if (attributeArgument == null || cancellationToken.IsCancellationRequested)
            {
                return(document);
            }

            AttributeArgumentSyntax modifiedArgument =
                attributeArgument.WithExpression(
                    SyntaxFactory.LiteralExpression(SyntaxKind.NumericLiteralExpression,
                                                    SyntaxFactory.Literal(minLengthForAutoNumbering)));

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

            var modifiedRoot = root.ReplaceNode(attributeArgument, modifiedArgument);

            return(document.WithSyntaxRoot(modifiedRoot));
        }
        private static async Task <Document> RefactorAsync(
            Document document,
            AttributeSyntax attribute,
            CancellationToken cancellationToken)
        {
            TypeDeclarationSyntax typeDeclaration = attribute.FirstAncestor <TypeDeclarationSyntax>();

            SemanticModel semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);

            string propertyName = NameGenerator.Default.EnsureUniqueMemberName(PropertyName, semanticModel, typeDeclaration.OpenBraceToken.Span.End, cancellationToken: cancellationToken);

            AttributeArgumentSyntax argument = attribute.ArgumentList.Arguments.First();

            TypeDeclarationSyntax newTypeDeclaration = typeDeclaration.ReplaceNode(
                argument,
                argument.WithExpression(
                    StringLiteralExpression($"{{{propertyName},nq}}")).WithTriviaFrom(argument.Expression));

            string value = semanticModel
                           .GetDeclaredSymbol(typeDeclaration, cancellationToken)
                           .GetAttribute(semanticModel.GetTypeByMetadataName(MetadataNames.System_Diagnostics_DebuggerDisplayAttribute))
                           .ConstructorArguments[0]
                           .Value
                           .ToString();

            ExpressionSyntax returnExpression = GetReturnExpression(value, SyntaxInfo.StringLiteralExpressionInfo(argument.Expression).IsVerbatim);

            PropertyDeclarationSyntax propertyDeclaration = PropertyDeclaration(
                SingletonList(
                    AttributeList(
                        Attribute(
                            ParseName("System.Diagnostics.DebuggerBrowsableAttribute"),
                            AttributeArgument(
                                SimpleMemberAccessExpression(
                                    ParseName("System.Diagnostics.DebuggerBrowsableState").WithSimplifierAnnotation(),
                                    IdentifierName("Never"))
                                )
                            ).WithSimplifierAnnotation()
                        )
                    ),
                Modifiers.Private(),
                CSharpTypeFactory.StringType(),
                default(ExplicitInterfaceSpecifierSyntax),
                Identifier(propertyName).WithRenameAnnotation(),
                AccessorList(
                    GetAccessorDeclaration(
                        Block(
                            ReturnStatement(returnExpression)))));

            propertyDeclaration = propertyDeclaration.WithFormatterAnnotation();

            newTypeDeclaration = MemberDeclarationInserter.Default.Insert(newTypeDeclaration, propertyDeclaration);

            return(await document.ReplaceNodeAsync(typeDeclaration, newTypeDeclaration, cancellationToken).ConfigureAwait(false));
        }
 private static AttributeArgumentSyntax CreateFixedAttribute(AttributeArgumentSyntax nameParameter, string className)
 {
     return(nameParameter
            .WithExpression(
                SyntaxFactory.LiteralExpression(
                    SyntaxKind.StringLiteralExpression,
                    SyntaxFactory.Token(
                        SyntaxTriviaList.Empty,
                        SyntaxKind.StringLiteralToken,
                        $@"""{className}""",
                        $@"""{className}""",
                        SyntaxTriviaList.Empty))));
 }
Exemple #6
0
            public override SyntaxNode VisitAttributeArgument(AttributeArgumentSyntax node)
            {
                var attributeList = (AttributeArgumentListSyntax)node.Parent;
                var attribute     = (AttributeSyntax)attributeList.Parent;
                var attributeName = ((IdentifierNameSyntax)attribute.Name).Identifier.ValueText;

                if (attributeName == attributeTypeName)
                {
                    var newArgument = node.WithExpression(SyntaxFactory.LiteralExpression(SyntaxKind.StringLiteralExpression, SyntaxFactory.Literal(attributeValue)));
                    return(newArgument);
                }

                return(base.VisitAttributeArgument(node));
            }
        public override SyntaxNode VisitAttributeArgument(AttributeArgumentSyntax node)
        {
            var argExpression = node.Expression;

            if (argExpression is MemberAccessExpressionSyntax memberAccess)
            {
                return(memberAccess.Name.ToString() == "Synchronized" ? default(SyntaxNode) : node);
            }
            if (argExpression is BinaryExpressionSyntax binary)
            {
                return(node.WithExpression((ExpressionSyntax)VisitBinaryExpression(binary)));
            }
            return(base.VisitAttributeArgument(node));
        }
        public override async Task RegisterCodeFixesAsync(CodeFixContext context)
        {
            foreach (var diagnostic in context.Diagnostics)
            {
                if (!string.Equals(diagnostic.Id, JsonObjectOptInAnalyzer.DiagnosticId, StringComparison.Ordinal))
                {
                    continue;
                }

                var documentRoot = await context.Document.GetSyntaxRootAsync(context.CancellationToken).ConfigureAwait(false);

                AttributeSyntax syntax = documentRoot.FindNode(diagnostic.Location.SourceSpan) as AttributeSyntax;
                if (syntax == null)
                {
                    continue;
                }

                ExpressionSyntax expression =
                    SyntaxFactory.ParseExpression("global::Newtonsoft.Json.MemberSerialization.OptIn")
                    .WithAdditionalAnnotations(Simplifier.Annotation);

                AttributeSyntax             newAttribute = null;
                AttributeArgumentListSyntax argumentList = syntax.ArgumentList;
                if (argumentList != null)
                {
                    AttributeArgumentSyntax existingArgument = null;
                    foreach (var attributeArgument in argumentList.Arguments)
                    {
                        if (string.Equals("MemberSerialization", attributeArgument.NameEquals?.Name?.Identifier.ValueText, StringComparison.Ordinal))
                        {
                            existingArgument = attributeArgument;
                            break;
                        }
                    }

                    if (existingArgument == null)
                    {
                        SemanticModel semanticModel = null;
                        foreach (var attributeArgument in argumentList.Arguments)
                        {
                            // this time only interested in arguments (no NameEquals clause)
                            if (attributeArgument.NameEquals != null)
                            {
                                continue;
                            }

                            if (string.Equals("memberSerialization", attributeArgument.NameColon?.Name?.Identifier.ValueText, StringComparison.Ordinal))
                            {
                                existingArgument = attributeArgument;
                                break;
                            }

                            if (attributeArgument.NameColon != null)
                            {
                                continue;
                            }

                            if (semanticModel == null)
                            {
                                semanticModel = await context.Document.GetSemanticModelAsync(context.CancellationToken).ConfigureAwait(false);
                            }

                            if (IsMemberSerializationArgument(semanticModel, attributeArgument.Expression, context.CancellationToken))
                            {
                                existingArgument = attributeArgument;
                                break;
                            }
                        }
                    }

                    if (existingArgument != null)
                    {
                        var newArgument =
                            existingArgument
                            .WithExpression(expression)
                            .WithTriviaFrom(existingArgument)
                            .WithoutFormatting();

                        newAttribute = syntax.ReplaceNode(existingArgument, newArgument);
                    }
                }

                if (newAttribute == null)
                {
                    if (argumentList == null)
                    {
                        argumentList = SyntaxFactory.AttributeArgumentList();
                    }

                    NameEqualsSyntax nameEquals;
                    if (argumentList.Arguments.Any(argument => argument.NameEquals == null))
                    {
                        nameEquals = SyntaxFactory.NameEquals("MemberSerialization");
                    }
                    else
                    {
                        nameEquals = null;
                    }

                    AttributeArgumentSyntax defaultValueArgument = SyntaxFactory.AttributeArgument(nameEquals, null, expression);

                    argumentList = argumentList.AddArguments(defaultValueArgument);
                    newAttribute = syntax.WithArgumentList(argumentList);
                }

                SyntaxNode newRoot     = documentRoot.ReplaceNode(syntax, newAttribute);
                Document   newDocument = context.Document.WithSyntaxRoot(newRoot);
                context.RegisterCodeFix(CodeAction.Create("Add MemberSerialization.OptIn", _ => Task.FromResult(newDocument)), diagnostic);
            }
        }
        private static Task <Document> UpdateValueOfArgumentAsync(Document document, SyntaxNode root, AttributeArgumentSyntax argument)
        {
            var newArgument = argument.WithExpression(GetNewAttributeValue());

            return(Task.FromResult(document.WithSyntaxRoot(root.ReplaceNode(argument, newArgument))));
        }
Exemple #10
0
        public override async Task RegisterCodeFixesAsync(CodeFixContext context)
        {
            foreach (var diagnostic in context.Diagnostics)
            {
                if (!string.Equals(diagnostic.Id, JsonPropertyDefaultValueHandlingAnalyzer.DiagnosticId, StringComparison.Ordinal))
                {
                    continue;
                }

                var documentRoot = await context.Document.GetSyntaxRootAsync(context.CancellationToken).ConfigureAwait(false);

                AttributeSyntax syntax = documentRoot.FindNode(diagnostic.Location.SourceSpan) as AttributeSyntax;
                if (syntax == null)
                {
                    continue;
                }

                ExpressionSyntax expression =
                    SyntaxFactory.ParseExpression("global::Newtonsoft.Json.DefaultValueHandling.Ignore")
                    .WithAdditionalAnnotations(Simplifier.Annotation);

                AttributeSyntax             newAttribute = null;
                AttributeArgumentListSyntax argumentList = syntax.ArgumentList;
                if (argumentList != null)
                {
                    AttributeArgumentSyntax existingArgument = null;
                    foreach (var attributeArgument in argumentList.Arguments)
                    {
                        if (string.Equals("DefaultValueHandling", attributeArgument.NameEquals?.Name?.Identifier.ValueText, StringComparison.Ordinal))
                        {
                            existingArgument = attributeArgument;
                            break;
                        }
                    }

                    if (existingArgument != null)
                    {
                        var newArgument =
                            existingArgument
                            .WithExpression(expression)
                            .WithTriviaFrom(existingArgument)
                            .WithoutFormatting();

                        newAttribute = syntax.ReplaceNode(existingArgument, newArgument);
                    }
                }

                if (newAttribute == null)
                {
                    NameEqualsSyntax nameEquals = SyntaxFactory.NameEquals("DefaultValueHandling");

                    AttributeArgumentSyntax defaultValueArgument = SyntaxFactory.AttributeArgument(nameEquals, null, expression);

                    if (argumentList == null)
                    {
                        argumentList = SyntaxFactory.AttributeArgumentList();
                    }

                    argumentList = argumentList.AddArguments(defaultValueArgument);

                    newAttribute = syntax.WithArgumentList(argumentList);
                }

                SyntaxNode newRoot     = documentRoot.ReplaceNode(syntax, newAttribute);
                Document   newDocument = context.Document.WithSyntaxRoot(newRoot);
                context.RegisterCodeFix(CodeAction.Create("Add DefaultValueHandling.Ignore", _ => Task.FromResult(newDocument)), diagnostic);
            }
        }
 private static Task<Document> UpdateValueOfArgumentAsync(Document document, SyntaxNode root, AttributeArgumentSyntax argument)
 {
     var newArgument = argument.WithExpression(GetNewAttributeValue());
     return Task.FromResult(document.WithSyntaxRoot(root.ReplaceNode(argument, newArgument)));
 }
        private async Task <Document> ConvertToAsyncPackageAsync(CodeFixContext context, Diagnostic diagnostic, CancellationToken cancellationToken)
        {
            SemanticModel semanticModel = await context.Document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);

            Compilation?compilation = await context.Document.Project.GetCompilationAsync(cancellationToken).ConfigureAwait(false);

            Assumes.NotNull(compilation);
            SyntaxNode root = await context.Document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);

            BaseTypeSyntax          baseTypeSyntax         = root.FindNode(diagnostic.Location.SourceSpan).FirstAncestorOrSelf <BaseTypeSyntax>();
            ClassDeclarationSyntax  classDeclarationSyntax = baseTypeSyntax.FirstAncestorOrSelf <ClassDeclarationSyntax>();
            MethodDeclarationSyntax initializeMethodSyntax = classDeclarationSyntax.DescendantNodes()
                                                             .OfType <MethodDeclarationSyntax>()
                                                             .FirstOrDefault(method => method.Modifiers.Any(modifier => modifier.IsKind(SyntaxKind.OverrideKeyword)) && method.Identifier.Text == Types.Package.Initialize);
            InvocationExpressionSyntax?baseInitializeInvocationSyntax = initializeMethodSyntax?.Body?.DescendantNodes()
                                                                        .OfType <InvocationExpressionSyntax>()
                                                                        .FirstOrDefault(ies => ies.Expression is MemberAccessExpressionSyntax memberAccess && memberAccess.Name?.Identifier.Text == Types.Package.Initialize && memberAccess.Expression is BaseExpressionSyntax);
            var             getServiceInvocationsSyntax = new List <InvocationExpressionSyntax>();
            AttributeSyntax?packageRegistrationSyntax   = null;

            {
                INamedTypeSymbol userClassSymbol             = semanticModel.GetDeclaredSymbol(classDeclarationSyntax, context.CancellationToken);
                INamedTypeSymbol packageRegistrationType     = compilation.GetTypeByMetadataName(Types.PackageRegistrationAttribute.FullName);
                AttributeData?   packageRegistrationInstance = userClassSymbol?.GetAttributes().FirstOrDefault(a => Equals(a.AttributeClass, packageRegistrationType));
                if (packageRegistrationInstance?.ApplicationSyntaxReference != null)
                {
                    packageRegistrationSyntax = (AttributeSyntax)await packageRegistrationInstance.ApplicationSyntaxReference.GetSyntaxAsync(cancellationToken).ConfigureAwait(false);
                }
            }

            if (initializeMethodSyntax != null)
            {
                getServiceInvocationsSyntax.AddRange(
                    from invocation in initializeMethodSyntax.DescendantNodes().OfType <InvocationExpressionSyntax>()
                    let memberBinding = invocation.Expression as MemberAccessExpressionSyntax
                                        let identifierName = invocation.Expression as IdentifierNameSyntax
                                                             where identifierName?.Identifier.Text == Types.Package.GetService ||
                                                             (memberBinding.Name.Identifier.Text == Types.Package.GetService && memberBinding.Expression.IsKind(SyntaxKind.ThisExpression))
                                                             select invocation);
            }

            // Make it easier to track nodes across changes.
            var nodesToTrack = new List <SyntaxNode?>
            {
                baseTypeSyntax,
                initializeMethodSyntax,
                baseInitializeInvocationSyntax,
                packageRegistrationSyntax,
            };

            nodesToTrack.AddRange(getServiceInvocationsSyntax);
            nodesToTrack.RemoveAll(n => n == null);
            SyntaxNode updatedRoot = root.TrackNodes(nodesToTrack);

            // Replace the Package base type with AsyncPackage
            baseTypeSyntax = updatedRoot.GetCurrentNode(baseTypeSyntax);
            SimpleBaseTypeSyntax asyncPackageBaseTypeSyntax = SyntaxFactory.SimpleBaseType(Types.AsyncPackage.TypeSyntax.WithAdditionalAnnotations(Simplifier.Annotation))
                                                              .WithLeadingTrivia(baseTypeSyntax.GetLeadingTrivia())
                                                              .WithTrailingTrivia(baseTypeSyntax.GetTrailingTrivia());

            updatedRoot = updatedRoot.ReplaceNode(baseTypeSyntax, asyncPackageBaseTypeSyntax);

            // Update the PackageRegistration attribute
            if (packageRegistrationSyntax != null)
            {
                LiteralExpressionSyntax trueExpression = SyntaxFactory.LiteralExpression(SyntaxKind.TrueLiteralExpression);
                packageRegistrationSyntax = updatedRoot.GetCurrentNode(packageRegistrationSyntax);
                AttributeArgumentSyntax allowsBackgroundLoadingSyntax = packageRegistrationSyntax.ArgumentList.Arguments.FirstOrDefault(a => a.NameEquals?.Name?.Identifier.Text == Types.PackageRegistrationAttribute.AllowsBackgroundLoading);
                if (allowsBackgroundLoadingSyntax != null)
                {
                    updatedRoot = updatedRoot.ReplaceNode(
                        allowsBackgroundLoadingSyntax,
                        allowsBackgroundLoadingSyntax.WithExpression(trueExpression));
                }
                else
                {
                    updatedRoot = updatedRoot.ReplaceNode(
                        packageRegistrationSyntax,
                        packageRegistrationSyntax.AddArgumentListArguments(
                            SyntaxFactory.AttributeArgument(trueExpression).WithNameEquals(SyntaxFactory.NameEquals(Types.PackageRegistrationAttribute.AllowsBackgroundLoading))));
                }
            }

            // Find the Initialize override, if present, and update it to InitializeAsync
            if (initializeMethodSyntax != null)
            {
                IdentifierNameSyntax cancellationTokenLocalVarName = SyntaxFactory.IdentifierName("cancellationToken");
                IdentifierNameSyntax progressLocalVarName          = SyntaxFactory.IdentifierName("progress");
                initializeMethodSyntax = updatedRoot.GetCurrentNode(initializeMethodSyntax);
                BlockSyntax newBody = initializeMethodSyntax.Body;

                SyntaxTriviaList leadingTrivia = SyntaxFactory.TriviaList(
                    SyntaxFactory.Comment(@"// When initialized asynchronously, we *may* be on a background thread at this point."),
                    SyntaxFactory.CarriageReturnLineFeed,
                    SyntaxFactory.Comment(@"// Do any initialization that requires the UI thread after switching to the UI thread."),
                    SyntaxFactory.CarriageReturnLineFeed,
                    SyntaxFactory.Comment(@"// Otherwise, remove the switch to the UI thread if you don't need it."),
                    SyntaxFactory.CarriageReturnLineFeed);

                ExpressionStatementSyntax switchToMainThreadStatement = SyntaxFactory.ExpressionStatement(
                    SyntaxFactory.AwaitExpression(
                        SyntaxFactory.InvocationExpression(
                            SyntaxFactory.MemberAccessExpression(
                                SyntaxKind.SimpleMemberAccessExpression,
                                SyntaxFactory.MemberAccessExpression(
                                    SyntaxKind.SimpleMemberAccessExpression,
                                    SyntaxFactory.ThisExpression(),
                                    SyntaxFactory.IdentifierName(Types.ThreadHelper.JoinableTaskFactory)),
                                SyntaxFactory.IdentifierName(Types.JoinableTaskFactory.SwitchToMainThreadAsync)))
                        .AddArgumentListArguments(SyntaxFactory.Argument(cancellationTokenLocalVarName))))
                                                                        .WithLeadingTrivia(leadingTrivia)
                                                                        .WithTrailingTrivia(SyntaxFactory.CarriageReturnLineFeed);

                if (baseInitializeInvocationSyntax != null)
                {
                    var baseInitializeAsyncInvocationBookmark = new SyntaxAnnotation();
                    AwaitExpressionSyntax baseInitializeAsyncInvocationSyntax = SyntaxFactory.AwaitExpression(
                        baseInitializeInvocationSyntax
                        .WithLeadingTrivia()
                        .WithExpression(
                            SyntaxFactory.MemberAccessExpression(
                                SyntaxKind.SimpleMemberAccessExpression,
                                SyntaxFactory.BaseExpression(),
                                SyntaxFactory.IdentifierName(Types.AsyncPackage.InitializeAsync)))
                        .AddArgumentListArguments(
                            SyntaxFactory.Argument(cancellationTokenLocalVarName),
                            SyntaxFactory.Argument(progressLocalVarName)))
                                                                                .WithLeadingTrivia(baseInitializeInvocationSyntax.GetLeadingTrivia())
                                                                                .WithAdditionalAnnotations(baseInitializeAsyncInvocationBookmark);
                    newBody = newBody.ReplaceNode(initializeMethodSyntax.GetCurrentNode(baseInitializeInvocationSyntax), baseInitializeAsyncInvocationSyntax);
                    StatementSyntax baseInvocationStatement = newBody.GetAnnotatedNodes(baseInitializeAsyncInvocationBookmark).First().FirstAncestorOrSelf <StatementSyntax>();

                    newBody = newBody.InsertNodesAfter(
                        baseInvocationStatement,
                        new[] { switchToMainThreadStatement.WithLeadingTrivia(switchToMainThreadStatement.GetLeadingTrivia().Insert(0, SyntaxFactory.LineFeed)) });
                }
                else
                {
                    newBody = newBody.WithStatements(
                        newBody.Statements.Insert(0, switchToMainThreadStatement));
                }

                MethodDeclarationSyntax initializeAsyncMethodSyntax = initializeMethodSyntax
                                                                      .WithIdentifier(SyntaxFactory.Identifier(Types.AsyncPackage.InitializeAsync))
                                                                      .WithReturnType(Types.Task.TypeSyntax.WithAdditionalAnnotations(Simplifier.Annotation))
                                                                      .AddModifiers(SyntaxFactory.Token(SyntaxKind.AsyncKeyword))
                                                                      .AddParameterListParameters(
                    SyntaxFactory.Parameter(cancellationTokenLocalVarName.Identifier).WithType(Types.CancellationToken.TypeSyntax.WithAdditionalAnnotations(Simplifier.Annotation)),
                    SyntaxFactory.Parameter(progressLocalVarName.Identifier).WithType(Types.IProgress.TypeSyntaxOf(Types.ServiceProgressData.TypeSyntax).WithAdditionalAnnotations(Simplifier.Annotation)))
                                                                      .WithBody(newBody);
                updatedRoot = updatedRoot.ReplaceNode(initializeMethodSyntax, initializeAsyncMethodSyntax);

                // Replace GetService calls with GetServiceAsync
                getServiceInvocationsSyntax = updatedRoot.GetCurrentNodes <InvocationExpressionSyntax>(getServiceInvocationsSyntax).ToList();
                updatedRoot = updatedRoot.ReplaceNodes(
                    getServiceInvocationsSyntax,
                    (orig, node) =>
                {
                    InvocationExpressionSyntax invocation = node;
                    if (invocation.Expression is IdentifierNameSyntax methodName)
                    {
                        invocation = invocation.WithExpression(SyntaxFactory.IdentifierName(Types.AsyncPackage.GetServiceAsync));
                    }
                    else if (invocation.Expression is MemberAccessExpressionSyntax memberAccess)
                    {
                        invocation = invocation.WithExpression(
                            memberAccess.WithName(SyntaxFactory.IdentifierName(Types.AsyncPackage.GetServiceAsync)));
                    }

                    return(SyntaxFactory.ParenthesizedExpression(SyntaxFactory.AwaitExpression(invocation))
                           .WithAdditionalAnnotations(Simplifier.Annotation));
                });

                updatedRoot = await Utils.AddUsingTaskEqualsDirectiveAsync(updatedRoot, cancellationToken);
            }

            Document newDocument = context.Document.WithSyntaxRoot(updatedRoot);

            newDocument = await ImportAdder.AddImportsAsync(newDocument, Simplifier.Annotation, cancellationToken : cancellationToken);

            return(newDocument);
        }