예제 #1
0
        public static void TransformSyntax()
        {
            // We start our syntax generation by finding the root of our syntax tree.
            // We will use this later to replace the existing class declaration with a new one.
            var rootNode = SyntaxTree.GetRoot();

            // Here we are creating a new AttributeListSyntax by using a helper class.
            // This helper encapsulates the attribute list syntax generation code for reuse.
            // Generated using https://roslynquoter.azurewebsites.net/
            var attrbuteList = AttributeUsageAnnotationGenerator.GenerateSyntax(AttributeTargets.Class);

            // We mutate our existing class declaration by adding the new attribute list syntax.
            var newSyntax = ClassDeclarationSyntax.AddAttributeLists(attrbuteList);

            // Next, we replace the old class declaration in the current syntax root node.
            // This creates a new, mutated root node that we will need to apply back onto our document.
            var mutatedRoot = rootNode.ReplaceNode(ClassDeclarationSyntax, newSyntax);

            // Before we change the original document, we use the formatter to correct whitespace
            // and apply user specified formatting conventions.
            var formattedSyntax = Formatter.Format(mutatedRoot, Workspace);

            // Lastly, we apply the new syntax node onto the original document.
            Document   = Document.WithSyntaxRoot(formattedSyntax);
            SyntaxTree = Document.GetSyntaxTreeAsync().Result;
        }
        public override SyntaxNode VisitClassDeclaration(ClassDeclarationSyntax node)
        {
            var commented = node.DescendantTrivia()
                            .Where(c => c.Kind() == SyntaxKind.SingleLineCommentTrivia)
                            .FirstOrDefault(c => c.ToString().Contains(attributeName));

            if (commented != null)
            {
                node = node.ReplaceTrivia(commented, SyntaxTrivia(SyntaxKind.WhitespaceTrivia, ""));
            }

            var attribute = node.AttributeLists.SelectMany(c => c.Attributes)
                            .FirstOrDefault(a => (a.Name as IdentifierNameSyntax)
                                            .Identifier.Text.StartsWith(attributeName));

            if (node.AttributeLists.Any(al => al.Contains(attribute)))
            {
                return(node);
            }

            var newAttrib =
                AttributeList(
                    SingletonSeparatedList(
                        Attribute(
                            IdentifierName(attributeName)
                            )
                        )
                    );

            return(node.AddAttributeLists(newAttrib).NormalizeWhitespace());
        }
        private async Task <Document> FixAsync(Document document, ClassDeclarationSyntax classDecl,
                                               string requiredAttributes, CancellationToken cancellationToken)
        {
            var attributes = new List <AttributeSyntax>();
            var namespaces = new List <string>();

            foreach (var attribute in requiredAttributes.Split(','))
            {
                var tempSplit = attribute.Split('.');
                namespaces.Add(string.Join(".", tempSplit.Take(tempSplit.Length - 1)));
                var @class = tempSplit.Last();
                @class = @class.Substring(0, @class.Length - 9); //cut out "Attribute" at the end
                attributes.Add(SyntaxFactory.Attribute(SyntaxFactory.ParseName(@class)));
            }

            var newClassDecl =
                classDecl.AddAttributeLists(SyntaxFactory.AttributeList(SyntaxFactory.SeparatedList(attributes)));

            var root = (CompilationUnitSyntax)await document.GetSyntaxRootAsync(cancellationToken);

            root = root.ReplaceNode(classDecl, newClassDecl);

            foreach (var ns in namespaces)
            {
                if (root.Usings.Any(u => u.Name.ToString() == ns))
                {
                    continue;
                }
                root = root.AddUsings(SyntaxFactory.UsingDirective(SyntaxFactory.ParseName(ns)));
            }
            return(document.WithSyntaxRoot(root));
        }
