public static List <QualifiedTypeName> GetQualifiedTypeNames(SyntaxNode node)
        {
            var me = new TypeNameWalker();

            me.Visit(node);
            return(me.m_TypeNames);
        }
Exemple #2
0
        public static async Task <Document> GenerateWithExtension(Document document, ClassDeclarationSyntax classDeclaration, CancellationToken cancellationToken)
        {
            var classInfos = TypeNameWalker.GetQualifiedTypeNames(await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false));

            var constructors = classDeclaration
                               .Members
                               .OfType <ConstructorDeclarationSyntax>()
                               .ToImmutableArray();

            if (!constructors.Any())
            {
                return(document);
            }

            var constructor = constructors
                              .MaxBy(c => c.ParameterList.Parameters.Count)
                              .First();


            var originalClassName  = classDeclaration.Name();
            var classInfo          = classInfos.First(c => c.Name == originalClassName);
            var fullClassName      = classInfo.QualifiedName(".");
            var extensionClassName = $"{classInfo.QualifiedName("")}WithExtension";
            var extensionClass     = SyntaxFactory
                                     .ClassDeclaration(extensionClassName)
                                     .Public()
                                     .Static()
                                     .AddMembers(
                SyntaxFactory.MethodDeclaration(Types.String, "With")
                .Public()
                .Static()
                .WithReturnType(SyntaxFactory.ParseTypeName(fullClassName))
                .WithParameterList(ToWithParameters(fullClassName, classDeclaration, constructor.ParameterList))
                .WithExpressionBody(Call(fullClassName, classDeclaration, constructor.ParameterList))

                ).NormalizeWhitespace();


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

            var updated = root.AddOrUpdateClass(extensionClassName, c => extensionClass, c => extensionClass);

            var updatedDoc = document.WithSyntaxRoot(updated);

            updatedDoc = await Formatter.FormatAsync(updatedDoc, cancellationToken : cancellationToken);

            return(updatedDoc);
        }