Exemple #1
0
        private static async Task <Document> CreateInterpolatedStringAsync(
            Document document,
            InvocationExpressionSyntax invocation,
            CancellationToken cancellationToken = default(CancellationToken))
        {
            SeparatedSyntaxList <ArgumentSyntax> arguments = invocation.ArgumentList.Arguments;

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

            ImmutableArray <ExpressionSyntax> expandedArguments = ImmutableArray.CreateRange(GetExpandedArguments(arguments, semanticModel));

            string formatText = ((LiteralExpressionSyntax)arguments[0].Expression).Token.ToString();

            var interpolatedString = (InterpolatedStringExpressionSyntax)ParseExpression("$" + formatText);

            var rewriter = new InterpolatedStringSyntaxRewriter(expandedArguments);

            var newInterpolatedString = (InterpolatedStringExpressionSyntax)rewriter.Visit(interpolatedString);

            SyntaxNode root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);

            SyntaxNode newRoot = root.ReplaceNode(invocation, newInterpolatedString);

            return(document.WithSyntaxRoot(newRoot));
        }
        private static Task <Document> RefactorAsync(
            Document document,
            InvocationExpressionSyntax invocation,
            SemanticModel semanticModel,
            CancellationToken cancellationToken = default(CancellationToken))
        {
            SeparatedSyntaxList <ArgumentSyntax> arguments = invocation.ArgumentList.Arguments;

            var formatExpression = (LiteralExpressionSyntax)arguments[0].Expression;

            string formatText = formatExpression.Token.Text;

            bool isVerbatim = formatText.StartsWith("@", StringComparison.Ordinal);

            string text = "$" + formatText;

            var interpolatedString = (InterpolatedStringExpressionSyntax)ParseExpression(text);

            if (CanReplaceInterpolationWithStringLiteralInnerText(arguments, isVerbatim))
            {
                interpolatedString = ReplaceInterpolationWithStringLiteralInnerText(arguments, interpolatedString, text);
            }

            IEnumerable <ExpressionSyntax> interpolationExpressions = GetInterpolationExpressions(arguments, semanticModel, cancellationToken);

            var rewriter = new InterpolatedStringSyntaxRewriter(interpolationExpressions);

            var newNode = (InterpolatedStringExpressionSyntax)rewriter.Visit(interpolatedString);

            newNode = newNode
                      .WithTriviaFrom(invocation)
                      .WithFormatterAnnotation();

            return(document.ReplaceNodeAsync(invocation, newNode, cancellationToken));
        }