Пример #1
0
 private ClassDeclarationSyntax AddBaseListTypes(ClassDeclarationSyntax classDeclaration)
 {
     if (classTemplate.HasBase)
     {
         return(classDeclaration.AddBaseListTypes(
                    SyntaxFactory.SimpleBaseType(SyntaxFactory.ParseTypeName(classTemplate.BaseClassName)),
                    SyntaxFactory.SimpleBaseType(SyntaxFactory.ParseTypeName(classTemplate.InterfaceName))));
     }
     else
     {
         return(classDeclaration.AddBaseListTypes(SyntaxFactory.SimpleBaseType(SyntaxFactory.ParseTypeName(classTemplate.InterfaceName))));
     }
 }
Пример #2
0
        public override SyntaxNode VisitClassDeclaration(ClassDeclarationSyntax node)
        {
            var attributeRemover = new AttributeRemover(node.AttributeLists, "TestFixture");

            if (attributeRemover.IsHavingAttribute)
            {
                if (!node.Modifiers.Any(m => m.IsKind(SyntaxKind.PublicKeyword)))
                {
                    var publicKeyword = SyntaxFactory.Token(SyntaxKind.PublicKeyword)
                                        .WithTrailingTrivia(SyntaxTriviaList.Create(SyntaxFactory.Space));
                    node = node.WithModifiers(node.Modifiers.Add(publicKeyword));
                }

                node = node.WithAttributeLists(attributeRemover.Remove());
            }

            if (node.DescendantNodes().Any(n => n is MethodDeclarationSyntax m &&
                                           m.AttributeLists.Contains("TearDown")))
            {
                node = node.AddBaseListTypes(
                    SyntaxFactory.SimpleBaseType(
                        SyntaxFactory.IdentifierName("IDisposable")).WithoutTrivia());
                node = node.WithIdentifier(node.Identifier.WithoutTrivia());
            }

            return(base.VisitClassDeclaration(node));
        }
        public CSharpSyntaxNode Convert(ClassDeclaration node)
        {
            ClassDeclarationSyntax csClass = SyntaxFactory
                                             .ClassDeclaration(node.Name.Text)
                                             .AddModifiers(node.Modifiers.ToCsNodes <SyntaxToken>())
                                             .AddMembers(node.Members.ToCsNodes <MemberDeclarationSyntax>());


            foreach (TypeParameter typeParameter in node.TypeParameters)
            {
                csClass = csClass.AddTypeParameterListParameters(typeParameter.ToCsNode <TypeParameterSyntax>());
                if (typeParameter.Constraint != null)
                {
                    csClass = csClass.AddConstraintClauses(SyntaxFactory
                                                           .TypeParameterConstraintClause(typeParameter.Name.Text)
                                                           .AddConstraints(SyntaxFactory.TypeConstraint(typeParameter.Constraint.ToCsNode <TypeSyntax>()))
                                                           );
                }
            }

            List <Node> baseTypes = node.GetBaseTypes(this.Context.Config.PreferTypeScriptType);

            if (baseTypes.Count > 0)
            {
                csClass = csClass.AddBaseListTypes(baseTypes.ToCsNodes <BaseTypeSyntax>());
            }
            if (node.JsDoc.Count > 0)
            {
                csClass = csClass.WithLeadingTrivia(SyntaxFactory.Trivia(node.JsDoc[0].ToCsNode <DocumentationCommentTriviaSyntax>()));
            }

            return(csClass);
        }
