Exemplo n.º 1
0
        public static async Task <string> Process(IEnumerable <IProcessor> processors, string inputSource)
        {
            try
            {
                var workspace = new AdhocWorkspace();

                string         projName     = "NewProject";
                var            projectId    = ProjectId.CreateNewId();
                var            versionStamp = VersionStamp.Create();
                var            projectInfo  = ProjectInfo.Create(projectId, versionStamp, projName, projName, LanguageNames.CSharp);
                var            newProject   = workspace.AddProject(projectInfo);
                var            document     = workspace.AddDocument(newProject.Id, "NewFile.cs", SourceText.From(inputSource));
                DocumentEditor editor       = await DocumentEditor.CreateAsync(document);

                foreach (var processor in processors)
                {
                    processor.Process(editor);
                }

                return((await editor.GetChangedDocument().GetTextAsync()).ToString());
            }
            catch (Exception e)
            {
                Console.Error.WriteLine(e.Message);
                return(inputSource);
            }
        }
        private Task <Document> MakeSealed(DocumentEditor editor, SyntaxNode declaration, CancellationToken ct)
        {
            DeclarationModifiers modifiers = editor.Generator.GetModifiers(declaration);

            editor.SetModifiers(declaration, modifiers + DeclarationModifiers.Sealed);
            return(Task.FromResult(editor.GetChangedDocument()));
        }
Exemplo n.º 3
0
            protected override async Task <Document> FixAllAsync(FixAllContext fixAllContext, Document document, ImmutableArray <Diagnostic> diagnostics)
            {
                SyntaxNode?root = await document.GetSyntaxRootAsync(fixAllContext.CancellationToken).ConfigureAwait(false);

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

                DocumentEditor editor = await DocumentEditor.CreateAsync(document, fixAllContext.CancellationToken).ConfigureAwait(false);

                switch (fixAllContext.CodeActionEquivalenceKey)
                {
                case AddMissingCustomTypeMarshallerMembersKey:
                    foreach (IGrouping <TextSpan, Diagnostic> diagnosticsBySpan in diagnostics.GroupBy(d => d.Location.SourceSpan))
                    {
                        SyntaxNode node = root.FindNode(diagnosticsBySpan.Key);

                        AddMissingMembers(editor, diagnosticsBySpan, node);
                    }
                    break;

                default:
                    break;
                }

                return(editor.GetChangedDocument());
            }
        private async Task <Document> MakePublic(Document document, SyntaxNode getMethod, CancellationToken cancellationToken)
        {
            DocumentEditor editor = await DocumentEditor.CreateAsync(document, cancellationToken).ConfigureAwait(false);

            editor.SetAccessibility(getMethod, Accessibility.Public);
            return(editor.GetChangedDocument());
        }
Exemplo n.º 5
0
        private static async Task <Document> ConvertToArrayEmptyAsync(Document document, SyntaxNode nodeToFix, CancellationToken cancellationToken)
        {
            DocumentEditor editor = await DocumentEditor.CreateAsync(document, cancellationToken).ConfigureAwait(false);

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

            SyntaxGenerator generator = editor.Generator;

            INamedTypeSymbol?arrayTypeSymbol = semanticModel.Compilation.GetSpecialType(SpecialType.System_Array);

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

            ITypeSymbol?elementType = GetArrayElementType(nodeToFix, semanticModel, cancellationToken);

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

            SyntaxNode arrayEmptyInvocation = GenerateArrayEmptyInvocation(generator, arrayTypeSymbol, elementType).WithTriviaFrom(nodeToFix);

            editor.ReplaceNode(nodeToFix, arrayEmptyInvocation);
            return(editor.GetChangedDocument());
        }
        private static async Task <Document> ImplementIDisposable(Document document, SyntaxNode declaration, CancellationToken cancellationToken)
        {
            DocumentEditor editor = await DocumentEditor.CreateAsync(document, cancellationToken).ConfigureAwait(false);

            SyntaxGenerator generator = editor.Generator;
            SemanticModel   model     = editor.SemanticModel;

            // Add the interface to the baselist.
            SyntaxNode interfaceType = generator.TypeExpression(WellKnownTypes.IDisposable(model.Compilation));

            editor.AddInterfaceType(declaration, interfaceType);

            // Find a Dispose method. If one exists make that implement IDisposable, else generate a new method.
            var           typeSymbol    = model.GetDeclaredSymbol(declaration) as INamedTypeSymbol;
            IMethodSymbol disposeMethod = (typeSymbol?.GetMembers("Dispose"))?.OfType <IMethodSymbol>()?.Where(m => m.Parameters.Length == 0).FirstOrDefault();

            if (disposeMethod != null && disposeMethod.DeclaringSyntaxReferences.Length == 1)
            {
                SyntaxNode memberPartNode = await disposeMethod.DeclaringSyntaxReferences.Single().GetSyntaxAsync(cancellationToken).ConfigureAwait(false);

                memberPartNode = generator.GetDeclaration(memberPartNode);
                editor.ReplaceNode(memberPartNode, generator.AsPublicInterfaceImplementation(memberPartNode, interfaceType));
            }
            else
            {
                SyntaxNode throwStatement = generator.ThrowStatement(generator.ObjectCreationExpression(WellKnownTypes.NotImplementedException(model.Compilation)));
                SyntaxNode member         = generator.MethodDeclaration(TypesThatOwnDisposableFieldsShouldBeDisposableAnalyzer <SyntaxNode> .Dispose, statements: new[] { throwStatement });
                member = generator.AsPublicInterfaceImplementation(member, interfaceType);
                editor.AddMember(declaration, member);
            }

            return(editor.GetChangedDocument());
        }