예제 #4
0
        public static async Task <Document> RefactorAsync(
            Document document,
            ClassDeclarationSyntax classDeclaration,
            CancellationToken cancellationToken)
        {
            SemanticModel semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);

            INamedTypeSymbol symbol = semanticModel.GetDeclaredSymbol(classDeclaration, cancellationToken);

            var attributeName = (NameSyntax)semanticModel
                                .GetTypeByMetadataName(MetadataNames.System_AttributeUsageAttribute)
                                .ToMinimalTypeSyntax(semanticModel, classDeclaration.SpanStart);

            TypeSyntax attributeTargetsType = semanticModel
                                              .GetTypeByMetadataName(MetadataNames.System_AttributeTargets)
                                              .ToMinimalTypeSyntax(semanticModel, classDeclaration.SpanStart);

            AttributeSyntax attribute = Attribute(
                attributeName,
                AttributeArgumentList(
                    AttributeArgument(SimpleMemberAccessExpression(attributeTargetsType, IdentifierName(Identifier("All").WithRenameAnnotation()))),
                    AttributeArgument(NameEquals(IdentifierName("AllowMultiple")), FalseLiteralExpression())));

            ClassDeclarationSyntax newNode = classDeclaration.AddAttributeLists(AttributeList(attribute));

            return(await document.ReplaceNodeAsync(classDeclaration, newNode, cancellationToken).ConfigureAwait(false));
        }
예제 #5
0
        public override SyntaxNode VisitClassDeclaration(ClassDeclarationSyntax node)
        {
            var identifierToken = node.Identifier.ToString();

            var leadingTrivia = node.GetLeadingTrivia();

            var obsoleteExpression =

                SyntaxFactory.AttributeList
                (
                    SyntaxFactory.SingletonSeparatedList <AttributeSyntax>
                    (
                        SyntaxFactory.Attribute
                        (
                            SyntaxFactory.IdentifierName("Obsolete")
                        )
                        .WithArgumentList
                        (
                            SyntaxFactory.AttributeArgumentList
                            (
                                SyntaxFactory.SingletonSeparatedList <AttributeArgumentSyntax>
                                (
                                    SyntaxFactory.AttributeArgument
                                    (
                                        SyntaxFactory.LiteralExpression
                                        (
                                            SyntaxKind.StringLiteralExpression,
                                            SyntaxFactory.Literal("Use " + identifierToken[0].ToString().ToUpper() + identifierToken.Substring(1) + " instead")
                                        )
                                    )
                                )
                            )
                        )
                    )
                ).WithLeadingTrivia(leadingTrivia);

            //char.IsLower(identifierToken[0])
            if (identifierToken[0] >= 'a' && identifierToken[0] <= 'z')
            {
                //identifierToken[0].ToString().ToUpper();


                /*  var obsoleteExpression =
                 *    SyntaxFactory.AttributeList(
                 *        SyntaxFactory.Attribute(
                 *            SyntaxFactory.IdentifierName("Obsolete").WithLeadingTrivia(leadingTrivia)),
                 *            SyntaxFactory.AttributeArgumentList(
                 *                SyntaxFactory.SingletonSeparatedList<AttributeArgumentSyntax>(
                 *                    SyntaxFactory.AttributeArgument(
                 *                        SyntaxFactory.LiteralExpression(SyntaxKind.StringLiteralExpression, SyntaxFactory.Literal(node.Identifier)
                 *
                 *
                 * ))))); */

                node = node.AddAttributeLists(obsoleteExpression);
            }

            return(base.VisitClassDeclaration(node));
        }
        private static SyntaxNode AddAttribute(SyntaxNode root, ClassDeclarationSyntax classNode, string name)
        {
            var attribute     = SyntaxFactory.Attribute(SyntaxFactory.ParseName(name));
            var attributeList = SyntaxFactory.AttributeList(SyntaxFactory.SeparatedList <AttributeSyntax>().Add(attribute));
            var newClassNode  = classNode.AddAttributeLists(attributeList);

            return(root.ReplaceNode(classNode, newClassNode));
        }
예제 #7
0
 public static ClassDeclarationSyntax AddDataContractAttribute(this ClassDeclarationSyntax classDeclaration)
 {
     return(classDeclaration.AddAttributeLists(new[]
     {
         SyntaxFactory.AttributeList(SyntaxFactory.SingletonSeparatedList(
                                         SyntaxFactory.Attribute(SyntaxFactory.IdentifierName(Constants.Attribute.DataContract))))
     }));
 }
