private Task <Document> AddStaticKeyword(Document document, SyntaxNode root, ClassDeclarationSyntax classDeclaration)
        {
            var staticKeyword  = SyntaxFactory.Token(SyntaxKind.StaticKeyword).WithAdditionalAnnotations(Formatter.Annotation);
            var newDeclaration = classDeclaration.AddModifiers(staticKeyword);
            var newRoot        = root.ReplaceNode(classDeclaration, newDeclaration);

            return(Task.FromResult(document.WithSyntaxRoot(newRoot)));
        }
 public static ClassDeclarationSyntax AddPartialModifier(this ClassDeclarationSyntax typeDecl)
 {
     if (typeDecl.Modifiers.Any(m => m.IsKind(SyntaxKind.PartialKeyword)))
     {
         return(typeDecl);
     }
     return(typeDecl.AddModifiers(new[] { PartialToken }));
 }
Esempio n. 3
0
 public static ClassDeclarationSyntax AddModifiers(this ClassDeclarationSyntax cl, params SyntaxKind[] modifiers)
 {
     if (modifiers == null)
     {
         return(cl);
     }
     return(cl.AddModifiers(modifiers.Select(x => SyntaxFactory.Token(x)).ToArray()));
 }
        public IWithInheritance CreateClass()
        {
            LogUtility.Info($"class Name: ${_settings.ClassName}");
            _class = SyntaxFactory.ClassDeclaration(_settings.ClassName);
            _class = _class.AddModifiers(SyntaxFactory.Token(SyntaxKind.PublicKeyword));

            return(this);
        }
        private void GenerateClass()
        {
            _classDeclaration = SyntaxFactory.ClassDeclaration(MainClassName);

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

            ProcessMainBlock(Module.Block);
        }
Esempio n. 6
0
        private ClassDeclarationSyntax CreateTestClass(string className)
        {
            AttributeListSyntax attributes = SyntaxFactory.AttributeList(SyntaxFactory.SingletonSeparatedList(
                                                                             SyntaxFactory.Attribute(SyntaxFactory.IdentifierName("TestClass")))
                                                                         ).NormalizeWhitespace();

            ClassDeclarationSyntax testClass = SyntaxFactory.ClassDeclaration("Test" + className);

            testClass = testClass.AddModifiers(SyntaxFactory.Token(SyntaxKind.PublicKeyword)).AddAttributeLists(attributes);
            return(testClass);
        }
Esempio n. 7
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)))));
            }
        }
        private async Task <Document> Seal(Document document, ClassDeclarationSyntax classDeclaration, CancellationToken cancellationToken)
        {
            var root = await document
                       .GetSyntaxRootAsync(cancellationToken)
                       .ConfigureAwait(false);

            return(document.WithSyntaxRoot(
                       root.ReplaceNode(
                           classDeclaration,
                           classDeclaration.AddModifiers(SyntaxFactory.Token(SyntaxKind.SealedKeyword))
                           )
                       ));
        }
        public IWithInheritance CreateClass(SyntaxToken[] modifiers, string name = null)
        {
            if (string.IsNullOrEmpty(name))
            {
                name = _settings.ClassName;
            }

            LogUtility.Info($"Adding class: ${name}");
            _class = SyntaxFactory.ClassDeclaration(name);
            _class = _class.AddModifiers(modifiers);

            return(this);
        }
        private static ClassDeclarationSyntax AddModifier(ClassDeclarationSyntax classDeclaration, SyntaxKind modifierKind)
        {
            SyntaxTokenList modifiers = classDeclaration.Modifiers;

            if (modifiers.Contains(modifierKind))
            {
                return(classDeclaration);
            }

            if (modifiers.Any())
            {
                int partialIndex = modifiers.IndexOf(SyntaxKind.PartialKeyword);

                if (partialIndex != -1)
                {
                    SyntaxToken partialToken = modifiers[partialIndex];

                    modifiers = modifiers
                                .ReplaceAt(partialIndex, partialToken.WithoutLeadingTrivia())
                                .Insert(
                        partialIndex,
                        Token(modifierKind)
                        .WithLeadingTrivia(partialToken.LeadingTrivia)
                        .WithTrailingTrivia(SpaceTrivia()));

                    return(classDeclaration.WithModifiers(modifiers));
                }
                else
                {
                    return(classDeclaration
                           .AddModifiers(Token(modifierKind).WithLeadingTrivia(SpaceTrivia())));
                }
            }
            else
            {
                return(classDeclaration.AddModifiers(Token(modifierKind)));
            }
        }
Esempio n. 11
0
        private async Task <Document> AddSealedAsync(Document document,
                                                     ClassDeclarationSyntax classDeclaration,
                                                     CancellationToken cancellationToken)
        {
            var sealedKeyword = SyntaxFactory.Token(SyntaxKind.SealedKeyword).WithAdditionalAnnotations(Formatter.Annotation);
            var newClass      = classDeclaration.AddModifiers(sealedKeyword);

            var root = await document.GetSyntaxRootAsync(cancellationToken);

            var newRoot     = root.ReplaceNode(classDeclaration, newClass);
            var newDocument = document.WithSyntaxRoot(newRoot);

            return(newDocument);
        }