Exemplo n.º 7
0
        private async Task <Document> ImplementOperatorEquals(Document document, SyntaxNode declaration, INamedTypeSymbol typeSymbol, CancellationToken cancellationToken)
        {
            DocumentEditor editor = await DocumentEditor.CreateAsync(document, cancellationToken).ConfigureAwait(false);

            var generator = editor.Generator;

            if (!typeSymbol.IsOperatorImplemented(WellKnownMemberNames.EqualityOperatorName))
            {
                var equalityOperator = GenerateOperatorDeclaration(generator.TypeExpression(SpecialType.System_Boolean),
                                                                   WellKnownMemberNames.EqualityOperatorName,
                                                                   new[]
                {
                    generator.ParameterDeclaration("left", generator.TypeExpression(typeSymbol)),
                    generator.ParameterDeclaration("right", generator.TypeExpression(typeSymbol)),
                },
                                                                   generator.ThrowStatement(generator.ObjectCreationExpression(generator.DottedName("System.NotImplementedException"))));
                editor.AddMember(declaration, equalityOperator);
            }

            if (!typeSymbol.IsOperatorImplemented(WellKnownMemberNames.InequalityOperatorName))
            {
                var inequalityOperator = GenerateOperatorDeclaration(generator.TypeExpression(SpecialType.System_Boolean),
                                                                     WellKnownMemberNames.InequalityOperatorName,
                                                                     new[]
                {
                    generator.ParameterDeclaration("left", generator.TypeExpression(typeSymbol)),
                    generator.ParameterDeclaration("right", generator.TypeExpression(typeSymbol)),
                },
                                                                     generator.ThrowStatement(generator.ObjectCreationExpression(generator.DottedName("System.NotImplementedException"))));
                editor.AddMember(declaration, inequalityOperator);
            }

            return(editor.GetChangedDocument());
        }
        private static Task <Document> MakeSealedAsync(DocumentEditor editor, SyntaxNode declaration)
        {
            DeclarationModifiers modifiers = editor.Generator.GetModifiers(declaration);

            editor.SetModifiers(declaration, modifiers + DeclarationModifiers.Sealed);
            return(Task.FromResult(editor.GetChangedDocument()));
        }
        private async Task <Document> MakePublic(Document document, SyntaxNode getMethod, SyntaxNode property, CancellationToken cancellationToken)
        {
            // Clear the accessibility on the getter.
            DocumentEditor editor = await DocumentEditor.CreateAsync(document, cancellationToken).ConfigureAwait(false);

            editor.SetAccessibility(getMethod, Accessibility.NotApplicable);

            // If the containing property is not public, make it so
            Accessibility propertyAccessibility = editor.Generator.GetAccessibility(property);

            if (propertyAccessibility != Accessibility.Public)
            {
                editor.SetAccessibility(property, Accessibility.Public);

                // Having just made the property public, if it has a setter with no Accessibility set, then we've just made the setter public.
                // Instead restore the setter's original accessibility so that we don't fire a violation with the generated code.
                SyntaxNode setter = editor.Generator.GetAccessor(property, DeclarationKind.SetAccessor);
                if (setter != null)
                {
                    Accessibility setterAccessibility = editor.Generator.GetAccessibility(setter);
                    if (setterAccessibility == Accessibility.NotApplicable)
                    {
                        editor.SetAccessibility(setter, propertyAccessibility);
                    }
                }
            }

            return(editor.GetChangedDocument());
        }
        private async Task <Document> WithAttributeAsync([NotNull] INamedTypeSymbol attribute,
                                                         [NotNull] Document document, [NotNull] SyntaxNode syntaxNode, CancellationToken cancellationToken)
        {
            DocumentEditor editor = await DocumentEditor.CreateAsync(document, cancellationToken).ConfigureAwait(false);

            // Add NotNull/CanBeNull/ItemNotNull/ItemCanBeNull attribute.
            SyntaxNode attributeSyntax =
                editor.Generator.Attribute(editor.Generator.TypeExpression(attribute))
                .WithAdditionalAnnotations(Simplifier.Annotation, Formatter.Annotation, NamespaceImportAnnotation);

            editor.AddAttribute(syntaxNode, attributeSyntax);
            Document documentWithAttribute = editor.GetChangedDocument();

            // Add namespace import.
            Document documentWithImport =
                await
                ImportAdder.AddImportsAsync(documentWithAttribute, NamespaceImportAnnotation, null,
                                            cancellationToken).ConfigureAwait(false);

            // Simplify and reformat all annotated nodes.
            Document simplified = await SimplifyAsync(documentWithImport, cancellationToken).ConfigureAwait(false);

            SyntaxNode formatted = await FormatAsync(simplified, cancellationToken).ConfigureAwait(false);

            return(simplified.WithSyntaxRoot(formatted));
        }
        private async Task <Document> RemoveSetter(Document document, SyntaxNode setMethod, CancellationToken cancellationToken)
        {
            DocumentEditor editor = await DocumentEditor.CreateAsync(document, cancellationToken).ConfigureAwait(false);

            editor.SetAccessibility(setMethod, Accessibility.Internal);
            return(editor.GetChangedDocument());
        }