예제 #8
0
        private static void FindMethod(SyntaxNode namespac, CompilationUnitSyntax root, ref List <Tests> Tests)
        {
            var classes = namespac.ChildNodes().Where(@class => @class is ClassDeclarationSyntax);

            foreach (ClassDeclarationSyntax @class in classes)
            {
                if (!(@class.Modifiers.Any(SyntaxKind.AbstractKeyword)))
                {
                    var members = @class.Members;
                    var methods = members.Where(mem => mem is MethodDeclarationSyntax);
                    methods = methods.Where(method => method.Modifiers.Where(modifier => modifier.Kind() == SyntaxKind.PublicKeyword).Any());
                    if (methods.Count() > 0)
                    {
                        var usings        = root.Usings;
                        var syntaxFactory = SyntaxFactory.CompilationUnit();
                        syntaxFactory = syntaxFactory.AddUsings(usings.ToArray());
                        syntaxFactory = syntaxFactory.AddUsings(SyntaxFactory.UsingDirective(SyntaxFactory.ParseName("NUnit.Framework")));
                        syntaxFactory = syntaxFactory.AddUsings(SyntaxFactory.UsingDirective(SyntaxFactory.ParseName("Moq")));
                        syntaxFactory = syntaxFactory.AddUsings(SyntaxFactory.UsingDirective(SyntaxFactory.ParseName(GetFullNameSpace(@class))));
                        var namespaceName = SyntaxFactory.NamespaceDeclaration(SyntaxFactory.ParseName(GetFullNameSpace(@class) + ".Test"));


                        ClassDeclarationSyntax TestClass = SyntaxFactory.ClassDeclaration(@class.Identifier.Text + "Tests")
                                                           .WithModifiers(
                            SyntaxFactory.TokenList(
                                SyntaxFactory.Token(SyntaxKind.PublicKeyword)));
                        TestClass = TestClass.AddAttributeLists(SyntaxFactory.SingletonList <AttributeListSyntax>(
                                                                    SyntaxFactory.AttributeList(
                                                                        SyntaxFactory.SingletonSeparatedList <AttributeSyntax>(
                                                                            SyntaxFactory.Attribute(
                                                                                SyntaxFactory.IdentifierName("TestFixture"))))).ToArray());

                        TestClass = TestClass.AddMembers(SetUpGenerate(@class));

                        TestClass = TestClass.AddMembers(TestMethodsGenerate(@class));


                        namespaceName = namespaceName.AddMembers(TestClass);
                        syntaxFactory = syntaxFactory.AddMembers(namespaceName);
                        string fileName = GetFullNameSpace(@class) + "." + @class.Identifier.Text + ".Test.cs";
                        Tests.Add(new Tests(fileName, syntaxFactory.NormalizeWhitespace().ToFullString()));
                    }
                    foreach (MemberDeclarationSyntax member in members)
                    {
                        if (member is ClassDeclarationSyntax)
                        {
                            FindMethod(@class, root, ref Tests);
                        }
                    }
                }
            }
            var namespaces = namespac.ChildNodes().Where(@class => @class is NamespaceDeclarationSyntax);

            foreach (NamespaceDeclarationSyntax @namespace in namespaces)
            {
                FindMethod(@namespace, root, ref Tests);
            }
        }
예제 #9
0
        public override SyntaxNode VisitClassDeclaration(ClassDeclarationSyntax node)
        {
            var updated = !node.Ancestors().OfType <TypeDeclarationSyntax>().Any()
                ? node.AddAttributeLists(GetTypeDeclarationAttributes())
                          .WithModifiers(this.GetTypeDeclarationModifiers(node.Modifiers))
                : node;

            return(base.VisitClassDeclaration(updated));
        }
예제 #10
0
        public override SyntaxNode VisitClassDeclaration(ClassDeclarationSyntax node)
        {
            //// OF COURSE there must be a verification that there is no such attribute already.
            var changedClass = node.AddAttributeLists(
                SyntaxFactory.AttributeList(SyntaxFactory.SingletonSeparatedList <AttributeSyntax>(
                                                SyntaxFactory.Attribute(SyntaxFactory.IdentifierName("Serializable")))));

            return(base.VisitClassDeclaration(changedClass));
        }
        private ClassDeclarationSyntax AddAttribute(ClassDeclarationSyntax classDecl, string attributeName)
        {
            var newAttributes = SyntaxFactory.AttributeList(
                SyntaxFactory.SingletonSeparatedList(
                    SyntaxFactory.Attribute(SyntaxFactory.IdentifierName(attributeName))
                    )
                );

            classDecl = classDecl.AddAttributeLists(newAttributes);
            return(classDecl);
        }
