Beispiel #1
0
        Task <Document> ChangeMagicNumberToIDAsync(CodeFixContext context, Document document, Diagnostic diagnostic, SyntaxNode root)
        {
            var n = root.FindNode(diagnostic.Location.SourceSpan);

            if (n is ArgumentSyntax argument && argument.Expression is LiteralExpressionSyntax)
            {
                n = argument.Expression;
            }

            // We expect this to point directly at the NumericLiteralExpression
            if (!(n is LiteralExpressionSyntax literalExpressionSyntax && literalExpressionSyntax.IsKind(SyntaxKind.NumericLiteralExpression)))
            {
                return(Task.FromResult(document));
            }

            string result = diagnostic.Properties["result"];

            NameSyntax name = SyntaxFactory.IdentifierName(result);

            name = name.WithLeadingTrivia(literalExpressionSyntax.GetLeadingTrivia()).WithTrailingTrivia(literalExpressionSyntax.GetTrailingTrivia()); // try WithTriviaFrom instead?

            var newRoot = root.ReplaceNode(literalExpressionSyntax, name);


            var compilationUnitSyntax = newRoot as CompilationUnitSyntax;

            var systemThreadingUsingName =
                SyntaxFactory.QualifiedName(
                    SyntaxFactory.IdentifierName("Terraria"),
                    SyntaxFactory.IdentifierName("ID"));

            if (compilationUnitSyntax.Usings.All(u => u.Name.GetText().ToString() != "Terraria.ID"))
            {
                if (compilationUnitSyntax.Usings.Any())
                {
                    newRoot = newRoot.InsertNodesAfter(compilationUnitSyntax.Usings.Last(), new[] { SyntaxFactory.UsingDirective(systemThreadingUsingName) });
                }
                else
                {
                    newRoot = compilationUnitSyntax.AddUsings(new[] { SyntaxFactory.UsingDirective(systemThreadingUsingName) });
                }
            }
            return(Task.FromResult(document.WithSyntaxRoot(newRoot)));
        }