Exemplo n.º 12
0
        public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context)
        {
            Document          doc = context.Document;
            CancellationToken cancellationToken = context.CancellationToken;
            SyntaxNode        root = await doc.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);

            if (root.FindNode(context.Span) is SyntaxNode expression)
            {
                string title = MicrosoftNetCoreAnalyzersResources.PreferTypedStringBuilderAppendOverloadsRemoveToString;
                context.RegisterCodeFix(
                    new MyCodeAction(title,
                                     async ct =>
                {
                    SemanticModel model = await doc.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);
                    if (model.GetOperationWalkingUpParentChain(expression, cancellationToken) is IArgumentOperation arg &&
                        arg.Value is IInvocationOperation invoke &&
                        invoke.Instance?.Syntax is SyntaxNode replacement)
                    {
                        DocumentEditor editor = await DocumentEditor.CreateAsync(doc, ct).ConfigureAwait(false);
                        editor.ReplaceNode(expression, editor.Generator.Argument(replacement));
                        return(editor.GetChangedDocument());
                    }

                    return(doc);
                },
                                     equivalenceKey: title),
                    context.Diagnostics);
            }
        }
        public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context)
        {
            Document          doc = context.Document;
            CancellationToken cancellationToken = context.CancellationToken;
            SyntaxNode        root = await doc.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);

            SemanticModel model = await doc.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);

            // If we're able to make the desired substitution...
            var(targetNode, replacementField) = GetTaskCreationOptionsField(context, root, model, cancellationToken);
            if (replacementField != null)
            {
                // ...then offer it.
                string title = MicrosoftNetCoreAnalyzersResources.DoNotCreateTaskCompletionSourceWithWrongArgumentsFix;
                context.RegisterCodeFix(
                    new MyCodeAction(title,
                                     async ct =>
                {
                    // Replace "TaskContinuationOptions.Value" with "TaskCreationOptions.Value"
                    DocumentEditor editor = await DocumentEditor.CreateAsync(doc, ct).ConfigureAwait(false);
                    editor.ReplaceNode(targetNode,
                                       editor.Generator.Argument(
                                           editor.Generator.MemberAccessExpression(
                                               editor.Generator.TypeExpressionForStaticMemberAccess(replacementField.ContainingType), replacementField.Name)));
                    return(editor.GetChangedDocument());
                },
                                     equivalenceKey: title),
                    context.Diagnostics);
            }
        private async Task <Document> ConvertToStringLengthComparison(CodeFixContext context, FixResolution fixResolution)
        {
            DocumentEditor editor = await DocumentEditor.CreateAsync(context.Document, context.CancellationToken).ConfigureAwait(false);

            SyntaxNode leftOperand  = GetLeftOperand(fixResolution.BinaryExpressionSyntax);
            SyntaxNode rightOperand = GetRightOperand(fixResolution.BinaryExpressionSyntax);

            // Take the below example:
            //   if (f == String.Empty) ...
            // The comparison operand, f, will now become 'f.Length' and a the other operand will become '0'
            SyntaxNode zeroLengthSyntax = editor.Generator.LiteralExpression(0);

            if (leftOperand == fixResolution.ComparisonOperand)
            {
                leftOperand  = editor.Generator.MemberAccessExpression(leftOperand, "Length");
                rightOperand = zeroLengthSyntax.WithTriviaFrom(rightOperand);
            }
            else
            {
                leftOperand  = zeroLengthSyntax;
                rightOperand = editor.Generator.MemberAccessExpression(rightOperand.WithoutTrivia(), "Length");
            }

            SyntaxNode replacementSyntax = fixResolution.UsesEqualsOperator ?
                                           editor.Generator.ValueEqualsExpression(leftOperand, rightOperand) :
                                           editor.Generator.ValueNotEqualsExpression(leftOperand, rightOperand);

            SyntaxNode replacementAnnotatedSyntax = replacementSyntax.WithAdditionalAnnotations(Formatter.Annotation);

            editor.ReplaceNode(fixResolution.BinaryExpressionSyntax, replacementAnnotatedSyntax);

            return(editor.GetChangedDocument());
        }
        public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context)
        {
            Document      doc   = context.Document;
            SemanticModel model = await doc.GetSemanticModelAsync(context.CancellationToken).ConfigureAwait(false);

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

            if (root.FindNode(context.Span, getInnermostNodeForTie: true) is SyntaxNode node &&
                model.Compilation.TryGetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemEnvironment, out var environmentType) &&
                model.GetOperation(node, context.CancellationToken) is IPropertyReferenceOperation operation)
            {
                string title = MicrosoftNetCoreAnalyzersResources.UseEnvironmentProcessIdFix;
                context.RegisterCodeFix(
                    new MyCodeAction(title,
                                     async cancellationToken =>
                {
                    DocumentEditor editor = await DocumentEditor.CreateAsync(doc, cancellationToken).ConfigureAwait(false);
                    var replacement       = editor.Generator.MemberAccessExpression(editor.Generator.TypeExpressionForStaticMemberAccess(environmentType), "ProcessId");
                    editor.ReplaceNode(node, replacement.WithTriviaFrom(node));
                    return(editor.GetChangedDocument());
                },
                                     equivalenceKey: title),
                    context.Diagnostics);
            }
        }
        public async Task <Solution> InlineAndRemoveMethodAsync(InvocationExpressionSyntax invocation, ExpressionSyntax expression)
        {
            if (invocation.SyntaxTree == MethodDeclaration.SyntaxTree)
            {
                DocumentEditor editor = await DocumentEditor.CreateAsync(Document, CancellationToken).ConfigureAwait(false);

                ExpressionSyntax newExpression = RewriteExpression(invocation, expression);

                editor.ReplaceNode(invocation, newExpression);

                editor.RemoveNode(MethodDeclaration);

                return(editor.GetChangedDocument().Solution());
            }
            else
            {
                Document newDocument = await InlineMethodAsync(invocation, expression).ConfigureAwait(false);

                DocumentId documentId = Document.Solution().GetDocumentId(MethodDeclaration.SyntaxTree);

                newDocument = await newDocument.Solution().GetDocument(documentId).RemoveMemberAsync(MethodDeclaration, CancellationToken).ConfigureAwait(false);

                return(newDocument.Solution());
            }
        }
        private static async Task <Document> SwapArgumentsOrderAsync(Document document, IObjectCreationOperation creation, int paramPosition, int argumentCount, CancellationToken token)
        {
            DocumentEditor editor = await DocumentEditor.CreateAsync(document, token).ConfigureAwait(false);

            SyntaxNode parameter = AddNameOfIfLiteral(creation.Arguments[paramPosition].Value, editor.Generator);
            SyntaxNode newCreation;

            if (argumentCount == 2)
            {
                if (paramPosition == 0)
                {
                    newCreation = editor.Generator.ObjectCreationExpression(creation.Type, creation.Arguments[1].Syntax, parameter);
                }
                else
                {
                    newCreation = editor.Generator.ObjectCreationExpression(creation.Type, parameter, creation.Arguments[0].Syntax);
                }
            }
            else
            {
                Debug.Assert(argumentCount == 3);
                if (paramPosition == 0)
                {
                    newCreation = editor.Generator.ObjectCreationExpression(creation.Type, creation.Arguments[1].Syntax, parameter, creation.Arguments[2].Syntax);
                }
                else
                {
                    newCreation = editor.Generator.ObjectCreationExpression(creation.Type, parameter, creation.Arguments[1].Syntax, creation.Arguments[0].Syntax);
                }
            }
            editor.ReplaceNode(creation.Syntax, newCreation);
            return(editor.GetChangedDocument());
        }