Esempio n. 12
0
        private async Task <Document> AddPublicModifierToClass(Document document, SyntaxNode node, CancellationToken cancellationToken)
        {
            SyntaxNode root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);

            ClassDeclarationSyntax convertedNode = (ClassDeclarationSyntax)node;

            ClassDeclarationSyntax?newNode = convertedNode?.AddModifiers(SyntaxFactory.Token(SyntaxKind.PublicKeyword));

            SyntaxNode newRoot = root.ReplaceNode(node, newNode);

            Document newDocument = document.WithSyntaxRoot(newRoot);

            return(newDocument);
        }
        private static async Task <Document> GenerateCodeFixAsync(Document document,
                                                                  ClassDeclarationSyntax node,
                                                                  CancellationToken cancellationToken)
        {
            var modifierPartical = SyntaxFactory.ParseToken("partial ");
            var updatedNode      = node.AddModifiers(modifierPartical);

            var syntaxTree = await document.GetSyntaxTreeAsync(cancellationToken);

            if (syntaxTree is null)
            {
                throw new NullReferenceException(nameof(syntaxTree));
            }
            var updatedSyntaxTree =
                syntaxTree.GetRoot().ReplaceNode(node, updatedNode);

            return(document.WithSyntaxRoot(updatedSyntaxTree));
        }
        public override Task RegisterCodeFixesAsync(CodeFixContext context)
        {
            CodeAction codeFix = CodeAction.Create("Seal the class", ct => SealClassAsync(ct));

            context.RegisterCodeFix(codeFix, context.Diagnostics[0]);
            return(Task.CompletedTask);

            async Task <Document> SealClassAsync(CancellationToken cancellationToken)
            {
                SyntaxNode root = await context.Document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);

                ClassDeclarationSyntax classDeclaration = (ClassDeclarationSyntax)root.FindNode(context.Span);

                ClassDeclarationSyntax newDeclaration = classDeclaration.AddModifiers(SyntaxFactory.Token(SyntaxKind.SealedKeyword));
                SyntaxNode             newRoot        = root.ReplaceNode(classDeclaration, newDeclaration);

                return(context.Document.WithSyntaxRoot(newRoot));
            }
        }
Esempio n. 15
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);
        }
Esempio n. 16
0
        public HamlCodeHostBuilder(Type modelType)
        {
            this._modelType = modelType;
            var modelTypeToken = SyntaxFactory.ParseTypeName(modelType.FullName);
            var rootDirectory  = Path.GetDirectoryName(typeof(object).GetTypeInfo().Assembly.Location);
            var className      = "__haml_UserCode_CompilationTarget";

            _compilation = CSharpCompilation.Create("Compilation")
                           .WithReferences(
                MetadataReference.CreateFromFile(typeof(object).GetTypeInfo().Assembly.Location),
                MetadataReference.CreateFromFile(Path.Combine(rootDirectory, "System.Runtime.dll")),
                MetadataReference.CreateFromFile(Path.Combine(rootDirectory, "mscorlib.dll")),
                MetadataReference.CreateFromFile(modelType.GetTypeInfo().Assembly.Location),
                MetadataReference.CreateFromFile(typeof(HtmlHelper).GetTypeInfo().Assembly.Location))
                           .WithOptions(new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary, optimizationLevel: OptimizationLevel.Release));
            _compilationTargetClass = SyntaxFactory.ClassDeclaration(className);
            _compilationUnit        = SyntaxFactory.CompilationUnit()
                                      .WithUsings(SyntaxFactory.List(new[] { SyntaxFactory.UsingDirective(SyntaxFactory.IdentifierName("System")) }));

            textRun = new StringBuilder();
            _compilationTargetClass = _compilationTargetClass

                                      /*.AddMembers(
                                       *  SyntaxFactory.PropertyDeclaration(SyntaxFactory.ParseTypeName(typeof(HtmlHelper).FullName), "Html"))*/
                                      .AddModifiers(SyntaxFactory.Token(SyntaxKind.SealedKeyword))
                                      .AddMembers(
                SyntaxFactory.ConstructorDeclaration(className)
                .AddModifiers(SyntaxFactory.Token(SyntaxKind.PublicKeyword))
                .AddParameterListParameters(SyntaxFactory.Parameter(SyntaxFactory.Identifier("_modelType")).WithType(modelTypeToken))
                .AddBodyStatements(SyntaxFactory.ExpressionStatement(
                                       SyntaxFactory.AssignmentExpression(SyntaxKind.SimpleAssignmentExpression, SyntaxFactory.IdentifierName("model"), SyntaxFactory.IdentifierName("_modelType")))))
                                      .AddMembers(SyntaxFactory.FieldDeclaration(SyntaxFactory.VariableDeclaration(modelTypeToken, SyntaxFactory.SingletonSeparatedList(SyntaxFactory.VariableDeclarator("model"))))
                                                  .AddModifiers(SyntaxFactory.Token(SyntaxKind.ReadOnlyKeyword)));

            _renderMethod = SyntaxFactory.MethodDeclaration(SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.VoidKeyword)), "render")
                            .AddParameterListParameters(SyntaxFactory.Parameter(SyntaxFactory.Identifier("textWriter")).WithType(SyntaxFactory.ParseTypeName(typeof(TextWriter).FullName)))
                            .AddModifiers(SyntaxFactory.Token(SyntaxKind.PublicKeyword));

            expressions = new Stack <IList <StatementSyntax> >();
            expressions.Push(new List <StatementSyntax>());
        }