Пример #4
0
        private ClassDeclarationSyntax AppendListProxy(GList list, ClassDeclarationSyntax cl)
        {
            var itemType       = list.ItemType;
            var serverItemType = ServerName(itemType);

            cl = cl.AddBaseListTypes(SimpleBaseType(
                                         ParseTypeName("ServerListProxyHelper<" + itemType + ", " + serverItemType + ">.IRegisterForSerialization")),
                                     SimpleBaseType(ParseTypeName("IList<" + itemType + ">"))
                                     );
            var code = ListProxyTemplate.Replace("ListTypeName", list.Name)
                       .Replace("ItemTypeName", itemType);

            var parsed      = ParseCompilationUnit(code);
            var parsedClass = (ClassDeclarationSyntax)parsed.Members.First();

            cl = cl.AddMembers(parsedClass.Members.ToArray());

            var defs = cl.Members.OfType <MethodDeclarationSyntax>().First(m => m.Identifier.Text == "InitializeDefaults");

            cl = cl.ReplaceNode(defs.Body, defs.Body.AddStatements(

                                    ParseStatement($"_list = new ServerListProxyHelper<{itemType}, {serverItemType}>(this);")));

            return(cl);
        }
 public static ClassDeclarationSyntax Inherits(this ClassDeclarationSyntax @class, params string[] bases)
 {
     foreach (var @base in bases)
     {
         @class = @class.AddBaseListTypes(SyntaxFactory.SimpleBaseType(SyntaxFactory.ParseTypeName(@base)));
     }
     return(@class);
 }
Пример #6
0
            public override SyntaxNode VisitClassDeclaration(ClassDeclarationSyntax node)
            {
                node = (ClassDeclarationSyntax)base.VisitClassDeclaration(node);

                if (!generator.GetBaseAndInterfaceTypes(node).Any(x =>
                                                                  x.ToString() == nameof(IStunt) ||
                                                                  x.ToString() == typeof(IStunt).FullName))
                {
                    // Only add the base type if it isn't already there
                    node = node.AddBaseListTypes(SimpleBaseType(IdentifierName(nameof(IStunt))));
                }

                if (!generator.GetMembers(node).Any(x => generator.GetName(x) == nameof(IStunt.Behaviors)))
                {
                    node = (ClassDeclarationSyntax)generator.InsertMembers(node, 0,
                                                                           PropertyDeclaration(
                                                                               GenericName(
                                                                                   Identifier("ObservableCollection"),
                                                                                   TypeArgumentList(SingletonSeparatedList <TypeSyntax>(IdentifierName(nameof(IStuntBehavior))))),
                                                                               Identifier(nameof(IStunt.Behaviors)))
                                                                           .WithExplicitInterfaceSpecifier(ExplicitInterfaceSpecifier(IdentifierName(nameof(IStunt))))
                                                                           .WithExpressionBody(ArrowExpressionClause(
                                                                                                   MemberAccessExpression(
                                                                                                       SyntaxKind.SimpleMemberAccessExpression,
                                                                                                       IdentifierName("pipeline"),
                                                                                                       IdentifierName("Behaviors"))))
                                                                           .WithSemicolonToken(Token(SyntaxKind.SemicolonToken))
                                                                           .NormalizeWhitespace()
                                                                           .WithTrailingTrivia(CarriageReturnLineFeed, CarriageReturnLineFeed)
                                                                           );
                }

                if (!generator.GetMembers(node).Any(x => generator.GetName(x) == "pipeline"))
                {
                    node = (ClassDeclarationSyntax)generator.InsertMembers(node, 0,
                                                                           FieldDeclaration(
                                                                               VariableDeclaration(IdentifierName(Identifier(nameof(BehaviorPipeline))))
                                                                               .WithVariables(
                                                                                   SingletonSeparatedList(
                                                                                       VariableDeclarator(Identifier("pipeline"))
                                                                                       .WithInitializer(
                                                                                           EqualsValueClause(
                                                                                               ObjectCreationExpression(IdentifierName(nameof(BehaviorPipeline)))
                                                                                               .WithArgumentList(ArgumentList())))))
                                                                               .NormalizeWhitespace()
                                                                               ).WithModifiers(TokenList(Token(SyntaxKind.ReadOnlyKeyword))));
                }

                return(node);
            }