예제 #12
0
        private void InitializeClassDeclaration()
        {
            _classDeclaration = SyntaxFactory.ClassDeclaration(_classInfo.ClassName + "UnitTests");
            _classDeclaration = _classDeclaration.AddModifiers(SyntaxFactory.Token(SyntaxKind.PublicKeyword));

            if (_testFramework.ClassAttribute.ShouldBeApplied)
            {
                _classDeclaration = _classDeclaration.AddAttributeLists(
                    SyntaxFactory.AttributeList(
                        SyntaxFactory.SingletonSeparatedList(
                            SyntaxFactory.Attribute(SyntaxFactory.IdentifierName(_testFramework.ClassAttribute.Value)))));
            }
        }
예제 #13
0
        public void AddParameterlessAttributeToClass <TAttributeType>() where TAttributeType : Attribute, new()
        {
            var attriList =
                SyntaxFactory.AttributeList(
                    SyntaxFactory.SeparatedList <AttributeSyntax>()
                    .Add(SyntaxFactory.Attribute(SyntaxFactory.IdentifierName(typeof(TAttributeType).FullName))));

            //add the attribute to the class
            lock (syncObj)
            {
                rosylnClassUnit = rosylnClassUnit
                                  .AddAttributeLists(attriList);
            }
        }
예제 #14
0
파일: Class.cs 프로젝트: tylike/Excess
        private ClassDeclarationSyntax addAttribute(ClassDeclarationSyntax @class, string attributeName, bool optional)
        {
            if (@class.AttributeLists.Any(attrList => attrList
                                          .Attributes
                                          .Any(attr => attr.Name.ToString() == attributeName)))
            {
                return(@class);
            }

            return(@class
                   .AddAttributeLists(CSharp.AttributeList(CSharp.SeparatedList(new[] { CSharp
                                                                                        .Attribute(CSharp
                                                                                                   .ParseName(attributeName), optional
                            ? Templates.GuidAttributeArgument(optional: true)
                            : Templates.GuidAttributeArgument(optional: false)) }))));
        }
예제 #15
0
        public static ClassDeclarationSyntax AddAttribute(this ClassDeclarationSyntax classSyntax, string attributeClassName, string arguments = null)
        {
            var attributeSyntax = SyntaxFactory.Attribute(SyntaxFactory.IdentifierName(attributeClassName));

            if (!string.IsNullOrEmpty(arguments))
            {
                attributeSyntax = attributeSyntax.WithArgumentList(SyntaxFactory.ParseAttributeArgumentList(arguments));
            }

            var newClassSyntax = classSyntax.AddAttributeLists(
                SyntaxFactory.AttributeList(
                    SyntaxFactory.SeparatedList(new[]
            {
                attributeSyntax
            })));

            return(newClassSyntax);
        }
        private async Task <Document> AddCakeAliasCategoryAsync(Document document, ClassDeclarationSyntax classDeclaration, CancellationToken cancellationToken)
        {
            var qualifiedName = BuildQualifiedName("Cake", "Core", "Annotations", "CakeAliasCategoryAttribute");

            var argument = SyntaxFactory.AttributeArgument(
                SyntaxFactory.LiteralExpression(
                    SyntaxKind.StringLiteralExpression,
                    SyntaxFactory.Literal("REPLACE_ME")));
            var newAttribute = SyntaxFactory.Attribute(qualifiedName)
                               .AddArgumentListArguments(argument);
            var newAttributeList = SyntaxFactory.AttributeList().AddAttributes(newAttribute).WithAdditionalAnnotations(Formatter.Annotation);
            var newDeclaration   = classDeclaration.AddAttributeLists(newAttributeList);

            var oldRoot = await document.GetSyntaxRootAsync(cancellationToken);

            var newRoot = oldRoot !.ReplaceNode(classDeclaration, newDeclaration);

            return(document.WithSyntaxRoot(newRoot));
        }
