public static void ComputeRefactorings(RefactoringContext context, InterpolationSyntax interpolation)
        {
            if (context.IsRefactoringEnabled(RefactoringIdentifiers.MergeInterpolationIntoInterpolatedString) &&
                MergeInterpolationIntoInterpolatedStringRefactoring.CanRefactor(interpolation))
            {
                string innerText = SyntaxUtility.GetStringLiteralInnerText((LiteralExpressionSyntax)interpolation.Expression);

                context.RegisterRefactoring(
                    $"Merge '{innerText}' into interpolated string",
                    cancellationToken => MergeInterpolationIntoInterpolatedStringRefactoring.RefactorAsync(context.Document, interpolation, cancellationToken));
            }

            if (context.IsRefactoringEnabled(RefactoringIdentifiers.RemoveInterpolation) &&
                (interpolation.OpenBraceToken.Span.Contains(context.Span) ||
                 interpolation.CloseBraceToken.Span.Contains(context.Span)))
            {
                context.RegisterRefactoring("Remove interpolation",
                                            cancellationToken =>
                {
                    return(RemoveInterpolationRefactoring.RefactorAsync(
                               context.Document,
                               interpolation,
                               cancellationToken));
                });
            }
        }
Beispiel #2
0
        public static bool CanRefactor(InterpolationSyntax interpolation)
        {
            if (interpolation == null)
            {
                throw new ArgumentNullException(nameof(interpolation));
            }

            ExpressionSyntax expression = interpolation.Expression;

            if (expression?.IsKind(SyntaxKind.StringLiteralExpression) == true)
            {
                var interpolatedString = interpolation.Parent as InterpolatedStringExpressionSyntax;

                if (interpolatedString != null)
                {
                    var literalExpression = (LiteralExpressionSyntax)expression;

                    if (interpolatedString.IsVerbatim() == literalExpression.Token.IsVerbatimStringLiteral())
                    {
                        return(true);
                    }
                }
            }

            return(false);
        }
Beispiel #3
0
        public static Task <Document> RefactorAsync(
            Document document,
            InterpolationSyntax interpolation,
            CancellationToken cancellationToken = default(CancellationToken))
        {
            if (document == null)
            {
                throw new ArgumentNullException(nameof(document));
            }

            if (interpolation == null)
            {
                throw new ArgumentNullException(nameof(interpolation));
            }

            var interpolatedString = (InterpolatedStringExpressionSyntax)interpolation.Parent;

            string s = interpolatedString.ToString();

            var literalExpression = (LiteralExpressionSyntax)interpolation.Expression;

            s = s.Substring(0, interpolation.Span.Start - interpolatedString.Span.Start)
                + StringUtility.DoubleBraces(literalExpression.GetStringLiteralInnerText())
                + s.Substring(interpolation.Span.End - interpolatedString.Span.Start);

            var newInterpolatedString = (InterpolatedStringExpressionSyntax)SyntaxFactory.ParseExpression(s)
                                        .WithTriviaFrom(interpolatedString);

            return(document.ReplaceNodeAsync(interpolatedString, newInterpolatedString, cancellationToken));
        }
Beispiel #4
0
        public static Doc Print(InterpolationSyntax node)
        {
            var docs = new List <Doc>
            {
                Token.Print(node.OpenBraceToken),
                Node.Print(node.Expression)
            };

            if (node.AlignmentClause != null)
            {
                docs.Add(
                    Token.PrintWithSuffix(node.AlignmentClause.CommaToken, " "),
                    Node.Print(node.AlignmentClause.Value)
                    );
            }
            if (node.FormatClause != null)
            {
                docs.Add(
                    Token.Print(node.FormatClause.ColonToken),
                    Token.Print(node.FormatClause.FormatStringToken)
                    );
            }

            docs.Add(Token.Print(node.CloseBraceToken));
            return(Doc.Concat(docs));
        }