Пример #7
0
        public override SyntaxNode VisitClassDeclaration(ClassDeclarationSyntax node)
        {
            var type = node.ChildNodes().OfType <BaseListSyntax>().FirstOrDefault();

            var symbol = _model.GetDeclaredSymbol(node);

            if (type == null)
            {
                node = node.AddBaseListTypes(SyntaxFactory.SimpleBaseType
                                             (

                                                 SyntaxFactory.QualifiedName
                                                 (
                                                     SyntaxFactory.IdentifierName("System"),
                                                     SyntaxFactory.IdentifierName("Object").WithTrailingTrivia(SyntaxFactory.EndOfLine(Environment.NewLine))
                                                 )
                                             ));
                var eol = node.ChildTokens().OfType <SyntaxToken>().ElementAt(1);
                var ws  = eol.ReplaceTrivia(eol.TrailingTrivia.Last(), SyntaxFactory.SyntaxTrivia(SyntaxKind.WhitespaceTrivia, " "));
                node = node.ReplaceToken(eol, ws);
                var colon   = node.BaseList.ChildTokens().OfType <SyntaxToken>().FirstOrDefault();
                var colonws = colon.WithTrailingTrivia(SyntaxFactory.SyntaxTrivia(SyntaxKind.WhitespaceTrivia, " "));
                node = node.ReplaceToken(colon, colonws);
            }
            else if (symbol.BaseType.Name == "Object" && (symbol.BaseType.ToString() != "Object" && symbol.BaseType.ToString() != "System.Object"))
            {
                var blist = node.BaseList.Types.Insert(0, SyntaxFactory.SimpleBaseType(
                                                           SyntaxFactory.QualifiedName
                                                           (
                                                               SyntaxFactory.IdentifierName("System"),
                                                               SyntaxFactory.IdentifierName("Object")
                                                           )).WithTrailingTrivia(SyntaxFactory.Whitespace(" ")));
                node = node.ReplaceNode(node.BaseList, SyntaxFactory.BaseList(blist));
                SyntaxToken comma = node.BaseList.ChildTokens().OfType <SyntaxToken>().FirstOrDefault();
                foreach (SyntaxToken token in node.BaseList.ChildTokens().OfType <SyntaxToken>())
                {
                    if (token.ValueText == ",")
                    {
                        comma = token;
                    }
                }
                var ncomma = comma.WithTrailingTrivia(SyntaxFactory.Whitespace(" "));
                node = node.ReplaceToken(comma, ncomma);
                var colon   = node.BaseList.ChildTokens().OfType <SyntaxToken>().FirstOrDefault();
                var colonws = colon.WithTrailingTrivia(SyntaxFactory.SyntaxTrivia(SyntaxKind.WhitespaceTrivia, " "));
                node = node.ReplaceToken(colon, colonws);
            }

            return(base.VisitClassDeclaration(node));
        }
        public IWithInheritance WithInheritance(List <string> inheritanceList)
        {
            if (inheritanceList == null)
            {
                return(this);
            }

            foreach (var obj in inheritanceList)
            {
                _class = _class.AddBaseListTypes(
                    SyntaxFactory.SimpleBaseType(SyntaxFactory.ParseTypeName(obj)));
            }

            return(this);
        }
        private async Task <Document> AddMissingHandler(Document document, ClassDeclarationSyntax classExpr, string messageType, CancellationToken cancellationToken)
        {
            if (classExpr.BaseList == null)
            {
                return(document);
            }
            var genericBases = classExpr.BaseList.ChildNodes()
                               .Where(x => x is SimpleBaseTypeSyntax)
                               .Select(x => x.ChildNodes().FirstOrDefault(g => g is GenericNameSyntax))
                               .Where(x => x != null)
                               .Cast <GenericNameSyntax>();

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

            SyntaxTriviaList     trailingWhiteSpace = new SyntaxTriviaList().Add(SyntaxFactory.EndOfLine(Environment.NewLine));
            SimpleBaseTypeSyntax newInterface       = null;

            if (genericBases.Any(x => x.Identifier.ValueText.Equals(MachineClassName)))
            {
                newInterface = SyntaxFactory.SimpleBaseType(SyntaxFactory.ParseTypeName($"IMachineMessageHandler<{messageType}>")).WithTrailingTrivia(trailingWhiteSpace);
            }
            else if (genericBases.Any(x => x.Identifier.ValueText.Equals(SagaClassName)))
            {
                newInterface = SyntaxFactory.SimpleBaseType(SyntaxFactory.ParseTypeName($"IMessageHandler<{messageType}>")).WithTrailingTrivia(trailingWhiteSpace);
            }
            else
            {
                return(document);
            }

            ClassDeclarationSyntax newClassExpr = classExpr.AddBaseListTypes(newInterface);

            var lastComma = newClassExpr.BaseList.DescendantTokens().LastOrDefault(x => x.IsKind(SyntaxKind.CommaToken));

            if (lastComma != null)
            {
                newClassExpr = newClassExpr.ReplaceToken(lastComma, lastComma.WithTrailingTrivia(trailingWhiteSpace));
            }

            var oldRoot = await document.GetSyntaxRootAsync(cancellationToken);

            var newRoot = oldRoot.ReplaceNode(classExpr, newClassExpr);

            return(document.WithSyntaxRoot(newRoot));
        }
 public static ClassDeclarationSyntax AddInheritanceGenericClass(this ClassDeclarationSyntax cls, string inheritanceType, string typeObject)
 {
     return(cls.AddBaseListTypes(
                SyntaxFactory.SimpleBaseType(
                    SyntaxFactory.GenericName(
                        SyntaxFactory.Identifier(inheritanceType),
                        SyntaxFactory.TypeArgumentList(
                            SyntaxFactory.Token(SyntaxKind.LessThanToken),
                            SyntaxFactory.SeparatedList(new[]
     {
         SyntaxFactory.ParseTypeName(typeObject)
     }),
                            SyntaxFactory.Token(SyntaxKind.GreaterThanToken)
                            )
                        )
                    )
                ));
 }