Esempio n. 17
0
        private static TypeDeclarationSyntax ParseModel(ClassDeclarationSyntax @class, ParameterListSyntax parameters, Scope scope)
        {
            var init  = new List <ParameterSyntax>();
            var props = new List <PropertyDeclarationSyntax>();

            foreach (var member in @class.Members)
            {
                var field = ParseField(member);
                if (field == null)
                {
                    continue; //error has already been registered
                }
                var type     = field.Declaration.Type;
                var variable = field.Declaration
                               .Variables
                               .Single();


                init.Add(CSharp.Parameter(variable.Identifier)
                         .WithType(type)
                         .WithDefault(CSharp.EqualsValueClause(
                                          variable.Initializer != null
                            ? variable.Initializer.Value
                            : CSharp.DefaultExpression(type))));

                props.Add(ModelProperty.Get <PropertyDeclarationSyntax>(type)
                          .WithIdentifier(variable.Identifier));
            }

            if (!RoslynCompiler.HasVisibilityModifier(@class.Modifiers))
            {
                @class = @class.AddModifiers(CSharp.Token(SyntaxKind.PublicKeyword));
            }

            return(@class
                   .WithMembers(CSharp.List <MemberDeclarationSyntax>(
                                    props.Union(new[] {
                GenerateConstructor(@class, init)
            }))));
        }
Esempio n. 18
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);
        }
Esempio n. 19
0
        private async Task <Document> MarkDacFieldAsAbstractAsync(Document document, TextSpan span, CancellationToken cancellationToken)
        {
            SyntaxNode root = await document.GetSyntaxRootAsync(cancellationToken)
                              .ConfigureAwait(false);

            ClassDeclarationSyntax dacFieldDeclaration = root?.FindNode(span) as ClassDeclarationSyntax;

            if (dacFieldDeclaration == null || cancellationToken.IsCancellationRequested)
            {
                return(document);
            }

            SyntaxToken abstractToken = SyntaxFactory.Token(SyntaxKind.AbstractKeyword);

            if (dacFieldDeclaration.Modifiers.Contains(abstractToken))
            {
                return(document);
            }

            var modifiedRoot = root.ReplaceNode(dacFieldDeclaration, dacFieldDeclaration.AddModifiers(abstractToken));

            return(document.WithSyntaxRoot(modifiedRoot));
        }
Esempio n. 20
0
 public static ClassDeclarationSyntax AddModifiers(this ClassDeclarationSyntax syntax, params SyntaxKind[] modifier)
 {
     return(syntax.AddModifiers(modifier.Select(Token).ToArray()));
 }
Esempio n. 21
0
 private void MakePartial() =>
 _declaration = _declaration.AddModifiers(Token(SyntaxKind.PartialKeyword));
 public static ClassDeclarationSyntax WithPartialModifier(this ClassDeclarationSyntax declaration)
 {
     return(declaration.AddModifiers(SyntaxFactory.Token(SyntaxKind.PartialKeyword)));
 }
 public static ClassDeclarationSyntax AddPartialModifierIfNotPresent(this ClassDeclarationSyntax node)
 {
     return(node.Modifiers.Any(SyntaxKind.PartialKeyword)
         ? node
         : node.AddModifiers(SyntaxFactory.Token(SyntaxKind.PartialKeyword)));
 }
 /// <summary>
 /// Adds the specified modifier to the class declaration.
 /// </summary>
 /// <param name="syntax">The syntax.</param>
 /// <param name="token">The token.</param>
 /// <returns></returns>
 internal static ClassDeclarationSyntax AddModifier(this ClassDeclarationSyntax syntax, SyntaxToken token)
 => syntax.AddModifiers(new SyntaxToken[] { token });
Esempio n. 25
0
 public static ClassDeclarationSyntax WithModifiers(this ClassDeclarationSyntax node, params SyntaxKind[] modifiers)
 {
     return(node.AddModifiers(CreateModifiers(modifiers)));
 }
Esempio n. 26
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);
        }
 private static Task <Document> FixMissingPartial(Document contextDocument, SyntaxNode root, ClassDeclarationSyntax @class)
 {
     return(Task.FromResult(contextDocument.WithSyntaxRoot(root.ReplaceNode(@class, @class.AddModifiers(Token(SyntaxKind.PartialKeyword))))));
 }