예제 #17
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);
        }
        private static Task <Document> UseAttributeUsageAttributeAsync(
            Document document,
            ClassDeclarationSyntax classDeclaration,
            CancellationToken cancellationToken)
        {
            AttributeSyntax attribute = Attribute(
                (NameSyntax)ParseTypeName("System.AttributeUsageAttribute").WithSimplifierAnnotation(),
                AttributeArgumentList(
                    AttributeArgument(
                        SimpleMemberAccessExpression(
                            ParseTypeName("System.AttributeTargets").WithSimplifierAnnotation(),
                            IdentifierName(Identifier("All").WithRenameAnnotation()))),
                    AttributeArgument(
                        NameEquals(IdentifierName("AllowMultiple")),
                        FalseLiteralExpression())));

            ClassDeclarationSyntax newNode = classDeclaration.AddAttributeLists(AttributeList(attribute));

            return(document.ReplaceNodeAsync(classDeclaration, newNode, cancellationToken));
        }
        private static CompilationUnitSyntax InsertMigrationVersionAttribute <T>(CompilationUnitSyntax syntaxRoot, ClassDeclarationSyntax classDeclarationSyntax, T timestamp)
        {
            SyntaxToken literal;
            SyntaxKind  syntaxKind;

            if (typeof(T) == typeof(long))
            {
                var value = Unsafe.As <T, long>(ref timestamp);
                literal    = Literal(value);
                syntaxKind = SyntaxKind.NumericLiteralExpression;
            }
            else if (typeof(T) == typeof(string))
            {
                var value = Unsafe.As <T, string>(ref timestamp);
                literal    = Literal(value);
                syntaxKind = SyntaxKind.StringLiteralExpression;
            }
            else
            {
                throw new ArgumentException("timestamp can either be a string or a long value", nameof(timestamp));
            }

            var newClassDeclarationSyntax =
                classDeclarationSyntax
                .AddAttributeLists(
                    AttributeList(
                        SingletonSeparatedList(
                            Attribute(
                                IdentifierName("MigrationVersion"))
                            .WithArgumentList(
                                AttributeArgumentList(
                                    SingletonSeparatedList(
                                        AttributeArgument(
                                            LiteralExpression(syntaxKind, literal))))))))
                .NormalizeWhitespace();

            syntaxRoot = syntaxRoot.ReplaceNode(classDeclarationSyntax, newClassDeclarationSyntax)
                         .NormalizeWhitespace();
            return(syntaxRoot);
        }
        private async Task <Document> AddDesignedForInheritanceAttribute(Document document, ClassDeclarationSyntax classDeclaration, CancellationToken cancellationToken)
        {
            var root = await document
                       .GetSyntaxRootAsync(cancellationToken)
                       .ConfigureAwait(false);

            var attributeToAdd = SyntaxFactory.Attribute(SyntaxFactory.IdentifierName(DesignedForInheritanceAnalyser.AttributeName));

            root = root.ReplaceNode(
                classDeclaration,
                classDeclaration.AddAttributeLists(SyntaxFactory.AttributeList(SyntaxFactory.SingletonSeparatedList(attributeToAdd)))                 // See http://stackoverflow.com/a/37598072/3813189
                );

            var usingDirectives = ((CompilationUnitSyntax)root).Usings;

            if (!usingDirectives.Any(usingDirective => (usingDirective.Alias == null) && (usingDirective.Name.ToFullString() == DesignedForInheritanceAnalyser.AttributeNamespace)))
            {
                root = ((CompilationUnitSyntax)root).WithUsings(                 // Courtesy of http://stackoverflow.com/a/17677024
                    usingDirectives.Add(SyntaxFactory.UsingDirective(SyntaxFactory.IdentifierName(DesignedForInheritanceAnalyser.AttributeNamespace)))
                    );
            }

            return(document.WithSyntaxRoot(root));
        }
예제 #21
0
 public static ClassDeclarationSyntax AddAttributeLists(this ClassDeclarationSyntax syntax, IEnumerable <AttributeListSyntax> lists)
 {
     return(syntax.AddAttributeLists(lists.ToArray()));
 }
예제 #22
0
 public void AddAttribute(AttributeSyntax attribute) =>
 _declaration = _declaration.AddAttributeLists(AttributeList().AddAttributes(attribute));
 public static void AddAttributeListToClass(this DocumentEditor documentEditor, ClassDeclarationSyntax classDeclaration, AttributeListSyntax attributeList)
 {
     documentEditor.ReplaceNode(classDeclaration, classDeclaration.AddAttributeLists(attributeList));
 }
예제 #24
0
 public static ClassDeclarationSyntax AsSerializable(this ClassDeclarationSyntax classDeclarationSyntax)
 {
     return(classDeclarationSyntax.AddAttributeLists(Attributes.Serializable));
 }
예제 #25
0
 public static ClassDeclarationSyntax AddAttributes(this ClassDeclarationSyntax source, params AttributeSyntax[] attributes)
 {
     return(source.AddAttributeLists(AttributeList(SeparatedList(attributes))));
 }