Пример #11
0
        public static string Generate(string className)
        {
            var syntaxFactory = SyntaxFactory.CompilationUnit();

            syntaxFactory = syntaxFactory.AddUsings(SyntaxFactory.UsingDirective(SyntaxFactory.ParseName("System")),
                                                    SyntaxFactory.UsingDirective(SyntaxFactory.ParseName("UnityEngine")),
                                                    SyntaxFactory.UsingDirective(SyntaxFactory.ParseName("UnityEditor")));

            //var @namespace = SyntaxFactory.NamespaceDeclaration(SyntaxFactory.ParseName("Events.CustomData"));

            ClassDeclarationSyntax dataClass = SyntaxFactory.ClassDeclaration(className);

            dataClass = dataClass.AddModifiers(SyntaxFactory.Token(SyntaxKind.PublicKeyword));
            dataClass = dataClass.AddBaseListTypes(SyntaxFactory.SimpleBaseType(SyntaxFactory.ParseTypeName("BaseCustomData")));

            var attributes = new SeparatedSyntaxList <AttributeSyntax>();

            attributes = attributes.Add(SyntaxFactory.Attribute(SyntaxFactory.ParseName("Serializable")));

            dataClass = dataClass.AddAttributeLists(SyntaxFactory.AttributeList(attributes));

            var variableDeclaration = SyntaxFactory.VariableDeclaration(SyntaxFactory.ParseTypeName("Vector3"))
                                      .AddVariables(SyntaxFactory.VariableDeclarator("testVector"));

            var fieldDeclaration = SyntaxFactory.FieldDeclaration(variableDeclaration)
                                   .AddModifiers(SyntaxFactory.Token(SyntaxKind.PublicKeyword));

            var constructorDeclaration = SyntaxFactory.ConstructorDeclaration(className)
                                         .WithBody(SyntaxFactory.Block());

            dataClass = dataClass.AddMembers(fieldDeclaration, constructorDeclaration);

            //@namespace = @namespace.AddMembers(dataClass);

            syntaxFactory = syntaxFactory.AddMembers(dataClass);

            var code = syntaxFactory
                       .NormalizeWhitespace()
                       .ToFullString();

            return(code);
        }
        internal static ClassDeclarationSyntax WithINotifyPropertyChangedInterface(this ClassDeclarationSyntax classDeclaration)
        {
            if (!(classDeclaration.BaseList?.Types.Any(x =>
            {
                var t = x.Type.ToString();
                return(t == "INotifyPropertyChanged" || t == "System.ComponentModel.INotifyPropertyChanged");
            }) ?? false))
            {
                var inpc = SyntaxFactory.ParseTypeName("System.ComponentModel.INotifyPropertyChanged")
                           .WithAdditionalAnnotations(Simplifier.Annotation)
                           .WithAdditionalAnnotations(Formatter.Annotation);

                var decl = classDeclaration.AddBaseListTypes(SyntaxFactory.SimpleBaseType(inpc));
                return(decl.WithIdentifier(decl.Identifier.WithTrailingTrivia()));
            }
            else
            {
                return(classDeclaration);
            }
        }