Beispiel #5
0
        private Doc PrintInterpolationSyntax(InterpolationSyntax node)
        {
            var parts = new Parts(
                this.PrintSyntaxToken(node.OpenBraceToken),
                this.Print(node.Expression)
                );

            if (node.AlignmentClause != null)
            {
                parts.Push(
                    this.PrintSyntaxToken(node.AlignmentClause.CommaToken, " "),
                    this.Print(node.AlignmentClause.Value)
                    );
            }
            if (node.FormatClause != null)
            {
                parts.Push(
                    this.PrintSyntaxToken(node.FormatClause.ColonToken),
                    this.PrintSyntaxToken(node.FormatClause.FormatStringToken)
                    );
            }

            parts.Push(this.PrintSyntaxToken(node.CloseBraceToken));
            return(Concat(parts));
        }
Beispiel #6
0
        public override Evaluation VisitInterpolation(InterpolationSyntax node)
        {
            node.AlignmentClause?.Accept <Evaluation>(this);
            node.FormatClause?.Accept <Evaluation>(this);
            node.Expression?.Accept <Evaluation>(this);

            return(base.VisitInterpolation(node));
        }
Beispiel #7
0
        public override void VisitInterpolation(InterpolationSyntax node)
        {
            node.AlignmentClause?.Accept(this);
            node.FormatClause?.Accept(this);
            node.Expression?.Accept(this);

            base.VisitInterpolation(node);
        }
Beispiel #8
0
 public static void ComputeRefactorings(RefactoringContext context, InterpolationSyntax interpolation)
 {
     if (context.IsRefactoringEnabled(RefactoringIdentifiers.RemoveInterpolation) &&
         context.Span.IsContainedInSpan(interpolation.OpenBraceToken, interpolation.CloseBraceToken))
     {
         context.RegisterRefactoring("Remove interpolation",
                                     cancellationToken => context.Document.RemoveNodeAsync(interpolation, SyntaxRemoveOptions.KeepUnbalancedDirectives, cancellationToken));
     }
 }
        private static void InterpolationCheck(InterpolationSyntax interpolation, SemanticModel semanticModel, Action <Diagnostic> reportDiagnostic, string filePath, CancellationToken cancellationToken)
        {
            var typeInfo = semanticModel.GetTypeInfo(interpolation.Expression, cancellationToken);

            if (typeInfo.Type?.IsValueType == true)
            {
                reportDiagnostic(Diagnostic.Create(ValueTypeToReferenceTypeConversionRule, interpolation.Expression.GetLocation(), EmptyMessageArgs));
                HeapAllocationAnalyzerEventSource.Logger.BoxingAllocation(filePath);
            }
        }
Beispiel #10
0
            public override SyntaxNode VisitInterpolation(InterpolationSyntax node)
            {
                var result = (InterpolationSyntax)base.VisitInterpolation(node);

                if (result.Expression != null && !result.Expression.IsKind(SyntaxKind.ParenthesizedExpression))
                {
                    result = result.WithExpression(result.Expression.Parenthesize());
                }

                return(result);
            }
Beispiel #11
0
        public static async Task <Document> RefactorAsync(
            Document document,
            InterpolationSyntax interpolation,
            CancellationToken cancellationToken = default(CancellationToken))
        {
            SyntaxNode root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);

            SyntaxNode newRoot = root.RemoveNode(interpolation, SyntaxRemoveOptions.KeepUnbalancedDirectives);

            return(document.WithSyntaxRoot(newRoot));
        }