예제 #26
0
 public static ClassDeclarationSyntax AddAttribute(this ClassDeclarationSyntax source, AttributeSyntax attributes)
 {
     return(source.AddAttributeLists(AttributeList(SingletonSeparatedList(attributes))));
 }
        public ClassDeclarationSyntax Build(RoslynTranslator translator, VSGraphModel graphModel)
        {
            var baseClass = m_NeedToCompleteDependenciesFirst ? nameof(ComponentSystem) : nameof(JobComponentSystem);

            m_ClassDeclaration = m_ClassDeclaration.WithBaseList(
                BaseList(
                    SingletonSeparatedList <BaseTypeSyntax>(
                        SimpleBaseType(
                            IdentifierName(baseClass)))));

            foreach (var queryTracking in m_QueryHasStateTracking)
            {
                var trackingMembers = new List <MemberDeclarationSyntax>();
                if (queryTracking.Value.Tracking)
                {
                    trackingMembers.Add(
                        FieldDeclaration(
                            VariableDeclaration(
                                PredefinedType(
                                    Token(SyntaxKind.BoolKeyword)))
                            .WithVariables(
                                SingletonSeparatedList(
                                    VariableDeclarator(
                                        Identifier("Processed")))))
                        .WithModifiers(
                            TokenList(
                                Token(SyntaxKind.InternalKeyword))));
                }

                DeclareComponent <ISystemStateComponentData>(queryTracking.Value.ComponentName, trackingMembers);
            }

            foreach (var eventSystem in m_EventSystems)
            {
                //  ClearEvents<TestEvent2>.Initialize(World);
                InitializationStatements.Add(ExpressionStatement(InvocationExpression(
                                                                     MemberAccessExpression(
                                                                         SyntaxKind.SimpleMemberAccessExpression,
                                                                         GenericName(
                                                                             Identifier("EventSystem"))
                                                                         .WithTypeArgumentList(
                                                                             TypeArgumentList(
                                                                                 SingletonSeparatedList <TypeSyntax>(
                                                                                     IdentifierName(eventSystem.FullName)))),
                                                                         IdentifierName("Initialize")))
                                                                 .WithArgumentList(
                                                                     ArgumentList(
                                                                         SingletonSeparatedList(
                                                                             Argument(
                                                                                 IdentifierName("World")))))));
            }

            if ((TranslationOptions & RoslynEcsTranslator.TranslationOptions.Tracing) != 0)
            {
                DeclareAndInitField(typeof(TracingRecorderSystem), nameof(TracingRecorderSystem), initValue: InvocationExpression(
                                        MemberAccessExpression(
                                            SyntaxKind.SimpleMemberAccessExpression,
                                            IdentifierName("World"),
                                            GenericName(
                                                Identifier(nameof(World.GetExistingSystem)))
                                            .WithTypeArgumentList(
                                                TypeArgumentList(
                                                    SingletonSeparatedList <TypeSyntax>(
                                                        IdentifierName(nameof(TracingRecorderSystem))))))));
            }
            HashSet <string> declaredQueries = new HashSet <string>();

            foreach (var group in m_WrittenComponentsPerGroup)
            {
                declaredQueries.Add(group.Key.Query.ComponentQueryDeclarationModel.GetId());
                DeclareEntityQueries(group.Value);
            }

            // declare unused queries in case there's a Count Entities In Query node somewhere
            foreach (var graphVariable in graphModel.GraphVariableModels.OfType <ComponentQueryDeclarationModel>().Where(q => !declaredQueries.Contains(q.GetId())))
            {
                var args = graphVariable.Components.Select(c => SyntaxFactory.Argument(
                                                               InvocationExpression(
                                                                   MemberAccessExpression(
                                                                       SyntaxKind.SimpleMemberAccessExpression,
                                                                       IdentifierName("ComponentType"),
                                                                       GenericName(
                                                                           Identifier("ReadOnly"))
                                                                       .WithTypeArgumentList(
                                                                           TypeArgumentList(
                                                                               SingletonSeparatedList <TypeSyntax>(
                                                                                   IdentifierName(c.Component.TypeHandle.Resolve(graphModel.Stencil)
                                                                                                  .FullName))))))
                                                               ));
                var initValue = MakeInitQueryExpression(args);

                DeclareAndInitField(typeof(EntityQuery), graphVariable.VariableName, initValue: initValue);
            }


            var singletonMembers = new List <FieldDeclarationSyntax>();
            var initArguments    = new List <AssignmentExpressionSyntax>();

            foreach (var graphVariable in graphModel.GraphVariableModels
                     .Where(g => g.VariableType == VariableType.GraphVariable))
            {
                singletonMembers.Add(graphVariable.DeclareField(translator, false)
                                     .WithAdditionalAnnotations(new SyntaxAnnotation(Annotations.VariableAnnotationKind)));
                initArguments.Add(RoslynBuilder.Assignment(
                                      IdentifierName(graphVariable.VariableName),
                                      translator.Constant(graphVariable.InitializationModel.ObjectValue, m_Stencil)));
            }

            if (singletonMembers.Any())
            {
                DeclareComponent <IComponentData>(SingletonComponentTypeName, singletonMembers);
                InitializationStatements.Add(ExpressionStatement(
                                                 RoslynBuilder.MethodInvocation(
                                                     nameof(EntityManager.CreateEntity),
                                                     IdentifierName(nameof(EntityManager)),
                                                     new[]
                {
                    Argument(TypeOfExpression(IdentifierName(SingletonComponentTypeName)))
                },
                                                     Enumerable.Empty <TypeSyntax>())));
                InitializationStatements.Add(
                    ExpressionStatement(
                        RoslynBuilder.MethodInvocation(
                            SafeGuardNamingSystem.SetSingletonName,
                            null,
                            new[]
                {
                    Argument(RoslynBuilder.DeclareNewObject(
                                 IdentifierName(SingletonComponentTypeName),
                                 Enumerable.Empty <ArgumentSyntax>(),
                                 initArguments))
                },
                            Enumerable.Empty <TypeSyntax>())));
            }

            // TODO : Remove this once there is real Systems' dependency tool
            var attributes = new List <AttributeListSyntax>();

            foreach (var assetModel in m_Stencil.UpdateAfter.Where(a => a.GraphModel.Stencil is EcsStencil))
            {
                RegisterAttributes <UpdateAfterAttribute>(attributes, assetModel.Name);
            }

            foreach (var assetModel in m_Stencil.UpdateBefore.Where(a => a.GraphModel.Stencil is EcsStencil))
            {
                RegisterAttributes <UpdateBeforeAttribute>(attributes, assetModel.Name);
            }

            m_ClassDeclaration = m_ClassDeclaration
                                 .AddAttributeLists(attributes.ToArray())
                                 .AddMembers(m_ClassMembers.OrderBy(x => x is FieldDeclarationSyntax ? 0 : 1).ToArray());

            if (m_InitializationStatements != null)
            {
                var onCreateManagerOverride = RoslynBuilder.DeclareMethod(
                    SafeGuardNamingSystem.OnCreateManagerName,
                    AccessibilityFlags.Protected | AccessibilityFlags.Override,
                    typeof(void));
                m_ClassDeclaration = m_ClassDeclaration
                                     .AddMembers(
                    onCreateManagerOverride.WithBody(
                        Block(m_InitializationStatements)));
            }

            if (m_SingletonUpdateSyntax != null)
            {
                AddStatement(m_SingletonUpdateSyntax);
            }

            var onUpdateBlock = Block(m_UpdateStatements);

            return(m_ClassDeclaration.AddMembers(
                       RoslynEcsTranslator.MakeOnUpdateOverride(
                           onUpdateBlock,
                           m_NeedToCompleteDependenciesFirst,
                           m_CreatedManagers)));
        }
예제 #28
0
        public static ClassDeclarationSyntax AddAttribute(this ClassDeclarationSyntax classDeclarationSyntax, AttributeSyntax attributeSyntax)
        {
            var attributeList = SyntaxFactory.AttributeList().AddAttributes(attributeSyntax);

            return(classDeclarationSyntax.AddAttributeLists(attributeList));
        }
예제 #29
0
 public static ClassDeclarationSyntax WithAttributes(this ClassDeclarationSyntax node, params AttributeSyntax[] attributes)
 {
     return(node.AddAttributeLists(AttributeList(SeparatedList(attributes))));
 }
예제 #30
0
 public static ClassDeclarationSyntax WithGeneratedNonUserCodeAttributes(this ClassDeclarationSyntax node)
 => node.AddAttributeLists(GeneratedNonUserCodeAttributeList());