Пример #13
0
        public void AddBaseClass(ITypeSyntaxBuilder builder, Type classType)
        {
            if (!classType.IsClass && !classType.IsInterface)
            {
                throw new InvalidOperationException(classType.ToString() + " is not a valid class type or interface.");
            }

            lock (syncObj)
            {
                //Check if there is already a baseclass
                if (hasBaseclass && classType.IsClass)
                {
                    throw new InvalidOperationException("A type may only derive from a single base class.");
                }
                else
                {
                    rosylnClassUnit = rosylnClassUnit.AddBaseListTypes(SyntaxFactory.SimpleBaseType(builder.GenerateFrom(classType)));

                    hasBaseclass = hasBaseclass || classType.IsClass;
                }
            }
        }
Пример #14
0
        private static ClassDeclarationSyntax CreateClassDeclarationSyntax(string className, string[] baseClasses, ClassType classType, List <ConstraintData> constraints)
        {
            ClassDeclarationSyntax syntax = SyntaxFactory.ClassDeclaration(className);

            List <SyntaxToken> tokens = new List <SyntaxToken>();

            tokens.Add(SyntaxFactory.Token(SyntaxKind.PublicKeyword));

            switch (classType)
            {
            case ClassType.Standard: break;

            case ClassType.Partial: tokens.Add(SyntaxFactory.Token(SyntaxKind.PartialKeyword)); break;

            case ClassType.Static: tokens.Add(SyntaxFactory.Token(SyntaxKind.StaticKeyword)); break;

            case ClassType.StaticPartial:
                tokens.Add(SyntaxFactory.Token(SyntaxKind.StaticKeyword));
                tokens.Add(SyntaxFactory.Token(SyntaxKind.PartialKeyword));
                break;
            }

            // Add the public modifier: (public class Order)
            syntax = syntax.AddModifiers(tokens.ToArray());

            // Inherit BaseEntity<T> and implement IHaveIdentity: (public class Order : BaseEntity<T>, IHaveIdentity)
            for (int i = 0; i < baseClasses.Length; i++)
            {
                syntax = syntax.AddBaseListTypes(SyntaxFactory.SimpleBaseType(SyntaxFactory.ParseTypeName(baseClasses[i])));
            }

            for (int i = 0; i < constraints.Count; i++)
            {
                syntax = syntax.AddConstraintClauses(CodeGenerationUtility.CreateConstraintClause(constraints[i]));
            }

            return(syntax);
        }
 public static ClassDeclarationSyntax AddInheritanceClass(this ClassDeclarationSyntax cls, string inheritanceType)
 {
     return(cls.AddBaseListTypes(SyntaxFactory.SimpleBaseType(SyntaxFactory.ParseTypeName(inheritanceType))));
 }