Exemplo n.º 18
0
        public virtual async Task <Solution> InlineAndRemoveAsync(
            SyntaxNode node,
            ExpressionSyntax expression,
            CancellationToken cancellationToken = default(CancellationToken))
        {
            if (node.SyntaxTree == Declaration.SyntaxTree)
            {
                DocumentEditor editor = await DocumentEditor.CreateAsync(Document, cancellationToken).ConfigureAwait(false);

                ExpressionSyntax newExpression = RewriteExpression(node, expression);

                editor.ReplaceNode(node, newExpression);

                editor.RemoveNode(Declaration);

                return(editor.GetChangedDocument().Solution());
            }
            else
            {
                Document newDocument = await InlineAsync(node, expression, cancellationToken).ConfigureAwait(false);

                DocumentId documentId = Document.Solution().GetDocumentId(Declaration.SyntaxTree);

                newDocument = await newDocument.Solution().GetDocument(documentId).RemoveMemberAsync(Declaration, cancellationToken).ConfigureAwait(false);

                return(newDocument.Solution());
            }
        }
        private static async Task <Document> RemoveField(Document document, SyntaxNode node, CancellationToken cancellationToken)
        {
            DocumentEditor editor = await DocumentEditor.CreateAsync(document, cancellationToken).ConfigureAwait(false);

            node = editor.Generator.GetDeclaration(node);
            editor.RemoveNode(node);
            return(editor.GetChangedDocument());
        }
        private static async Task <Document> RemoveFinalizerAsync(Document document, SyntaxNode node, CancellationToken cancellationToken)
        {
            DocumentEditor editor = await DocumentEditor.CreateAsync(document, cancellationToken).ConfigureAwait(false);

            // Get the declaration so that we step up to the methodblocksyntax and not the methodstatementsyntax for VB.
            node = editor.Generator.GetDeclaration(node);
            editor.RemoveNode(node);
            return(editor.GetChangedDocument());
        }
        private static async Task <Document> AddNonSerializedAttribute(Document document, SyntaxNode fieldNode, CancellationToken cancellationToken)
        {
            DocumentEditor editor = await DocumentEditor.CreateAsync(document, cancellationToken).ConfigureAwait(false);

            SyntaxNode attr = editor.Generator.Attribute(editor.Generator.TypeExpression(WellKnownTypes.NonSerializedAttribute(editor.SemanticModel.Compilation)));

            editor.AddAttribute(fieldNode, attr);
            return(editor.GetChangedDocument());
        }
        private static async Task <Document> GetFixAsync(Document document, SyntaxNode expression, bool argument, CancellationToken cancellationToken)
        {
            // Rewrite the expression to include a .ConfigureAwait() after it. We reattach trailing trivia to the end.
            // This is especially important for VB, as the end-of-line may be in the trivia
            DocumentEditor editor = await DocumentEditor.CreateAsync(document, cancellationToken).ConfigureAwait(false);

            FixDiagnostic(editor, expression, argument);
            return(editor.GetChangedDocument());
        }
        private static async Task <Document> AddNullMessageToArgumentListAsync(Document document, IObjectCreationOperation creation, CancellationToken token)
        {
            DocumentEditor editor = await DocumentEditor.CreateAsync(document, token).ConfigureAwait(false);

            SyntaxNode argument    = AddNameOfIfLiteral(creation.Arguments[0].Value, editor.Generator);
            SyntaxNode newCreation = editor.Generator.ObjectCreationExpression(creation.Type, editor.Generator.Argument(editor.Generator.NullLiteralExpression()), argument);

            editor.ReplaceNode(creation.Syntax, newCreation);
            return(editor.GetChangedDocument());
        }
