private bool CheckForCastedLocalDeclarationPattern(
            SemanticModel semanticModel,
            AnonymousFunctionExpressionSyntax anonymousFunction,
            CancellationToken cancellationToken,
            out LocalDeclarationStatementSyntax localDeclaration)
        {
            // var t = (Type)(<anonymous function>)
            var containingStatement = anonymousFunction.GetAncestor <StatementSyntax>();

            if (containingStatement.IsKind(SyntaxKind.LocalDeclarationStatement))
            {
                localDeclaration = (LocalDeclarationStatementSyntax)containingStatement;
                if (localDeclaration.Declaration.Variables.Count == 1)
                {
                    var variableDeclarator = localDeclaration.Declaration.Variables[0];
                    if (variableDeclarator.Initializer != null)
                    {
                        var value = variableDeclarator.Initializer.Value.WalkDownParentheses();
                        if (value is CastExpressionSyntax castExpression)
                        {
                            if (castExpression.Expression.WalkDownParentheses() == anonymousFunction)
                            {
                                return(true);
                            }
                        }
                    }
                }
            }

            localDeclaration = null;
            return(false);
        }
Example #2
0
        private static SyntaxNode ReplaceAnonymousWithLocalFunction(
            Workspace workspace,
            SyntaxNode currentRoot,
            LocalDeclarationStatementSyntax localDeclaration,
            AnonymousFunctionExpressionSyntax anonymousFunction,
            IMethodSymbol delegateMethod,
            ParameterListSyntax parameterList,
            bool makeStatic
            )
        {
            var newLocalFunctionStatement = CreateLocalFunctionStatement(
                localDeclaration,
                anonymousFunction,
                delegateMethod,
                parameterList,
                makeStatic
                )
                                            .WithTriviaFrom(localDeclaration)
                                            .WithAdditionalAnnotations(Formatter.Annotation);

            var editor = new SyntaxEditor(currentRoot, workspace);

            editor.ReplaceNode(localDeclaration, newLocalFunctionStatement);

            var anonymousFunctionStatement = anonymousFunction.GetAncestor <StatementSyntax>();

            if (anonymousFunctionStatement != localDeclaration)
            {
                // This is the split decl+init form.  Remove the second statement as we're
                // merging into the first one.
                editor.RemoveNode(anonymousFunctionStatement);
            }

            return(editor.GetChangedRoot());
        }