Пример #16
0
            public override SyntaxNode VisitClassDeclaration(ClassDeclarationSyntax node)
            {
                node = (ClassDeclarationSyntax)base.VisitClassDeclaration(node);

                if (!generator.GetBaseAndInterfaceTypes(node).Any(x =>
                                                                  x.ToString() == nameof(IMocked) ||
                                                                  x.ToString() == typeof(IMocked).FullName))
                {
                    // Only add the base type if it isn't already there
                    node = node.AddBaseListTypes(SimpleBaseType(IdentifierName(nameof(IMocked))));
                }

                if (!generator.GetMembers(node).Any(x => generator.GetName(x) == "mock"))
                {
                    var field = FieldDeclaration(
                        VariableDeclaration(IdentifierName(Identifier(nameof(IMock))))
                        .WithVariables(SingletonSeparatedList(VariableDeclarator(Identifier("mock"))))
                        );

                    // Try to locate the mock field following the pipeline field
                    var pipeline = generator.GetMembers(node).FirstOrDefault(x => generator.GetName(x) == "pipeline");
                    if (pipeline != null)
                    {
                        node = (ClassDeclarationSyntax)generator.InsertNodesAfter(node, pipeline,
                                                                                  new[] { field.WithLeadingTrivia(pipeline.GetLeadingTrivia()) });
                    }
                    else
                    {
                        node = (ClassDeclarationSyntax)generator.InsertMembers(node, 0, field
                                                                               .WithLeadingTrivia(ElasticTab, ElasticTab)
                                                                               .NormalizeWhitespace()
                                                                               .WithTrailingTrivia(CarriageReturnLineFeed, CarriageReturnLineFeed));
                    }
                }

                if (!generator.GetMembers(node).Any(x => generator.GetName(x) == nameof(IMocked.Mock)))
                {
                    var property = PropertyDeclaration(IdentifierName(nameof(IMock)), nameof(IMocked.Mock))
                                   // Make IMocked properties explicit.
                                   .WithExplicitInterfaceSpecifier(
                        ExplicitInterfaceSpecifier(
                            IdentifierName(nameof(IMocked))))
                                   .WithModifiers(TokenList())
                                   // => LazyInitializer.EnsureInitialized(ref mock, () => new MockInfo(pipeline.Behaviors));
                                   .WithExpressionBody(ArrowExpressionClause(
                                                           InvocationExpression(
                                                               MemberAccessExpression(
                                                                   SyntaxKind.SimpleMemberAccessExpression,
                                                                   IdentifierName(nameof(LazyInitializer)),
                                                                   IdentifierName(nameof(LazyInitializer.EnsureInitialized))),
                                                               ArgumentList(SeparatedList(new ArgumentSyntax[]
                    {
                        Argument(RefExpression(IdentifierName("mock"))),
                        Argument(ParenthesizedLambdaExpression(
                                     ObjectCreationExpression(
                                         IdentifierName(nameof(DefaultMock)))
                                     .WithArgumentList(ArgumentList(SingletonSeparatedList(Argument(
                                                                                               ThisExpression()
                                                                                               ))))
                                     ))
                    }))
                                                               )
                                                           ))
                                   .WithSemicolonToken(Token(SyntaxKind.SemicolonToken));

                    // Try to locate the Mock property following the Behaviors property
                    var behaviors = generator.GetMembers(node).FirstOrDefault(x => generator.GetName(x) == nameof(IStunt.Behaviors));
                    if (behaviors != null)
                    {
                        node = (ClassDeclarationSyntax)generator.InsertNodesAfter(node, behaviors, new[] { property });
                    }
                    else
                    {
                        node = (ClassDeclarationSyntax)generator.AddMembers(node, property);
                    }
                }

                return(node);
            }
Пример #17
0
 public static ClassDeclarationSyntax BaseFrom(this ClassDeclarationSyntax source, params string[] bases)
 {
     return(source.AddBaseListTypes(bases.Select(str => SimpleBaseType(ParseTypeName(str))).ToArray()));
 }
Пример #18
0
 public static ClassDeclarationSyntax AddBaseType(this ClassDeclarationSyntax classDeclaration, string baseTypeName)
 {
     return(classDeclaration.AddBaseListTypes(SyntaxFactory.SimpleBaseType(SyntaxFactory.IdentifierName(baseTypeName))));
 }