Exemplo n.º 24
0
        private static async Task <Document> AddSerializableAttribute(Document document, SyntaxNode node, CancellationToken cancellationToken)
        {
            DocumentEditor editor = await DocumentEditor.CreateAsync(document, cancellationToken).ConfigureAwait(false);

            SyntaxNode attr = editor.Generator.Attribute(editor.Generator.TypeExpression(
                                                             editor.SemanticModel.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemSerializableAttribute)));

            editor.AddAttribute(node, attr);
            return(editor.GetChangedDocument());
        }
Exemplo n.º 25
0
        private static async Task <Solution> InlineAndRemoveMethodAsync(
            Document document,
            ExpressionStatementSyntax expressionStatement,
            MethodDeclarationSyntax methodDeclaration,
            StatementSyntax[] statements,
            ParameterInfo[] parameterInfos,
            CancellationToken cancellationToken = default(CancellationToken))
        {
            if (expressionStatement.SyntaxTree.Equals(methodDeclaration.SyntaxTree))
            {
                DocumentEditor editor = await DocumentEditor.CreateAsync(document, cancellationToken).ConfigureAwait(false);

                Solution solution = document.Project.Solution;

                StatementSyntax[] newStatements = await ReplaceParameterExpressionWithArgumentExpressionAsync(
                    parameterInfos,
                    statements,
                    solution,
                    cancellationToken).ConfigureAwait(false);

                newStatements[0] = newStatements[0].WithLeadingTrivia(expressionStatement.GetLeadingTrivia());
                newStatements[statements.Length - 1] = newStatements[statements.Length - 1].WithTrailingTrivia(expressionStatement.GetTrailingTrivia());

                if (expressionStatement.Parent.IsKind(SyntaxKind.Block))
                {
                    var block = (BlockSyntax)expressionStatement.Parent;

                    BlockSyntax newBlock = block.WithStatements(block.Statements.ReplaceRange(expressionStatement, newStatements));

                    editor.ReplaceNode(block, newBlock);
                }
                else
                {
                    editor.ReplaceNode(expressionStatement, Block(newStatements));
                }

                editor.RemoveNode(methodDeclaration);

                document = editor.GetChangedDocument();

                return(document.Project.Solution);
            }
            else
            {
                Solution solution = document.Project.Solution;

                document = await InlineMethodAsync(document, expressionStatement, statements, parameterInfos, cancellationToken).ConfigureAwait(false);

                DocumentId documentId = solution.GetDocumentId(methodDeclaration.SyntaxTree);

                solution = document.Project.Solution;

                return(await RemoveMethodAsync(solution.GetDocument(documentId), methodDeclaration, cancellationToken).ConfigureAwait(false));
            }
        }
        private async Task <Document> ConvertToGeneratedDllImport(
            Document doc,
            MethodDeclarationSyntax methodSyntax,
            IMethodSymbol methodSymbol,
            AttributeData dllImportAttr,
            INamedTypeSymbol generatedDllImportAttrType,
            char?entryPointSuffix,
            CancellationToken cancellationToken)
        {
            DocumentEditor editor = await DocumentEditor.CreateAsync(doc, cancellationToken).ConfigureAwait(false);

            SyntaxGenerator generator = editor.Generator;

            var dllImportSyntax = (AttributeSyntax)dllImportAttr !.ApplicationSyntaxReference !.GetSyntax(cancellationToken);

            // Create GeneratedDllImport attribute based on the DllImport attribute
            SyntaxNode generatedDllImportSyntax = GetGeneratedDllImportAttribute(
                editor,
                generator,
                dllImportSyntax,
                methodSymbol.GetDllImportData() !,
                generatedDllImportAttrType,
                methodSymbol.Name,
                entryPointSuffix,
                out SyntaxNode? unmanagedCallConvAttributeMaybe);

            // Add annotation about potential behavioural and compatibility changes
            generatedDllImportSyntax = generatedDllImportSyntax.WithAdditionalAnnotations(
                WarningAnnotation.Create(string.Format(Resources.ConvertToGeneratedDllImportWarning, "[TODO] Documentation link")));

            // Replace DllImport with GeneratedDllImport
            SyntaxNode generatedDeclaration = generator.ReplaceNode(methodSyntax, dllImportSyntax, generatedDllImportSyntax);

            if (!methodSymbol.MethodImplementationFlags.HasFlag(System.Reflection.MethodImplAttributes.PreserveSig))
            {
                generatedDeclaration = await RemoveNoPreserveSigTransform(editor, generatedDeclaration, methodSymbol, cancellationToken).ConfigureAwait(false);
            }

            if (unmanagedCallConvAttributeMaybe is not null)
            {
                generatedDeclaration = generator.AddAttributes(generatedDeclaration, unmanagedCallConvAttributeMaybe);
            }

            // Replace extern keyword with partial keyword
            generatedDeclaration = generator.WithModifiers(
                generatedDeclaration,
                generator.GetModifiers(methodSyntax)
                .WithIsExtern(false)
                .WithPartial(true));

            // Replace the original method with the updated one
            editor.ReplaceNode(methodSyntax, generatedDeclaration);

            return(editor.GetChangedDocument());
        }
        private async Task <Document> ReplaceVarWithExplicitType(Document document, SyntaxNode varNode, ITypeSymbol explicitTypeSymbol, CancellationToken cancellationToken)
        {
            DocumentEditor documentEditor = await DocumentEditor.CreateAsync(document, cancellationToken);

            SyntaxNode explicitTypeNode = documentEditor.Generator.TypeExpression(explicitTypeSymbol)
                                          .WithAdditionalAnnotations(Simplifier.Annotation)
                                          .WithTriviaFrom(varNode);

            documentEditor.ReplaceNode(varNode, explicitTypeNode);
            return(documentEditor.GetChangedDocument());
        }
