private static DeclarationExpressionSyntax GetDeclarationExpression(
            SourceText sourceText, IdentifierNameSyntax identifier,
            TypeSyntax newType, VariableDeclaratorSyntax declaratorOpt)
        {
            newType = newType.WithoutTrivia().WithAdditionalAnnotations(Formatter.Annotation);
            var designation = SyntaxFactory.SingleVariableDesignation(identifier.Identifier);

            if (declaratorOpt != null)
            {
                // We're removing a single declarator.  Copy any comments it has to the out-var.
                //
                // Note: this is tricky due to comment ownership.  We want the comments that logically
                // belong to the declarator, even if our syntax model attaches them to other tokens.
                var precedingTrivia = declaratorOpt.GetAllPrecedingTriviaToPreviousToken(
                    sourceText, includePreviousTokenTrailingTriviaOnlyIfOnSameLine: true);
                if (precedingTrivia.Any(t => t.IsSingleOrMultiLineComment()))
                {
                    designation = designation.WithPrependedLeadingTrivia(MassageTrivia(precedingTrivia));
                }

                if (declaratorOpt.GetTrailingTrivia().Any(t => t.IsSingleOrMultiLineComment()))
                {
                    designation = designation.WithAppendedTrailingTrivia(MassageTrivia(declaratorOpt.GetTrailingTrivia()));
                }
            }

            return(SyntaxFactory.DeclarationExpression(newType, designation));
        }
        public static async Task ComputeRefactoringAsync(RefactoringContext context, LocalDeclarationStatementSyntax localDeclaration)
        {
            SyntaxNode method = localDeclaration.GetContainingMethod();

            if (method?.IsKind(SyntaxKind.MethodDeclaration) == true)
            {
                VariableDeclarationSyntax declaration = localDeclaration.Declaration;

                if (declaration != null)
                {
                    VariableDeclaratorSyntax variable = declaration
                                                        .Variables
                                                        .FirstOrDefault(f => !f.IsMissing && f.Identifier.Span.Contains(context.Span));

                    if (variable != null)
                    {
                        TypeSyntax type = declaration.Type;

                        if (type != null)
                        {
                            if (type.IsVar)
                            {
                                SemanticModel semanticModel = await context.GetSemanticModelAsync().ConfigureAwait(false);

                                ITypeSymbol typeSymbol = semanticModel.GetTypeInfo(type, context.CancellationToken).Type;

                                if (typeSymbol?.SupportsExplicitDeclaration() == true)
                                {
                                    type = Type(typeSymbol);
                                }
                                else
                                {
                                    type = null;
                                }
                            }

                            if (type != null)
                            {
                                context.RegisterRefactoring(
                                    $"Promote '{variable.Identifier.ValueText}' to parameter",
                                    cancellationToken =>
                                {
                                    return(RefactorAsync(
                                               context.Document,
                                               (MethodDeclarationSyntax)method,
                                               localDeclaration,
                                               type.WithoutTrivia(),
                                               variable,
                                               cancellationToken));
                                });
                            }
                        }
                    }
                }
            }
        }
        public static Task <Document> RefactorAsync(
            Document document,
            TypeSyntax type,
            TypeSyntax nullableType,
            CancellationToken cancellationToken)
        {
            TypeSyntax newType = NullableType(nullableType.WithoutTrivia(), QuestionToken())
                                 .WithTriviaFrom(type)
                                 .WithFormatterAnnotation();

            return(document.ReplaceNodeAsync(type, newType, cancellationToken));
        }
        private static async Task <Document> SimplifyNullableOfTAsync(
            Document document,
            TypeSyntax type,
            TypeSyntax nullableType,
            CancellationToken cancellationToken)
        {
            SyntaxNode oldRoot = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);

            TypeSyntax newType = SyntaxFactory.NullableType(nullableType.WithoutTrivia(), SyntaxFactory.Token(SyntaxKind.QuestionToken))
                                 .WithTriviaFrom(type)
                                 .WithFormatterAnnotation();

            SyntaxNode newRoot = oldRoot.ReplaceNode(type, newType);

            return(document.WithSyntaxRoot(newRoot));
        }