Пример #19
0
 static ClassDeclarationSyntax ExtendAndImplementInterface(ClassDeclarationSyntax syntax, ITypeSymbol symbolToExtendFrom)
 {
     return(syntax
            .AddBaseListTypes(SimpleBaseType(ParseName(symbolToExtendFrom.Name))));
 }
 public static ClassDeclarationSyntax ImplementEquatable(this ClassDeclarationSyntax classDeclaration, GeneratedPropertyInfo[] properties)
 => classDeclaration
 .AddBaseListTypes(SimpleBaseType(ParseTypeName($"System.IEquatable<{classDeclaration.Identifier}>")))
 .AddMembers(BuildGenericEqualsMethod(classDeclaration.Identifier, properties));
Пример #21
0
        public void TestAddDocument()
        {
            // Create CompilationUnitSyntax
            CompilationUnitSyntax syntaxFactory = SyntaxFactory.CompilationUnit();

            // Add System using statement: (using System)
            syntaxFactory = syntaxFactory.AddUsings(SyntaxFactory.UsingDirective(SyntaxFactory.ParseName("System")));

            // Create a namespace: (namespace CodeGenerationSample)
            var @namespace = SyntaxFactory.NamespaceDeclaration(SyntaxFactory.ParseName("CodeGenerationSample")).NormalizeWhitespace();

            //  Create a class: (class Order)
            ClassDeclarationSyntax classDeclaration = SyntaxFactory.ClassDeclaration("Order");

            // Add the public modifier: (public class Order)
            classDeclaration = classDeclaration.AddModifiers(SyntaxFactory.Token(SyntaxKind.PublicKeyword));

            // Inherit BaseEntity<T> and implement IHaveIdentity: (public class Order : BaseEntity<T>, IHaveIdentity)
            classDeclaration = classDeclaration.AddBaseListTypes(
                SyntaxFactory.SimpleBaseType(SyntaxFactory.ParseTypeName("BaseEntity<Order>")),
                SyntaxFactory.SimpleBaseType(SyntaxFactory.ParseTypeName("IHaveIdentity")));

            // Create a string variable: (bool canceled;)
            var variableDeclaration = SyntaxFactory.VariableDeclaration(SyntaxFactory.ParseTypeName("bool"))
                                      .AddVariables(SyntaxFactory.VariableDeclarator("canceled"));

            // Create a field declaration: (private bool canceled;)
            var fieldDeclaration = SyntaxFactory.FieldDeclaration(variableDeclaration)
                                   .AddModifiers(SyntaxFactory.Token(SyntaxKind.PrivateKeyword));

            // Create a Property: (public int Quantity { get; set; })
            var propertyDeclaration = SyntaxFactory.PropertyDeclaration(SyntaxFactory.ParseTypeName("int"), "Quantity")
                                      .AddModifiers(SyntaxFactory.Token(SyntaxKind.PublicKeyword))
                                      .AddAccessorListAccessors(
                SyntaxFactory.AccessorDeclaration(SyntaxKind.GetAccessorDeclaration).WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.SemicolonToken)),
                SyntaxFactory.AccessorDeclaration(SyntaxKind.SetAccessorDeclaration).WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.SemicolonToken)));

            // Create a stament with the body of a method.
            var syntax = SyntaxFactory.ParseStatement("canceled = true;");

            // Create a method
            var methodDeclaration = SyntaxFactory.MethodDeclaration(SyntaxFactory.ParseTypeName("void"), "MarkAsCanceled")
                                    .AddModifiers(SyntaxFactory.Token(SyntaxKind.PublicKeyword))
                                    .WithBody(SyntaxFactory.Block(syntax));

            // Add the field, the property and method to the class.
            classDeclaration = classDeclaration.AddMembers(fieldDeclaration, propertyDeclaration, methodDeclaration);

            // Add the class to the namespace.
            @namespace = @namespace.AddMembers(classDeclaration);

            // Add the namespace to the compilation unit.
            syntaxFactory = syntaxFactory.AddMembers(@namespace);

            // Normalize and get code as string.
            var code = syntaxFactory
                       .NormalizeWhitespace()
                       .ToFullString();

            // Output new code to the console.
            Console.WriteLine(code);
        }