Exemplo n.º 28
0
        public static KeyValuePair <SyntaxTree, SyntaxTree> FixDocument(Document document)
        {
            DocumentEditor curlyBraceEditor = DocumentEditor.CreateAsync(document).Result;
            SyntaxFixer    fixer            = new SyntaxFixer();
            SyntaxNode     newRoot          = fixer.Visit(curlyBraceEditor.OriginalRoot);

            curlyBraceEditor.ReplaceNode(curlyBraceEditor.OriginalRoot, newRoot);
            Document newDocument = curlyBraceEditor.GetChangedDocument();

            return(new KeyValuePair <SyntaxTree, SyntaxTree>(document.GetSyntaxTreeAsync().Result, newDocument.GetSyntaxTreeAsync().Result));
        }
Exemplo n.º 29
0
        private async Task <Document> OverrideObjectGetHashCode(Document document, SyntaxNode typeDeclaration, CancellationToken cancellationToken)
        {
            DocumentEditor editor = await DocumentEditor.CreateAsync(document, cancellationToken).ConfigureAwait(false);

            SyntaxGenerator generator = editor.Generator;

            SyntaxNode methodDeclaration = generator.GetHashCodeOverrideDeclaration();

            editor.AddMember(typeDeclaration, methodDeclaration);
            return(editor.GetChangedDocument());
        }
Exemplo n.º 30
0
            public async Task <Document> RemoveNodes(Document document, IEnumerable <SyntaxNode> nodes, CancellationToken cancellationToken)
            {
                DocumentEditor editor = await DocumentEditor.CreateAsync(document, cancellationToken).ConfigureAwait(false);

                // Start removing from bottom to top to keep spans of nodes that are removed later.
                foreach (var node in nodes.Where(n => n != null).OrderByDescending(n => n.SpanStart))
                {
                    RemoveNode(editor, node);
                }

                return(editor.GetChangedDocument());
            }