Ejemplo n.º 5
0
 private InvocationExpressionSyntax WrapInTaskFromException(ExpressionSyntax node)
 {
     return(InvocationExpression(
                MemberAccessExpression(
                    SyntaxKind.SimpleMemberAccessExpression,
                    _namespaceMetadata.TaskConflict
                                                 ? SyntaxNodeExtensions.ConstructNameSyntax("System.Threading.Tasks.Task").WithLeadingTrivia(node.GetLeadingTrivia())
                                                 : IdentifierName(Identifier(TriviaList(node.GetLeadingTrivia()), nameof(Task), TriviaList())),
                    GenericName(
                        Identifier("FromException"))
                    .WithTypeArgumentList(
                        TypeArgumentList(
                            SingletonSeparatedList(
                                _retunTypeSyntax == null
                                                                                 ? PredefinedType(Token(SyntaxKind.ObjectKeyword))
                                                                                 : _retunTypeSyntax.WithoutTrivia())))))
            .WithArgumentList(
                ArgumentList(
                    SingletonSeparatedList(
                        Argument(node.WithoutLeadingTrivia())))));
 }
Ejemplo n.º 6
0
        public static async Task ComputeRefactoringAsync(RefactoringContext context, LocalDeclarationStatementSyntax localDeclaration)
        {
            SemanticModel semanticModel = await context.GetSemanticModelAsync().ConfigureAwait(false);

            ISymbol symbol = semanticModel.GetEnclosingSymbol(localDeclaration.SpanStart, context.CancellationToken);

            if (symbol?.IsMethod() == true)
            {
                var methodsymbol = (IMethodSymbol)symbol;

                if (methodsymbol.MethodKind == MethodKind.Ordinary)
                {
                    if (methodsymbol.PartialImplementationPart != null)
                    {
                        symbol = methodsymbol.PartialImplementationPart;
                    }

                    SyntaxNode node = await symbol
                                      .DeclaringSyntaxReferences[0]
                                      .GetSyntaxAsync(context.CancellationToken)
                                      .ConfigureAwait(false);

                    var method = node as MethodDeclarationSyntax;

                    if (method != null)
                    {
                        VariableDeclarationSyntax declaration = localDeclaration.Declaration;

                        if (declaration != null)
                        {
                            VariableDeclaratorSyntax variable = declaration
                                                                .Variables
                                                                .FirstOrDefault(f => !f.IsMissing && f.Identifier.Span.Contains(context.Span));

                            if (variable != null)
                            {
                                TypeSyntax type = declaration.Type;

                                if (type != null)
                                {
                                    if (type.IsVar)
                                    {
                                        ITypeSymbol typeSymbol = semanticModel.GetTypeSymbol(type, context.CancellationToken);

                                        if (typeSymbol?.SupportsExplicitDeclaration() == true)
                                        {
                                            type = typeSymbol.ToTypeSyntax();
                                        }
                                        else
                                        {
                                            type = null;
                                        }
                                    }

                                    if (type != null)
                                    {
                                        context.RegisterRefactoring(
                                            $"Promote '{variable.Identifier.ValueText}' to parameter",
                                            cancellationToken =>
                                        {
                                            return(RefactorAsync(
                                                       context.Document,
                                                       method,
                                                       localDeclaration,
                                                       type.WithoutTrivia().WithSimplifierAnnotation(),
                                                       variable,
                                                       cancellationToken));
                                        });
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
Ejemplo n.º 7
0
 /// <summary>
 /// Determines whether the specified <see cref="TypeSyntax"/> instances refer to the same type.
 /// </summary>
 /// <param name="syntax1">The first <see cref="TypeSyntax"/> to compare.</param>
 /// <param name="syntax2">The second <see cref="TypeSyntax"/> to compare.</param>
 /// <returns><c>true</c> if <paramref name="syntax1"/> refers to the same type as <paramref name="syntax2"/>; otherwise, <c>false</c>.</returns>
 private static bool AreSame(TypeSyntax syntax1, TypeSyntax syntax2)
 {
     return(syntax1.GetType() == syntax2.GetType() && syntax1.WithoutTrivia().NormalizeWhitespace().ToString() == syntax2.WithoutTrivia().NormalizeWhitespace().ToString());
 }
Ejemplo n.º 8
0
        public static void ComputeRefactoring(
            RefactoringContext context,
            LocalDeclarationStatementSyntax localDeclaration,
            SemanticModel semanticModel)
        {
            if (!(semanticModel.GetEnclosingSymbol(localDeclaration.SpanStart, context.CancellationToken) is IMethodSymbol methodSymbol))
            {
                return;
            }

            if (methodSymbol.IsImplicitlyDeclared)
            {
                return;
            }

            if (methodSymbol.MethodKind != MethodKind.Ordinary)
            {
                return;
            }

            if (methodSymbol.PartialImplementationPart != null)
            {
                methodSymbol = methodSymbol.PartialImplementationPart;
            }

            if (!(methodSymbol.GetSyntax(context.CancellationToken) is MethodDeclarationSyntax methodDeclaration))
            {
                return;
            }

            VariableDeclarationSyntax declaration = localDeclaration.Declaration;

            if (declaration == null)
            {
                return;
            }

            VariableDeclaratorSyntax variable = declaration
                                                .Variables
                                                .FirstOrDefault(f => !f.IsMissing && f.Identifier.Span.Contains(context.Span));

            if (variable == null)
            {
                return;
            }

            TypeSyntax type = declaration.Type;

            if (type == null)
            {
                return;
            }

            if (type.IsVar)
            {
                ITypeSymbol typeSymbol = semanticModel.GetTypeSymbol(type, context.CancellationToken);

                if (typeSymbol?.SupportsExplicitDeclaration() == true)
                {
                    type = typeSymbol.ToTypeSyntax();
                }
                else
                {
                    return;
                }
            }

            context.RegisterRefactoring(
                $"Promote '{variable.Identifier.ValueText}' to parameter",
                cancellationToken =>
            {
                return(RefactorAsync(
                           context.Document,
                           methodDeclaration,
                           localDeclaration,
                           type.WithoutTrivia().WithSimplifierAnnotation(),
                           variable,
                           cancellationToken));
            },
                RefactoringIdentifiers.PromoteLocalToParameter);
        }
Ejemplo n.º 9
0
 public RecordBuilder AddProperty(TypeSyntax type, string identifier)
 {
     this.properties.Add(new PropertyInfo(type.WithoutTrivia(), identifier));
     return(this);
 }
Ejemplo n.º 10
0
 internal static QualifiedCrefSyntax CrefMember(this TypeSyntax type, string name) =>
 QualifiedCref(type.WithoutTrivia(), NameMemberCref(ParseTypeName(name)));
Ejemplo n.º 11
0
        private async Task <Document> AddMixinAttribute(CodeRefactoringContext context, ClassDeclarationSyntax @class, TypeSyntax baseType, CancellationToken ct)
        {
            var root = await context.Document.GetSyntaxRootAsync(ct).ConfigureAwait(false);

            var newClass = @class.WithAttributeLists(@class.AttributeLists.Add(
                                                         AttributeList(
                                                             SeparatedList(new[] {
                Attribute(IdentifierName(nameof(Mixin)),
                          AttributeArgumentList(SeparatedList(new[] { AttributeArgument(TypeOfExpression(baseType.WithoutTrivia())) }))
                          )
            })
                                                             ).WithAdditionalAnnotations(Formatter.Annotation)
                                                         ));

            root = root.ReplaceNode(@class, newClass);

            return(context.Document.WithSyntaxRoot(root));
        }