Beispiel #12
0
 public override SyntaxNode VisitInterpolatedStringExpression(InterpolatedStringExpressionSyntax node)
 {
     return(node.Contents.Count() == 1
         ? node.Contents.Single() switch
     {
         InterpolationSyntax interpolation
         => interpolation.Expression,
         InterpolatedStringTextSyntax interpolatedStringText
         => interpolatedStringText.TextToken.Text.ToLiteralExpression(),
         _ => throw new NotSupportedException()
     }
        private void FindInterpolatedStrings(SyntaxNode syntaxNode, SemanticModel model, ref List <VulnerabilityDetail> vulnerabilities)
        {
            var interpolatedStrings = syntaxNode.DescendantNodes().OfType <InterpolatedStringExpressionSyntax>();

            foreach (var interpolatedString in interpolatedStrings)
            {
                string variableValue = interpolatedString.Contents.JoinStr(null, x => x switch
                {
                    InterpolationSyntax interpolation => model.GetConstantValue(interpolation.Expression) is { } optional &&
                    optional.HasValue && optional.Value is string value ? value : null,
                    InterpolatedStringTextSyntax text => text.TextToken.ToString(),
                    _ => null
                } ?? CredentialSeparator.ToString());
        internal static void Analyze(SyntaxNodeAnalysisContext context, InterpolationSyntax interpolation)
        {
            ExpressionSyntax expression = interpolation.Expression;

            if (expression?.IsKind(SyntaxKind.ParenthesizedExpression) == true)
            {
                var parenthesizedExpression = (ParenthesizedExpressionSyntax)expression;

                if (parenthesizedExpression.Expression?.IsKind(SyntaxKind.ConditionalExpression) == false)
                {
                    AnalyzeParenthesizedExpression(context, parenthesizedExpression);
                }
            }
        }
Beispiel #15
0
        public override void VisitInterpolation(InterpolationSyntax node)
        {
            if (!PreVisit(node))
            {
                return;
            }

            node.AlignmentClause?.Accept(this);
            node.FormatClause?.Accept(this);
            node.Expression?.Accept(this);

            base.VisitInterpolation(node);

            PostVisit(node);
        }
            public override SyntaxNode VisitInterpolation(InterpolationSyntax node)
            {
                var literalExpression = node.Expression as LiteralExpressionSyntax;

                if (literalExpression != null && literalExpression.IsKind(SyntaxKind.NumericLiteralExpression))
                {
                    var index = (int)literalExpression.Token.Value;
                    if (index >= 0 && index < expandedArguments.Length)
                    {
                        return(node.WithExpression(expandedArguments[index]));
                    }
                }

                return(base.VisitInterpolation(node));
            }
 public static void ComputeRefactorings(RefactoringContext context, InterpolationSyntax interpolation)
 {
     if (context.IsRefactoringEnabled(RefactoringIdentifiers.RemoveInterpolation) &&
         (interpolation.OpenBraceToken.Span.Contains(context.Span) ||
          interpolation.CloseBraceToken.Span.Contains(context.Span)))
     {
         context.RegisterRefactoring("Remove interpolation",
                                     cancellationToken =>
         {
             return(RemoveInterpolationRefactoring.RefactorAsync(
                        context.Document,
                        interpolation,
                        cancellationToken));
         });
     }
 }
            public override SyntaxNode VisitInterpolation(InterpolationSyntax node)
            {
                ExpressionSyntax expression = node.Expression;

                if (expression?.Kind() == SyntaxKind.NumericLiteralExpression)
                {
                    var literalExpression = (LiteralExpressionSyntax)expression;

                    var index = (int)literalExpression.Token.Value;

                    if (index >= 0 && index < _interpolationExpressions.Length)
                    {
                        return(node.WithExpression(_interpolationExpressions[index]));
                    }
                }

                return(base.VisitInterpolation(node));
            }
Beispiel #19
0
        public static Task <Document> RefactorAsync(
            Document document,
            InterpolationSyntax interpolation,
            CancellationToken cancellationToken = default(CancellationToken))
        {
            var interpolatedString = (InterpolatedStringExpressionSyntax)interpolation.Parent;

            string s = interpolatedString.ToString();

            s = s.Substring(0, interpolation.SpanStart - interpolatedString.SpanStart)
                + StringUtility.DoubleBraces(SyntaxInfo.StringLiteralExpressionInfo(interpolation.Expression).InnerText)
                + s.Substring(interpolation.Span.End - interpolatedString.SpanStart);

            var newInterpolatedString = (InterpolatedStringExpressionSyntax)SyntaxFactory.ParseExpression(s)
                                        .WithTriviaFrom(interpolatedString);

            return(document.ReplaceNodeAsync(interpolatedString, newInterpolatedString, cancellationToken));
        }
Beispiel #20
0
        private void AnalyzeInterpolation(SyntaxNodeAnalysisContext context)
        {
            InterpolationSyntax syntax = (InterpolationSyntax)context.Node;

            var type = context.SemanticModel.GetTypeInfo(syntax.Expression);

            if (IsItAlreadyObject(type, context))
            {
                return;
            }

            if (HasToStringOverride(type, context))
            {
                return;
            }

            context.ReportDiagnostic(Diagnostic.Create(Rule, syntax.GetLocation()));
        }
Beispiel #21
0
            public override SyntaxNode VisitInterpolation(InterpolationSyntax node)
            {
                if (node == null)
                {
                    throw new ArgumentNullException(nameof(node));
                }

                var literalExpression = node.Expression as LiteralExpressionSyntax;

                if (literalExpression?.IsKind(SyntaxKind.NumericLiteralExpression) == true)
                {
                    var index = (int)literalExpression.Token.Value;

                    if (index >= 0 && index < _expandedArguments.Length)
                    {
                        return(node.WithExpression(_expandedArguments[index]));
                    }
                }

                return(base.VisitInterpolation(node));
            }
        private static bool IgnoreInterpolation(SourceText text, int offset, InterpolationSyntax interpolation)
        {
            // We can ignore the hole if all the content of it is after the region's indentation level.
            // In that case, it's fine to draw the line through the hole as it won't intersect any code
            // (or show up on the right side of the line).

            var holeStartLine = text.Lines.GetLineFromPosition(interpolation.SpanStart).LineNumber;
            var holeEndLine   = text.Lines.GetLineFromPosition(interpolation.Span.End).LineNumber;

            for (var i = holeStartLine; i <= holeEndLine; i++)
            {
                var line = text.Lines[i];
                var currentLineOffset = line.GetFirstNonWhitespaceOffset();

                if (currentLineOffset != null && currentLineOffset < offset)
                {
                    return(false);
                }
            }

            return(true);
        }
Beispiel #23
0
        public static async Task <Document> RefactorAsync(
            Document document,
            InterpolationSyntax interpolation,
            CancellationToken cancellationToken = default(CancellationToken))
        {
            SyntaxNode root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);

            var interpolatedString = (InterpolatedStringExpressionSyntax)interpolation.Parent;

            string s = interpolatedString.ToString();

            s = s.Substring(0, interpolation.Span.Start - interpolatedString.Span.Start)
                + SyntaxUtility.GetStringLiteralInnerText((LiteralExpressionSyntax)interpolation.Expression)
                + s.Substring(interpolation.Span.End - interpolatedString.Span.Start);

            var newInterpolatedString = (InterpolatedStringExpressionSyntax)SyntaxFactory.ParseExpression(s)
                                        .WithTriviaFrom(interpolatedString);

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

            return(document.WithSyntaxRoot(newRoot));
        }
        public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context)
        {
            SyntaxNode root = await context.Document.GetSyntaxRootAsync(context.CancellationToken).ConfigureAwait(false);

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

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

            if (interpolation == null)
            {
                return;
            }

            string innerText = SyntaxUtility.GetStringLiteralInnerText((LiteralExpressionSyntax)interpolation.Expression);

            CodeAction codeAction = CodeAction.Create(
                $"Merge '{innerText}' into interpolated string",
                cancellationToken => MergeInterpolationIntoInterpolatedStringRefactoring.RefactorAsync(context.Document, interpolation, cancellationToken),
                DiagnosticIdentifiers.MergeInterpolationIntoInterpolatedString + EquivalenceKeySuffix);

            context.RegisterCodeFix(codeAction, context.Diagnostics);
        }
 public override SyntaxNode VisitInterpolation(InterpolationSyntax node)
 {
     node = (InterpolationSyntax)base.VisitInterpolation(node);
     Classes.Add(node);
     return(node);
 }
            public override SyntaxNode VisitInterpolation(InterpolationSyntax node)
            {
                var result = (InterpolationSyntax)base.VisitInterpolation(node);

                if (result.Expression != null && !result.Expression.IsKind(SyntaxKind.ParenthesizedExpression))
                {
                    result = result.WithExpression(result.Expression.Parenthesize());
                }

                return result;
            }
        private static bool RemovalMayIntroduceInterpolationAmbiguity(ParenthesizedExpressionSyntax node)
        {
            // First, find the parenting interpolation. If we find a parenthesize expression first,
            // we can bail out early.
            InterpolationSyntax interpolation = null;

            foreach (var ancestor in node.Parent.AncestorsAndSelf())
            {
                if (ancestor.IsKind(SyntaxKind.ParenthesizedExpression))
                {
                    return(false);
                }

                if (ancestor.IsKind(SyntaxKind.Interpolation))
                {
                    interpolation = (InterpolationSyntax)ancestor;
                    break;
                }
            }

            if (interpolation == null)
            {
                return(false);
            }

            // In order determine whether removing this parenthesized expression will introduce a
            // parsing ambiguity, we must dig into the child tokens and nodes to determine whether
            // they include any : or :: tokens. If they do, we can't remove the parentheses because
            // the parser would assume that the first : would begin the format clause of the interpolation.

            var stack = s_nodeStackPool.AllocateAndClear();

            try
            {
                stack.Push(node.Expression);

                while (stack.Count > 0)
                {
                    var expression = stack.Pop();

                    foreach (var nodeOrToken in expression.ChildNodesAndTokens())
                    {
                        // Note: There's no need drill into other parenthesized expressions, since any colons in them would be unambiguous.
                        if (nodeOrToken.IsNode && !nodeOrToken.IsKind(SyntaxKind.ParenthesizedExpression))
                        {
                            stack.Push(nodeOrToken.AsNode());
                        }
                        else if (nodeOrToken.IsToken)
                        {
                            if (nodeOrToken.IsKind(SyntaxKind.ColonToken) || nodeOrToken.IsKind(SyntaxKind.ColonColonToken))
                            {
                                return(true);
                            }
                        }
                    }
                }
            }
            finally
            {
                s_nodeStackPool.ClearAndFree(stack);
            }

            return(false);
        }
            public override SyntaxNode VisitInterpolation(InterpolationSyntax node)
            {
                var literalExpression = node.Expression as LiteralExpressionSyntax;
                if (literalExpression != null && literalExpression.IsKind(SyntaxKind.NumericLiteralExpression))
                {
                    var index = (int)literalExpression.Token.Value;
                    if (index >= 0 && index < expandedArguments.Length)
                    {
                        return node.WithExpression(expandedArguments[index]);
                    }
                }

                return base.VisitInterpolation(node);
            }
 /// <inheritdoc />
 public override Expression VisitInterpolation(InterpolationSyntax node)
 {
     throw Unexpected(node, nameof(VisitInterpolatedStringExpression));
 }
 /// <summary>
 /// 
 /// </summary>
 /// <param name="node"></param>
 public override sealed void VisitInterpolation(InterpolationSyntax node)
 {
     this.OnNodeVisited(node, this.type.IsInstanceOfType(node));
     base.VisitInterpolation(node);
 }
Beispiel #31
0
 public override void VisitInterpolation(InterpolationSyntax node)
 {
     Log(node, "Unsupported Syntax !");
 }
Beispiel #32
0
 private bool ReplacementBreaksInterpolation(InterpolationSyntax interpolation, InterpolationSyntax newInterpolation)
 {
     return(!TypesAreCompatible(interpolation.Expression, newInterpolation.Expression));
 }
Beispiel #33
0
 public override void VisitInterpolation(InterpolationSyntax node)
 {
     throw new NotImplementedException();
 }
 /// <summary>
 /// 
 /// </summary>
 /// <param name="node"></param>
 public override sealed void VisitInterpolation(InterpolationSyntax node)
 {
     this.OnNodeVisited(node);
     if (!this.traverseRootOnly) base.VisitInterpolation(node);
 }