Пример #22
0
 public static ClassDeclarationSyntax WithBaseTypes(this ClassDeclarationSyntax node, params string[] types)
 {
     return(node.AddBaseListTypes(types.Select(x => SimpleBaseType(ParseTypeName(x))).Cast <BaseTypeSyntax>().ToArray()));
 }
Пример #23
0
            public override SyntaxNode?VisitClassDeclaration(ClassDeclarationSyntax node)
            {
                node = (ClassDeclarationSyntax)base.VisitClassDeclaration(node) !;

                if (node.BaseList != null && !node.BaseList.Types.Any(x =>
                                                                      x.ToString() == nameof(IAvatar) ||
                                                                      x.ToString() == typeof(IAvatar).FullName))
                {
                    // Only add the base type if it isn't already there
                    node = node.AddBaseListTypes(SimpleBaseType(IdentifierName(nameof(IAvatar))));
                }

                if (!node.Members.OfType <PropertyDeclarationSyntax>().Any(prop => prop.Identifier.ToString() == nameof(IAvatar.Behaviors)))
                {
                    var behaviors = PropertyDeclaration(
                        GenericName(
                            "IList",
                            IdentifierName(nameof(IAvatarBehavior))),
                        Identifier(nameof(IAvatar.Behaviors)))
                                    .WithExplicitInterfaceSpecifier(
                        ExplicitInterfaceSpecifier(
                            IdentifierName(nameof(IAvatar))))
                                    .WithExpressionBody(
                        ArrowExpressionClause(
                            MemberAccessExpression(
                                IdentifierName("pipeline"),
                                IdentifierName("Behaviors"))))
                                    .WithSemicolonToken(Token(SyntaxKind.SemicolonToken))
                                    .NormalizeWhitespace()
                                    .WithTrailingTrivia(CarriageReturnLineFeed, CarriageReturnLineFeed);

                    if (node.Members.Count > 0)
                    {
                        node = node.InsertNodesAfter(node.Members.First(), new[] { behaviors });
                    }
                    else
                    {
                        node = node.AddMembers(behaviors);
                    }
                }

                if (!node.Members.OfType <FieldDeclarationSyntax>().Any(x => x.Declaration.Variables.Any(v => v.Identifier.ToString() == "pipeline")))
                {
                    node = node.InsertNodesBefore(node.Members.First(), new[]
                    {
                        FieldDeclaration(
                            VariableDeclaration(
                                "pipeline",
                                IdentifierName(nameof(BehaviorPipeline)),
                                InvocationExpression(
                                    MemberAccessExpression(
                                        SyntaxKind.SimpleMemberAccessExpression,
                                        MemberAccessExpression(
                                            nameof(BehaviorPipelineFactory),
                                            nameof(BehaviorPipelineFactory.Default)),
                                        GenericName(
                                            nameof(IBehaviorPipelineFactory.CreatePipeline),
                                            IdentifierName(node.Identifier.ValueText)))))
                            .NormalizeWhitespace()
                            ).WithModifiers(TokenList(Token(SyntaxKind.ReadOnlyKeyword)))
                    });
                }

                return(node);
            }
Пример #24
0
 public static ClassDeclarationSyntax WithBaseType(this ClassDeclarationSyntax cl, string bt)
 {
     return(cl.AddBaseListTypes(SimpleBaseType(SyntaxFactory.ParseTypeName(bt))));
 }
Пример #25
0
 public static ClassDeclarationSyntax AddProxiedTypes(this ClassDeclarationSyntax proxyClass, params INamedTypeSymbol[] types) =>
 proxyClass.AddBaseListTypes(types.OrderBy(t => t.Name).Select(i => SimpleBaseType(ToSyntax(i))).ToArray());
Пример #26
0
 public void AddBaseType(TypeSyntax baseType) =>
 _declaration = _declaration.AddBaseListTypes(SimpleBaseType(baseType));