public void ParseFieldWithConvertAttribute() { var f = FieldModel.Parse(null, RoslynBuilder.DeclareField(typeof(Entity), "a") .AddAttributeLists(SyntaxFactory.AttributeList().AddAttributes(SyntaxFactory.Attribute(SyntaxFactory.IdentifierName("Convert"))))); Assert.That(f, Is.Not.Null); Assert.AreEqual(typeof(GameObject), f.Type); }
private List <MethodDeclarationSyntax> CreateMethods(ref List <ClassDeclarationSyntax> classes) { List <MethodDeclarationSyntax> newMethods = new List <MethodDeclarationSyntax>(); foreach (var classDecl in classes) { var methods = classDecl.DescendantNodes() .OfType <MethodDeclarationSyntax>() .Where(method => method.Modifiers. Where(modifier => modifier.IsKind(SyntaxKind.PublicKeyword)).Any()).ToList(); if (methods.Count() == 0) { return(newMethods); } foreach (var method in methods) { var body = SyntaxFactory.ParseStatement("Assert.Fail(\"autogenerated\");"); var newTestMethod = SyntaxFactory.MethodDeclaration(SyntaxFactory.ParseTypeName("void"), string.Concat(classDecl.Identifier, method.Identifier, "Test")) .AddAttributeLists(SyntaxFactory.AttributeList((SyntaxFactory.SingletonSeparatedList( SyntaxFactory.Attribute(SyntaxFactory.IdentifierName("Test")))))) .AddModifiers(SyntaxFactory.Token(SyntaxKind.PublicKeyword)) .WithBody(SyntaxFactory.Block(body)); newMethods.Add(newTestMethod); } } return(newMethods); }
public static AttributeSyntax Attribute(string name) { return(SyntaxFactory.Attribute(SyntaxFactory.ParseName(name))); }
private static MethodDeclarationSyntax CreateEmptyMethod(MethodInfo methodInfo, IList <Type> attributeTypes) { var returnType = MakeReturnType(methodInfo); var claimParameters = GetClaimsParameters(methodInfo); if (claimParameters.Any()) { attributeTypes = attributeTypes.ToList(); attributeTypes.Add(typeof(AuthorizeAttribute)); } var attributeList = new SeparatedSyntaxList <AttributeSyntax>(); foreach (var attribute in attributeTypes) { attributeList = attributeList.Add(SyntaxFactory.Attribute(SyntaxFactory.ParseName(attribute.FullName))); } var routeAttribute = SyntaxFactory.Attribute(SyntaxFactory.ParseName(typeof(RouteAttribute).FullName), SyntaxFactory.ParseAttributeArgumentList(@"(""[action]"")") ); attributeList = attributeList.Add(routeAttribute); var methodDeclaration = SyntaxFactory .MethodDeclaration(SyntaxFactory.ParseTypeName(Type2String(returnType)), methodInfo.Name) .AddModifiers(SyntaxFactory.Token(SyntaxKind.PublicKeyword)); if (IsAsyncMethod(methodInfo)) { methodDeclaration = methodDeclaration.AddModifiers(SyntaxFactory.Token(SyntaxKind.AsyncKeyword)); } var attributes = SyntaxFactory.AttributeList(attributeList); var attributesList = methodDeclaration.AttributeLists.Add(attributes); methodDeclaration = methodDeclaration.WithAttributeLists(attributesList); var payloadParameters = GetPayLoadParameters(methodInfo); if (payloadParameters.Any()) { var payloadClassName = methodInfo.Name + "Payload"; var parameter = SyntaxFactory.Parameter(SyntaxFactory.Identifier("payload")) .WithType(SyntaxFactory.ParseTypeName(payloadClassName)); var parameters = SyntaxFactory.ParameterList(SyntaxFactory.SeparatedList <ParameterSyntax>().Add(parameter)); methodDeclaration = methodDeclaration.WithParameterList(parameters); return(methodDeclaration); } var normalParameters = GetNormalParameters(methodInfo); foreach (var normalParameter in normalParameters) { var parameter = SyntaxFactory.Parameter(SyntaxFactory.Identifier(normalParameter.Name)) .WithType(SyntaxFactory.ParseTypeName(normalParameter.ParameterType.FullName)); var parameters = SyntaxFactory.ParameterList(SyntaxFactory.SeparatedList <ParameterSyntax>().Add(parameter)); methodDeclaration = methodDeclaration.WithParameterList(parameters); } return(methodDeclaration); }
public void TestClassGenerating() { //Generated by https://roslynquoter.azurewebsites.net/ #region TestClassGenerate var testClass = SyntaxFactory.CompilationUnit() .WithMembers( SyntaxFactory.SingletonList <MemberDeclarationSyntax>( SyntaxFactory.ClassDeclaration("CodeGeneratingSamples") .WithAttributeLists( SyntaxFactory.SingletonList <AttributeListSyntax>( SyntaxFactory.AttributeList( SyntaxFactory.SingletonSeparatedList <AttributeSyntax>( SyntaxFactory.Attribute( SyntaxFactory.IdentifierName("TestClass")))))) .WithModifiers( SyntaxFactory.TokenList( SyntaxFactory.Token(SyntaxKind.PublicKeyword))) .WithMembers( SyntaxFactory.SingletonList <MemberDeclarationSyntax>( SyntaxFactory.MethodDeclaration( SyntaxFactory.PredefinedType( SyntaxFactory.Token(SyntaxKind.VoidKeyword)), SyntaxFactory.Identifier("EmptyCSharpClassGenerating")) .WithAttributeLists( SyntaxFactory.SingletonList <AttributeListSyntax>( SyntaxFactory.AttributeList( SyntaxFactory.SingletonSeparatedList <AttributeSyntax>( SyntaxFactory.Attribute( SyntaxFactory.IdentifierName("TestMethod")))))) .WithModifiers( SyntaxFactory.TokenList( SyntaxFactory.Token(SyntaxKind.PublicKeyword))) .WithBody( SyntaxFactory.Block( SyntaxFactory.LocalDeclarationStatement( SyntaxFactory.VariableDeclaration( SyntaxFactory.IdentifierName( SyntaxFactory.Identifier( SyntaxFactory.TriviaList( SyntaxFactory.Comment( "//Compilation unit for representing single source file")), "var", SyntaxFactory.TriviaList()))) .WithVariables( SyntaxFactory .SingletonSeparatedList <VariableDeclaratorSyntax>( SyntaxFactory.VariableDeclarator( SyntaxFactory.Identifier("compilationUnit")) .WithInitializer( SyntaxFactory.EqualsValueClause( SyntaxFactory.InvocationExpression( SyntaxFactory .MemberAccessExpression( SyntaxKind .SimpleMemberAccessExpression, SyntaxFactory .IdentifierName( "SyntaxFactory"), SyntaxFactory .IdentifierName( "CompilationUnit")))))))), SyntaxFactory.LocalDeclarationStatement( SyntaxFactory.VariableDeclaration( SyntaxFactory.IdentifierName("var")) .WithVariables( SyntaxFactory .SingletonSeparatedList <VariableDeclaratorSyntax>( SyntaxFactory.VariableDeclarator( SyntaxFactory.Identifier( "emptyClassSyntax")) .WithInitializer( SyntaxFactory.EqualsValueClause( SyntaxFactory.InvocationExpression( SyntaxFactory .MemberAccessExpression( SyntaxKind .SimpleMemberAccessExpression, SyntaxFactory .InvocationExpression( SyntaxFactory .MemberAccessExpression( SyntaxKind .SimpleMemberAccessExpression, SyntaxFactory .IdentifierName( "compilationUnit"), SyntaxFactory .IdentifierName( "WithMembers"))) .WithArgumentList( SyntaxFactory .ArgumentList( SyntaxFactory .SingletonSeparatedList <ArgumentSyntax >( SyntaxFactory .Argument( SyntaxFactory .InvocationExpression( SyntaxFactory .MemberAccessExpression( SyntaxKind .SimpleMemberAccessExpression, SyntaxFactory .IdentifierName( "SyntaxFactory"), SyntaxFactory .GenericName( SyntaxFactory .Identifier( "SingletonList")) .WithTypeArgumentList( SyntaxFactory .TypeArgumentList( SyntaxFactory .SingletonSeparatedList <TypeSyntax >( SyntaxFactory .IdentifierName( "MemberDeclarationSyntax")))))) .WithArgumentList( SyntaxFactory .ArgumentList( SyntaxFactory .SingletonSeparatedList <ArgumentSyntax >( SyntaxFactory .Argument( SyntaxFactory .InvocationExpression( SyntaxFactory .MemberAccessExpression( SyntaxKind .SimpleMemberAccessExpression, SyntaxFactory .IdentifierName( "SyntaxFactory"), SyntaxFactory .IdentifierName( "ClassDeclaration"))) .WithArgumentList( SyntaxFactory .ArgumentList( SyntaxFactory .SingletonSeparatedList <ArgumentSyntax >( SyntaxFactory .Argument( SyntaxFactory .LiteralExpression( SyntaxKind .StringLiteralExpression, SyntaxFactory .Literal( "C")))))))))))))), SyntaxFactory .IdentifierName( "NormalizeWhitespace")))))))), SyntaxFactory.ExpressionStatement( SyntaxFactory.InvocationExpression( SyntaxFactory.MemberAccessExpression( SyntaxKind.SimpleMemberAccessExpression, SyntaxFactory.IdentifierName("Trace"), SyntaxFactory.IdentifierName("WriteLine"))) .WithArgumentList( SyntaxFactory.ArgumentList( SyntaxFactory.SingletonSeparatedList <ArgumentSyntax>( SyntaxFactory.Argument( SyntaxFactory.InvocationExpression( SyntaxFactory.MemberAccessExpression( SyntaxKind.SimpleMemberAccessExpression, SyntaxFactory.IdentifierName( "emptyClassSyntax"), SyntaxFactory.IdentifierName( "ToFullString")))))))))))))) .NormalizeWhitespace(); #endregion Trace.WriteLine(testClass.ToFullString()); }
public override async Task RegisterCodeFixesAsync(CodeFixContext context) { bool RequiresUsing(SemanticModel model, SyntaxNode root) => model.Compilation.GlobalNamespace?.Namespace(nameof(Entia))?.Namespace(nameof(Core)) is INamespaceSymbol @namespace && root.DescendantNodes().OfType <UsingDirectiveSyntax>().None(@using => model.GetSymbolInfo(@using.Name).Symbol == @namespace); UsingDirectiveSyntax CreateUsing() => SyntaxFactory.UsingDirective( SyntaxFactory.QualifiedName( SyntaxFactory.IdentifierName(nameof(Entia)), SyntaxFactory.IdentifierName(nameof(Core)))); SyntaxList <AttributeListSyntax> AddAttribute(in SyntaxList <AttributeListSyntax> lists) { var attribute = SyntaxFactory.Attribute(SyntaxFactory.IdentifierName("Default")); return(lists.Count > 0 ? lists.Replace(lists[0], lists[0].AddAttributes(attribute)) : lists.Add(SyntaxFactory.AttributeList().AddAttributes(attribute))); } async Task <Solution> FixField(Document document, CompilationUnitSyntax root, FieldDeclarationSyntax declaration, CancellationToken token) { var model = await document.GetSemanticModelAsync(token); var replaced = root.ReplaceNode(declaration, declaration.WithAttributeLists(AddAttribute(declaration.AttributeLists))); if (RequiresUsing(model, root)) { replaced = replaced.AddUsings(CreateUsing()); } var solution = document.Project.Solution; return(solution.WithDocumentSyntaxRoot(document.Id, replaced)); } async Task <Solution> FixProperty(Document document, CompilationUnitSyntax root, PropertyDeclarationSyntax declaration, CancellationToken token) { var model = await document.GetSemanticModelAsync(token); var replaced = root.ReplaceNode(declaration, declaration.WithAttributeLists(AddAttribute(declaration.AttributeLists))); if (RequiresUsing(model, root)) { replaced = replaced.AddUsings(CreateUsing()); } var solution = document.Project.Solution; return(solution.WithDocumentSyntaxRoot(document.Id, replaced)); } async Task <Solution> FixMethod(Document document, CompilationUnitSyntax root, MethodDeclarationSyntax declaration, CancellationToken token) { var model = await document.GetSemanticModelAsync(token); var replaced = root.ReplaceNode(declaration, declaration.WithAttributeLists(AddAttribute(declaration.AttributeLists))); if (RequiresUsing(model, root)) { replaced = replaced.AddUsings(CreateUsing()); } var solution = document.Project.Solution; return(solution.WithDocumentSyntaxRoot(document.Id, replaced)); } await context.RegisterCodeAction <FieldDeclarationSyntax>("Add 'Default' attribute.", NamedType.Rules.MissingDefaultAttribute.Id, FixField); await context.RegisterCodeAction <PropertyDeclarationSyntax>("Add 'Default' attribute.", NamedType.Rules.MissingDefaultAttribute.Id, FixProperty); await context.RegisterCodeAction <MethodDeclarationSyntax>("Add 'Default' attribute.", NamedType.Rules.MissingDefaultAttribute.Id, FixMethod); }
public void FormatElasticTrivia() { var expected = @"extern alias A1; #line 99 [assembly: My] class My : System.Attribute { } class A { } [My] class B { }"; var compilation = SyntaxFactory.CompilationUnit( externs: SyntaxFactory.SingletonList <ExternAliasDirectiveSyntax>( SyntaxFactory.ExternAliasDirective("A1")), usings: default(SyntaxList <UsingDirectiveSyntax>), attributeLists: SyntaxFactory.SingletonList <AttributeListSyntax>( SyntaxFactory.AttributeList( SyntaxFactory.Token( SyntaxFactory.TriviaList( SyntaxFactory.Trivia( SyntaxFactory.LineDirectiveTrivia( SyntaxFactory.Literal("99", 99), false))), SyntaxKind.OpenBracketToken, SyntaxFactory.TriviaList()), SyntaxFactory.AttributeTargetSpecifier( SyntaxFactory.Identifier("assembly")), SyntaxFactory.SingletonSeparatedList <AttributeSyntax>( SyntaxFactory.Attribute( SyntaxFactory.ParseName("My"))), SyntaxFactory.Token( SyntaxKind.CloseBracketToken))), members: SyntaxFactory.List <MemberDeclarationSyntax>( new MemberDeclarationSyntax[] { SyntaxFactory.ClassDeclaration( default(SyntaxList <AttributeListSyntax>), SyntaxFactory.TokenList(), SyntaxFactory.Identifier("My"), null, SyntaxFactory.BaseList( SyntaxFactory.SingletonSeparatedList <BaseTypeSyntax>( SyntaxFactory.SimpleBaseType(SyntaxFactory.ParseTypeName("System.Attribute")))), default(SyntaxList <TypeParameterConstraintClauseSyntax>), default(SyntaxList <MemberDeclarationSyntax>)), SyntaxFactory.ClassDeclaration("A"), SyntaxFactory.ClassDeclaration( attributeLists: SyntaxFactory.SingletonList <AttributeListSyntax>( SyntaxFactory.AttributeList( SyntaxFactory.SingletonSeparatedList <AttributeSyntax>( SyntaxFactory.Attribute( SyntaxFactory.ParseName("My"))))), modifiers: SyntaxFactory.TokenList(), identifier: SyntaxFactory.Identifier("B"), typeParameterList: null, baseList: null, constraintClauses: default(SyntaxList <TypeParameterConstraintClauseSyntax>), members: default(SyntaxList <MemberDeclarationSyntax>)) })); Assert.NotNull(compilation); var newCompilation = Formatter.Format(compilation, new AdhocWorkspace()); Assert.Equal(expected, newCompilation.ToFullString()); }
/// <summary> /// Créé une syntaxe d'attribut. /// </summary> /// <param name="attributeName">Nom de l'attribut.</param> /// <returns>Node attribut.</returns> private static AttributeSyntax CreateAttribute(string attributeName) { return(SyntaxFactory.Attribute( SyntaxFactory.IdentifierName( SyntaxFactory.Identifier(attributeName)))); }
private static AttributeListSyntax CreateIgnoreAttribute() { AttributeSyntax attr = SyntaxFactory.Attribute(SyntaxFactory.ParseName("XmlIgnore")); return(SyntaxFactory.AttributeList(SyntaxFactory.SeparatedList(new[] { attr }))); }
static AttributeListSyntax MakeAttributes(params string[] attributeNames) { return(SyntaxFactory.AttributeList( SyntaxFactory.SeparatedList( attributeNames.Select(a => SyntaxFactory.Attribute(SyntaxFactory.IdentifierName(a)))))); }
public static void ExampleTwo() { var codeSyntax = new List <SyntaxNode>(); foreach (var data in GetEnumsDetails()) { var generatedEnum = SyntaxFactory.EnumDeclaration(data.ShortDescription.Replace(" ", "")) .WithModifiers(SyntaxFactory.TokenList(SyntaxFactory.Token(SyntaxKind.PublicKeyword))) .WithAttributeLists(SyntaxFactory.SingletonList(SyntaxFactory.AttributeList( SyntaxFactory.SingletonSeparatedList(SyntaxFactory.Attribute(SyntaxFactory.IdentifierName("Description")) .WithArgumentList(SyntaxFactory.AttributeArgumentList(SyntaxFactory.SingletonSeparatedList( SyntaxFactory.AttributeArgument(SyntaxFactory.LiteralExpression(SyntaxKind.StringLiteralExpression, SyntaxFactory.Literal(data.LongDescription)))))))))); foreach (var item in data.Details) { var attributes = SyntaxFactory.SingletonList( SyntaxFactory.AttributeList(SyntaxFactory .SingletonSeparatedList(SyntaxFactory.Attribute( SyntaxFactory.IdentifierName("Description")).WithArgumentList( SyntaxFactory.AttributeArgumentList( SyntaxFactory.SingletonSeparatedList(SyntaxFactory.AttributeArgument( SyntaxFactory.LiteralExpression( SyntaxKind.StringLiteralExpression, SyntaxFactory.Literal(item.LongDescription))))))))); var objectCreationExpression = SyntaxFactory.EqualsValueClause( SyntaxFactory.LiteralExpression(SyntaxKind.NumericLiteralExpression, SyntaxFactory.Literal(item.LoanCodeId))); if (!string.IsNullOrEmpty(item.LongDescription)) { var member = SyntaxFactory.EnumMemberDeclaration(attributes, SyntaxFactory.Identifier(item.ShortDescription), objectCreationExpression); generatedEnum = generatedEnum.AddMembers(member); } else { generatedEnum = generatedEnum.AddMembers(SyntaxFactory.EnumMemberDeclaration(SyntaxFactory.Identifier(item.ShortDescription)) .WithEqualsValue(SyntaxFactory.EqualsValueClause(SyntaxFactory.LiteralExpression (SyntaxKind.NumericLiteralExpression, SyntaxFactory.Literal(item.LoanCodeId))))); } } codeSyntax.Add(generatedEnum); } codeSyntax.ForEach(a => Console.WriteLine(a.NormalizeWhitespace().ToString())); }
private static SyntaxTree GetAssemblyInfo(AssemblyInfo info) { return(SyntaxFactory.CompilationUnit() // start: add using patterns code and set custom qualified name for assembly basic head info, example as /* * using System.Reflection * using System.Runtime.InteropServices * using System.Runtime.Versioning */ .WithUsings( SyntaxFactory.List( new[] { SyntaxFactory.UsingDirective(SyntaxFactory.QualifiedName( SyntaxFactory.IdentifierName("System"), SyntaxFactory.IdentifierName("Reflection"))), SyntaxFactory.UsingDirective(SyntaxFactory.QualifiedName( SyntaxFactory.QualifiedName(SyntaxFactory.IdentifierName("System"), SyntaxFactory.IdentifierName("Runtime")), SyntaxFactory.IdentifierName("InteropServices"))), SyntaxFactory.UsingDirective(SyntaxFactory.QualifiedName( SyntaxFactory.QualifiedName(SyntaxFactory.IdentifierName("System"), SyntaxFactory.IdentifierName("Runtime")), SyntaxFactory.IdentifierName("Versioning"))) })) // before // start: add reflection code and set custom tips text or framework version /* * [0] = {AttributeListSyntax} "[assembly:TargetFramework(".NETFramework,Version=v4.5",FrameworkDisplayName=".NET Framework 4.5")]" * [1] = {AttributeListSyntax} "[assembly:AssemblyTitle("Rabbit.Rpc.ClientProxys")]" * [2] = {AttributeListSyntax} "[assembly:AssemblyProduct("Rabbit.Rpc.ClientProxys")]" * [3] = {AttributeListSyntax} "[assembly:AssemblyCopyright("Copyright © Rabbit")]" * [4] = {AttributeListSyntax} "[assembly:ComVisible(false)]" * [5] = {AttributeListSyntax} "[assembly:Guid("a40f0c95-b12d-4f76-a983-d7fea7a90f1d")]" * [6] = {AttributeListSyntax} "[assembly:AssemblyVersion("1.0.0.0")]" * [7] = {AttributeListSyntax} "[assembly:AssemblyFileVersion("1.0.0.0")]" */ .WithAttributeLists( SyntaxFactory.List( new[] { SyntaxFactory.AttributeList(SyntaxFactory.SingletonSeparatedList(SyntaxFactory .Attribute(SyntaxFactory.IdentifierName("TargetFramework")) .WithArgumentList(SyntaxFactory.AttributeArgumentList( SyntaxFactory.SeparatedList <AttributeArgumentSyntax>( new SyntaxNodeOrToken[] { SyntaxFactory.AttributeArgument( SyntaxFactory.LiteralExpression(SyntaxKind.StringLiteralExpression, SyntaxFactory.Literal(".NETFramework,Version=v4.5"))), SyntaxFactory.Token(SyntaxKind.CommaToken), SyntaxFactory .AttributeArgument(SyntaxFactory.LiteralExpression( SyntaxKind.StringLiteralExpression, SyntaxFactory.Literal(".NET Framework 4.5"))) .WithNameEquals(SyntaxFactory.NameEquals( SyntaxFactory.IdentifierName("FrameworkDisplayName"))) }))))) .WithTarget( SyntaxFactory.AttributeTargetSpecifier( SyntaxFactory.Token(SyntaxKind.AssemblyKeyword))), // [AssemblyTitle("Rabbit.Rpc.ClientProxys")] SyntaxFactory.AttributeList(SyntaxFactory.SingletonSeparatedList(SyntaxFactory .Attribute(SyntaxFactory.IdentifierName("AssemblyTitle")) .WithArgumentList( SyntaxFactory.AttributeArgumentList(SyntaxFactory.SingletonSeparatedList( SyntaxFactory.AttributeArgument( SyntaxFactory.LiteralExpression(SyntaxKind.StringLiteralExpression, SyntaxFactory.Literal(info.Title)))))))) .WithTarget( SyntaxFactory.AttributeTargetSpecifier( SyntaxFactory.Token(SyntaxKind.AssemblyKeyword))), SyntaxFactory.AttributeList(SyntaxFactory.SingletonSeparatedList(SyntaxFactory .Attribute(SyntaxFactory.IdentifierName("AssemblyProduct")) .WithArgumentList( SyntaxFactory.AttributeArgumentList(SyntaxFactory.SingletonSeparatedList( SyntaxFactory.AttributeArgument( SyntaxFactory.LiteralExpression(SyntaxKind.StringLiteralExpression, SyntaxFactory.Literal(info.Product)))))))) .WithTarget( SyntaxFactory.AttributeTargetSpecifier( SyntaxFactory.Token(SyntaxKind.AssemblyKeyword))), SyntaxFactory.AttributeList(SyntaxFactory.SingletonSeparatedList(SyntaxFactory .Attribute(SyntaxFactory.IdentifierName("AssemblyCopyright")) .WithArgumentList( SyntaxFactory.AttributeArgumentList(SyntaxFactory.SingletonSeparatedList( SyntaxFactory.AttributeArgument( SyntaxFactory.LiteralExpression(SyntaxKind.StringLiteralExpression, SyntaxFactory.Literal(info.Copyright)))))))) .WithTarget( SyntaxFactory.AttributeTargetSpecifier( SyntaxFactory.Token(SyntaxKind.AssemblyKeyword))), SyntaxFactory.AttributeList(SyntaxFactory.SingletonSeparatedList(SyntaxFactory .Attribute(SyntaxFactory.IdentifierName("ComVisible")) .WithArgumentList( SyntaxFactory.AttributeArgumentList(SyntaxFactory.SingletonSeparatedList( SyntaxFactory.AttributeArgument( SyntaxFactory.LiteralExpression(info.ComVisible ? SyntaxKind.TrueLiteralExpression : SyntaxKind.FalseLiteralExpression))))))) .WithTarget( SyntaxFactory.AttributeTargetSpecifier( SyntaxFactory.Token(SyntaxKind.AssemblyKeyword))), SyntaxFactory.AttributeList(SyntaxFactory.SingletonSeparatedList(SyntaxFactory .Attribute(SyntaxFactory.IdentifierName("Guid")) .WithArgumentList( SyntaxFactory.AttributeArgumentList(SyntaxFactory.SingletonSeparatedList( SyntaxFactory.AttributeArgument( SyntaxFactory.LiteralExpression(SyntaxKind.StringLiteralExpression, SyntaxFactory.Literal(info.Guid)))))))) .WithTarget( SyntaxFactory.AttributeTargetSpecifier( SyntaxFactory.Token(SyntaxKind.AssemblyKeyword))), SyntaxFactory.AttributeList(SyntaxFactory.SingletonSeparatedList(SyntaxFactory .Attribute(SyntaxFactory.IdentifierName("AssemblyVersion")) .WithArgumentList( SyntaxFactory.AttributeArgumentList(SyntaxFactory.SingletonSeparatedList( SyntaxFactory.AttributeArgument( SyntaxFactory.LiteralExpression(SyntaxKind.StringLiteralExpression, SyntaxFactory.Literal(info.Version)))))))) .WithTarget( SyntaxFactory.AttributeTargetSpecifier( SyntaxFactory.Token(SyntaxKind.AssemblyKeyword))), SyntaxFactory.AttributeList(SyntaxFactory.SingletonSeparatedList(SyntaxFactory .Attribute(SyntaxFactory.IdentifierName("AssemblyFileVersion")) .WithArgumentList( SyntaxFactory.AttributeArgumentList(SyntaxFactory.SingletonSeparatedList( SyntaxFactory.AttributeArgument( SyntaxFactory.LiteralExpression(SyntaxKind.StringLiteralExpression, SyntaxFactory.Literal(info.FileVersion)))))))) .WithTarget( SyntaxFactory.AttributeTargetSpecifier( SyntaxFactory.Token(SyntaxKind.AssemblyKeyword))) })) .NormalizeWhitespace() .SyntaxTree); }
public string GenerateCode(bool cmApi = false) { var cmApiUsings = new[] { SyntaxFactory.UsingDirective(SyntaxFactory.IdentifierName("Newtonsoft.Json")), SyntaxFactory.UsingDirective(SyntaxFactory.IdentifierName("KenticoCloud.ContentManagement.Models.Items")), SyntaxFactory.UsingDirective(SyntaxFactory.IdentifierName("KenticoCloud.ContentManagement.Models.Assets")) }; var deliveryUsings = new[] { SyntaxFactory.UsingDirective(SyntaxFactory.IdentifierName("KenticoCloud.Delivery")) }; var usings = new[] { SyntaxFactory.UsingDirective(SyntaxFactory.IdentifierName("System")), SyntaxFactory.UsingDirective(SyntaxFactory.IdentifierName("System.Collections.Generic")), }.Concat(cmApi ? cmApiUsings : deliveryUsings).ToArray(); var properties = ClassDefinition.Properties.Select((element, i) => { var property = SyntaxFactory .PropertyDeclaration(SyntaxFactory.ParseTypeName(element.TypeName), element.Identifier) .AddModifiers(SyntaxFactory.Token(SyntaxKind.PublicKeyword)) .AddAccessorListAccessors( SyntaxFactory.AccessorDeclaration(SyntaxKind.GetAccessorDeclaration) .WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.SemicolonToken)), SyntaxFactory.AccessorDeclaration(SyntaxKind.SetAccessorDeclaration) .WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.SemicolonToken)) ); if (cmApi && ClassDefinition.PropertyCodenameConstants.Count > i) { property = property.AddAttributeLists( SyntaxFactory.AttributeList( SyntaxFactory.SingletonSeparatedList( SyntaxFactory.Attribute(SyntaxFactory.IdentifierName("JsonProperty")) .WithArgumentList( SyntaxFactory.AttributeArgumentList( SyntaxFactory.SingletonSeparatedList( SyntaxFactory.AttributeArgument( SyntaxFactory.LiteralExpression( SyntaxKind.StringLiteralExpression, SyntaxFactory.Literal(ClassDefinition .PropertyCodenameConstants[i].Codename))))))))); } return(property); } ).ToArray(); var propertyCodenameConstants = ClassDefinition.PropertyCodenameConstants.Select(element => SyntaxFactory.FieldDeclaration( SyntaxFactory.VariableDeclaration( SyntaxFactory.ParseTypeName("string"), SyntaxFactory.SeparatedList(new[] { SyntaxFactory.VariableDeclarator( SyntaxFactory.Identifier($"{TextHelpers.GetValidPascalCaseIdentifierName(element.Codename)}Codename"), null, SyntaxFactory.EqualsValueClause(SyntaxFactory.LiteralExpression(SyntaxKind.StringLiteralExpression, SyntaxFactory.Literal(element.Codename))) ) }) ) ) .AddModifiers(SyntaxFactory.Token(SyntaxKind.PublicKeyword)) .AddModifiers(SyntaxFactory.Token(SyntaxKind.ConstKeyword)) ).ToArray(); var classDeclaration = SyntaxFactory.ClassDeclaration(ClassDefinition.ClassName) .AddModifiers(SyntaxFactory.Token(SyntaxKind.PublicKeyword)) .AddModifiers(SyntaxFactory.Token(SyntaxKind.PartialKeyword)); if (!CustomPartial && !cmApi) { var classCodenameConstant = SyntaxFactory.FieldDeclaration( SyntaxFactory.VariableDeclaration( SyntaxFactory.ParseTypeName("string"), SyntaxFactory.SeparatedList(new[] { SyntaxFactory.VariableDeclarator( SyntaxFactory.Identifier("Codename"), null, SyntaxFactory.EqualsValueClause(SyntaxFactory.LiteralExpression(SyntaxKind.StringLiteralExpression, SyntaxFactory.Literal(ClassDefinition.Codename))) ) }) ) ) .AddModifiers(SyntaxFactory.Token(SyntaxKind.PublicKeyword)) .AddModifiers(SyntaxFactory.Token(SyntaxKind.ConstKeyword)); classDeclaration = classDeclaration.AddMembers(classCodenameConstant); } if (!cmApi) { classDeclaration = classDeclaration.AddMembers(propertyCodenameConstants); } classDeclaration = classDeclaration.AddMembers(properties); var description = SyntaxFactory.Comment( @"// This code was generated by a cloud-generators-net tool // (see https://github.com/Kentico/cloud-generators-net). // // Changes to this file may cause incorrect behavior and will be lost if the code is regenerated. // For further modifications of the class, create a separate file with the partial class." + Environment.NewLine + Environment.NewLine ); CompilationUnitSyntax cu = SyntaxFactory.CompilationUnit() .AddUsings(usings) .AddMembers( SyntaxFactory.NamespaceDeclaration(SyntaxFactory.IdentifierName(Namespace)) .AddMembers(classDeclaration) ); if (!CustomPartial) { cu = cu.WithLeadingTrivia(description); } AdhocWorkspace cw = new AdhocWorkspace(); return(Formatter.Format(cu, cw).ToFullString()); }
private AttributeSyntax FixIgnoreAttribute() { return(SyntaxFactory.Attribute(Attribute.Name, SyntaxFactory.ParseAttributeArgumentList($"({DefaultReasonMessageFix})"))); }
/// <summary> /// Gets the result syntax tree. /// </summary> public IEnumerable <SyntaxTree> BuildTree(string namespaceName, string className, string fileName) { UseType(BuilderDataContextType); var controlType = ReflectionUtils.IsFullName(ResultControlType) ? "global::" + ResultControlType : ResultControlType; var root = SyntaxFactory.CompilationUnit().WithMembers( SyntaxFactory.NamespaceDeclaration(SyntaxFactory.ParseName(namespaceName)).WithMembers( SyntaxFactory.List <MemberDeclarationSyntax>( new[] { SyntaxFactory.ClassDeclaration(className) .WithModifiers(SyntaxFactory.TokenList(SyntaxFactory.Token(SyntaxKind.PublicKeyword))) .WithBaseList(SyntaxFactory.BaseList( SyntaxFactory.SeparatedList(new BaseTypeSyntax[] { SyntaxFactory.SimpleBaseType( ParseTypeName(typeof(IControlBuilder)) ) }) )) .AddAttributeLists(SyntaxFactory.AttributeList(SyntaxFactory.SeparatedList(new [] { SyntaxFactory.Attribute( SyntaxFactory.ParseName($"global::{typeof(LoadControlBuilderAttribute).FullName}"), SyntaxFactory.AttributeArgumentList(SyntaxFactory.SeparatedList(new [] { SyntaxFactory.AttributeArgument(EmitStringLiteral(fileName)) })) ) }))) .WithMembers( SyntaxFactory.List <MemberDeclarationSyntax>( outputMethods.Select <EmitterMethodInfo, MemberDeclarationSyntax>(m => SyntaxFactory.MethodDeclaration( m.ReturnType, m.Name) .WithModifiers(SyntaxFactory.TokenList(SyntaxFactory.Token(SyntaxKind.PublicKeyword))) .WithParameterList(m.Parameters) .WithBody(SyntaxFactory.Block(m.Statements)) ).Concat(new [] { SyntaxFactory.PropertyDeclaration(ParseTypeName(typeof(Type)), nameof(IControlBuilder.DataContextType)) .WithModifiers(SyntaxFactory.TokenList(SyntaxFactory.Token(SyntaxKind.PublicKeyword))) .WithExpressionBody( SyntaxFactory.ArrowExpressionClause(SyntaxFactory.TypeOfExpression(ParseTypeName(BuilderDataContextType)))) .WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.SemicolonToken)), SyntaxFactory.PropertyDeclaration(ParseTypeName(typeof(Type)), nameof(IControlBuilder.ControlType)) .WithModifiers(SyntaxFactory.TokenList(SyntaxFactory.Token(SyntaxKind.PublicKeyword))) .WithExpressionBody( SyntaxFactory.ArrowExpressionClause(SyntaxFactory.TypeOfExpression(SyntaxFactory.ParseTypeName(controlType)))) .WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.SemicolonToken)), }).Concat(otherDeclarations) ) ) } ) ) ); // WORKAROUND: serializing and parsing the tree is necessary here because Roslyn throws compilation errors when pass the original tree which uses markup controls (they reference in-memory assemblies) // the trees are the same (root2.GetChanges(root) returns empty collection) but without serialization and parsing it does not work //SyntaxTree = CSharpSyntaxTree.ParseText(root.ToString()); //SyntaxTree = root.SyntaxTree; return(new[] { root.SyntaxTree }); }
public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context) { if (context.Diagnostics.Length == 0) { return; } var rootNode = await context.Document.GetSyntaxRootAsync(context.CancellationToken).ConfigureAwait(false); Debug.Assert(context.Diagnostics.Length == 1); var diagnostic = context.Diagnostics[0]; var methodName = diagnostic.Properties[ApiActionsAreAttributeRoutedAnalyzer.MethodNameKey]; var matchedByKeyword = false; foreach (var routeInfo in RouteAttributes) { foreach (var keyword in routeInfo.KeyWords) { // Determine if the method starts with a conventional key and only show relevant routes. // For e.g. FindPetByCategory would result in HttpGet attribute. if (methodName.StartsWith(keyword, StringComparison.Ordinal)) { matchedByKeyword = true; var title = $"Add {routeInfo.Name} attribute"; context.RegisterCodeFix( CodeAction.Create( title, createChangedDocument: cancellationToken => CreateChangedDocumentAsync(routeInfo.Type, cancellationToken), equivalenceKey: title), context.Diagnostics); } } } if (!matchedByKeyword) { foreach (var routeInfo in RouteAttributes) { var title = $"Add {routeInfo.Name} attribute"; context.RegisterCodeFix( CodeAction.Create( title, createChangedDocument: cancellationToken => CreateChangedDocumentAsync(routeInfo.Type, cancellationToken), equivalenceKey: title), context.Diagnostics); } } async Task <Document> CreateChangedDocumentAsync(string attributeName, CancellationToken cancellationToken) { var methodNode = (MethodDeclarationSyntax)rootNode.FindNode(context.Span); var editor = await DocumentEditor.CreateAsync(context.Document, cancellationToken).ConfigureAwait(false); var compilation = editor.SemanticModel.Compilation; var attributeMetadata = compilation.GetTypeByMetadataName(attributeName); var fromRouteAttribute = compilation.GetTypeByMetadataName(TypeNames.FromRouteAttribute); attributeName = attributeMetadata.ToMinimalDisplayString(editor.SemanticModel, methodNode.SpanStart); // Remove the Attribute suffix from type names e.g. "HttpGetAttribute" -> "HttpGet" if (attributeName.EndsWith("Attribute", StringComparison.Ordinal)) { attributeName = attributeName.Substring(0, attributeName.Length - "Attribute".Length); } var method = editor.SemanticModel.GetDeclaredSymbol(methodNode); var attribute = SyntaxFactory.Attribute( SyntaxFactory.ParseName(attributeName)); var route = GetRoute(fromRouteAttribute, method); if (!string.IsNullOrEmpty(route)) { attribute = attribute.AddArgumentListArguments( SyntaxFactory.AttributeArgument( SyntaxFactory.LiteralExpression( SyntaxKind.StringLiteralExpression, SyntaxFactory.Literal(route)))); } editor.AddAttribute(methodNode, attribute); return(editor.GetChangedDocument()); } }
private static string GenerateClassTest(ClassDeclarationSyntax @class) { //Test methods var methodBody = SyntaxFactory.ParseStatement(TestMethodBody); var methods = @class.DescendantNodes().OfType <MethodDeclarationSyntax>(); var members = new List <MemberDeclarationSyntax>(); foreach (var method in methods) { if (!method.Modifiers.Any(SyntaxKind.PublicKeyword)) { continue; } var methodName = method.Identifier.Text; var methodDeclaration = SyntaxFactory .MethodDeclaration(SyntaxFactory.ParseTypeName("void"), methodName + "Test") .AddModifiers(SyntaxFactory.Token(SyntaxKind.PublicKeyword)) .WithBody(SyntaxFactory.Block(methodBody)) .AddAttributeLists(SyntaxFactory.AttributeList(SyntaxFactory.SingletonSeparatedList( SyntaxFactory.Attribute(SyntaxFactory.IdentifierName("Test")) ))); //SingletonSeparatedList singleton? separated? members.Add(methodDeclaration); } //Test class var className = @class.Identifier.Text; var classDeclaration = SyntaxFactory.ClassDeclaration(className + "Tests") .AddModifiers(SyntaxFactory.Token(SyntaxKind.PublicKeyword)) .AddMembers(members.ToArray()) .AddAttributeLists(SyntaxFactory.AttributeList(SyntaxFactory.SingletonSeparatedList( SyntaxFactory.Attribute(SyntaxFactory.IdentifierName("TestFixture")) ))); //namespace, using string sourceNamespace = null; if (@class.TryGetParentSyntax <NamespaceDeclarationSyntax>(out var namespaceDeclarationSyntax)) { sourceNamespace = namespaceDeclarationSyntax.Name.ToString(); } var @namespace = SyntaxFactory .NamespaceDeclaration(SyntaxFactory.ParseName((sourceNamespace ?? "My") + ".Tests")) .AddMembers(classDeclaration); var compilationUnit = SyntaxFactory.CompilationUnit().AddUsings( SyntaxFactory.UsingDirective(SyntaxFactory.ParseName("System")), SyntaxFactory.UsingDirective(SyntaxFactory.ParseName("System.Collections.Generic")), SyntaxFactory.UsingDirective(SyntaxFactory.ParseName("System.Linq")), SyntaxFactory.UsingDirective(SyntaxFactory.ParseName("System.Text")), SyntaxFactory.UsingDirective(SyntaxFactory.ParseName("NUnit.Framework")) ); if (sourceNamespace != null) { compilationUnit = compilationUnit.AddUsings(SyntaxFactory.UsingDirective(SyntaxFactory.ParseName(sourceNamespace))); } //result var code = compilationUnit.AddMembers(@namespace); return(code.NormalizeWhitespace().ToFullString()); }
private SyntaxNode CreateAttributeListForSal(AttributeListSyntax cppAttrList) { ParameterSyntax paramNode = (ParameterSyntax)cppAttrList.Parent; bool marshalAsAdded = this.nodesWithMarshalAs.Contains(paramNode); AttributeSyntax cppAttr = cppAttrList.Attributes[0]; List <AttributeSyntax> attributesList = new List <AttributeSyntax>(); string salText = cppAttr.ArgumentList.Arguments[0].ToString(); salText = salText.Substring(1, salText.Length - 2); string nativeArrayInfoParams = null; bool isIn = false; bool isOut = false; bool isOpt = false; bool isComOutPtr = false; bool isRetVal = false; bool isNullNullTerminated; bool? pre = null; bool? post = null; var salAttrs = GetSalAttributes(salText); isNullNullTerminated = salAttrs.Any(a => a.Name == "SAL_name" && a.P1 == "_NullNull_terminated_"); foreach (var salAttr in salAttrs) { if (salAttr.Name == "SAL_name") { if (salAttr.P1.StartsWith("_COM_Outptr")) { isComOutPtr = true; continue; } else if (salAttr.P1.StartsWith("_Outptr_") && !isComOutPtr) { isOut = true; continue; } } if (salAttr.Name == "SAL_null" && salAttr.P1 == "__maybe") { isOpt = true; continue; } if (salAttr.Name == "SAL_retval") { isRetVal = true; continue; } if (salAttr.Name == "SAL_pre") { pre = true; continue; } if (salAttr.Name == "SAL_post") { pre = false; post = true; continue; } if (salAttr.Name == "SAL_end") { pre = post = false; } if (salAttr.Name == "SAL_valid") { if (pre.HasValue && pre.Value) { isIn = true; } else if (post.HasValue && post.Value) { isOut = true; } else { isIn = isOut = true; } continue; } if (salAttr.Name == "SAL_name" && salAttr.P1 == "_Post_valid_") { isOut = true; continue; } if (!marshalAsAdded && (salAttr.Name == "SAL_writableTo" || salAttr.Name == "SAL_readableTo") && pre.HasValue && pre.Value) { nativeArrayInfoParams = GetArrayMarshalAsFromP1(paramNode, salAttr.P1); if (!string.IsNullOrEmpty(nativeArrayInfoParams)) { marshalAsAdded = true; } continue; } } // If we didn't add marshal as yet, try again without using pre if (!marshalAsAdded) { var salAttr = salAttrs.FirstOrDefault(attr => attr.Name == "SAL_readableTo" || attr.Name == "SAL_writeableTo"); if (salAttr != null) { nativeArrayInfoParams = GetArrayMarshalAsFromP1(paramNode, salAttr.P1); if (!string.IsNullOrEmpty(nativeArrayInfoParams)) { marshalAsAdded = true; } } } if (!string.IsNullOrEmpty(nativeArrayInfoParams)) { var attrName = SyntaxFactory.ParseName("NativeArrayInfo"); var args = SyntaxFactory.ParseAttributeArgumentList(nativeArrayInfoParams.ToString()); var finalAttr = SyntaxFactory.Attribute(attrName, args); attributesList.Add(finalAttr); } if (isIn) { attributesList.Add(SyntaxFactory.Attribute(SyntaxFactory.ParseName("In"))); } if (isComOutPtr) { attributesList.Add(SyntaxFactory.Attribute(SyntaxFactory.ParseName("ComOutPtr"))); } else if (isOut) { attributesList.Add(SyntaxFactory.Attribute(SyntaxFactory.ParseName("Out"))); } if (isOpt) { attributesList.Add(SyntaxFactory.Attribute(SyntaxFactory.ParseName("Optional"))); } if (isNullNullTerminated) { attributesList.Add(SyntaxFactory.Attribute(SyntaxFactory.ParseName("NullNullTerminated"))); } if (isRetVal) { attributesList.Add(SyntaxFactory.Attribute(SyntaxFactory.ParseName("RetVal"))); } if (attributesList.Count == 0) { return(null); } return(SyntaxFactory.AttributeList(SyntaxFactory.SeparatedList(attributesList))); string GetArrayMarshalAsFromP1(ParameterSyntax paramNode, string p1Text) { ParameterListSyntax parameterListNode = (ParameterListSyntax)paramNode.Parent; var match = elementCountRegex.Match(p1Text); StringBuilder ret = new StringBuilder("("); if (match.Success) { string sizeOrParamName = match.Groups[1].Value; if (int.TryParse(sizeOrParamName, out int size)) { // Don't bother marking this as an array if it only has 1 if (size == 1) { return(string.Empty); } if (ret.Length != 1) { ret.Append(", "); } ret.Append($"SizeConst = {size}"); } else { sizeOrParamName = sizeOrParamName.Replace("*", string.Empty); for (int i = 0; i < parameterListNode.Parameters.Count; i++) { if (parameterListNode.Parameters[i].Identifier.ValueText == sizeOrParamName) { if (ret.Length != 1) { ret.Append(", "); } string propName = p1Text.StartsWith("elementCount") ? "SizeParamIndex" : "BytesParamIndex"; ret.Append($"{propName} = {i}"); break; } } } } else { // If it didn't match the regex and we don't see inexpressibleCount, we can't do // anything but return an empty string, because we don't know how to interpret it if (!p1Text.StartsWith("inexpressibleCount")) { ret = new StringBuilder(); } } if (ret.Length > 1) { ret.Append(')'); return(ret.ToString()); } return(string.Empty); } IEnumerable <SalAttribute> GetSalAttributes(string salArgsText) { foreach (var attr in salArgsText.Split('^')) { var salAttr = SalAttribute.CreateFromCppAttribute(attr); if (salAttr != null) { yield return(salAttr); } } } }
private static SyntaxTree GetAssemblyInfo(AssemblyInfo info) { return(SyntaxFactory.CompilationUnit() // start: add using patterns code and set custom qualified name for assembly basic head info, example as /* * using System.Reflection * using System.Runtime.InteropServices * using System.Runtime.Versioning */ .WithUsings( SyntaxFactory.List( new[] { SyntaxFactory.UsingDirective(SyntaxFactory.QualifiedName( SyntaxFactory.IdentifierName("System"), SyntaxFactory.IdentifierName("Reflection"))), SyntaxFactory.UsingDirective(SyntaxFactory.QualifiedName( SyntaxFactory.QualifiedName(SyntaxFactory.IdentifierName("System"), SyntaxFactory.IdentifierName("Runtime")), SyntaxFactory.IdentifierName("InteropServices"))), SyntaxFactory.UsingDirective(SyntaxFactory.QualifiedName( SyntaxFactory.QualifiedName(SyntaxFactory.IdentifierName("System"), SyntaxFactory.IdentifierName("Runtime")), SyntaxFactory.IdentifierName("Versioning"))) })) .WithAttributeLists( SyntaxFactory.List( new[] { SyntaxFactory.AttributeList(SyntaxFactory.SingletonSeparatedList(SyntaxFactory .Attribute(SyntaxFactory.IdentifierName("TargetFramework")) .WithArgumentList(SyntaxFactory.AttributeArgumentList( SyntaxFactory.SeparatedList <AttributeArgumentSyntax>( new SyntaxNodeOrToken[] { SyntaxFactory.AttributeArgument( SyntaxFactory.LiteralExpression(SyntaxKind.StringLiteralExpression, SyntaxFactory.Literal(".NETFramework,Version=v4.5"))), SyntaxFactory.Token(SyntaxKind.CommaToken), SyntaxFactory .AttributeArgument(SyntaxFactory.LiteralExpression( SyntaxKind.StringLiteralExpression, SyntaxFactory.Literal(".NET Framework 4.5"))) .WithNameEquals(SyntaxFactory.NameEquals( SyntaxFactory.IdentifierName("FrameworkDisplayName"))) }))))) .WithTarget( SyntaxFactory.AttributeTargetSpecifier( SyntaxFactory.Token(SyntaxKind.AssemblyKeyword))), SyntaxFactory.AttributeList(SyntaxFactory.SingletonSeparatedList(SyntaxFactory .Attribute(SyntaxFactory.IdentifierName("AssemblyTitle")) .WithArgumentList( SyntaxFactory.AttributeArgumentList(SyntaxFactory.SingletonSeparatedList( SyntaxFactory.AttributeArgument( SyntaxFactory.LiteralExpression(SyntaxKind.StringLiteralExpression, SyntaxFactory.Literal(info.Title)))))))) .WithTarget( SyntaxFactory.AttributeTargetSpecifier( SyntaxFactory.Token(SyntaxKind.AssemblyKeyword))), SyntaxFactory.AttributeList(SyntaxFactory.SingletonSeparatedList(SyntaxFactory .Attribute(SyntaxFactory.IdentifierName("AssemblyProduct")) .WithArgumentList( SyntaxFactory.AttributeArgumentList(SyntaxFactory.SingletonSeparatedList( SyntaxFactory.AttributeArgument( SyntaxFactory.LiteralExpression(SyntaxKind.StringLiteralExpression, SyntaxFactory.Literal(info.Product)))))))) .WithTarget( SyntaxFactory.AttributeTargetSpecifier( SyntaxFactory.Token(SyntaxKind.AssemblyKeyword))), SyntaxFactory.AttributeList(SyntaxFactory.SingletonSeparatedList(SyntaxFactory .Attribute(SyntaxFactory.IdentifierName("AssemblyCopyright")) .WithArgumentList( SyntaxFactory.AttributeArgumentList(SyntaxFactory.SingletonSeparatedList( SyntaxFactory.AttributeArgument( SyntaxFactory.LiteralExpression(SyntaxKind.StringLiteralExpression, SyntaxFactory.Literal(info.Copyright)))))))) .WithTarget( SyntaxFactory.AttributeTargetSpecifier( SyntaxFactory.Token(SyntaxKind.AssemblyKeyword))), SyntaxFactory.AttributeList(SyntaxFactory.SingletonSeparatedList(SyntaxFactory .Attribute(SyntaxFactory.IdentifierName("ComVisible")) .WithArgumentList( SyntaxFactory.AttributeArgumentList(SyntaxFactory.SingletonSeparatedList( SyntaxFactory.AttributeArgument( SyntaxFactory.LiteralExpression(info.ComVisible ? SyntaxKind.TrueLiteralExpression : SyntaxKind.FalseLiteralExpression))))))) .WithTarget( SyntaxFactory.AttributeTargetSpecifier( SyntaxFactory.Token(SyntaxKind.AssemblyKeyword))), SyntaxFactory.AttributeList(SyntaxFactory.SingletonSeparatedList(SyntaxFactory .Attribute(SyntaxFactory.IdentifierName("Guid")) .WithArgumentList( SyntaxFactory.AttributeArgumentList(SyntaxFactory.SingletonSeparatedList( SyntaxFactory.AttributeArgument( SyntaxFactory.LiteralExpression(SyntaxKind.StringLiteralExpression, SyntaxFactory.Literal(info.Guid)))))))) .WithTarget( SyntaxFactory.AttributeTargetSpecifier( SyntaxFactory.Token(SyntaxKind.AssemblyKeyword))), SyntaxFactory.AttributeList(SyntaxFactory.SingletonSeparatedList(SyntaxFactory .Attribute(SyntaxFactory.IdentifierName("AssemblyVersion")) .WithArgumentList( SyntaxFactory.AttributeArgumentList(SyntaxFactory.SingletonSeparatedList( SyntaxFactory.AttributeArgument( SyntaxFactory.LiteralExpression(SyntaxKind.StringLiteralExpression, SyntaxFactory.Literal(info.Version)))))))) .WithTarget( SyntaxFactory.AttributeTargetSpecifier( SyntaxFactory.Token(SyntaxKind.AssemblyKeyword))), SyntaxFactory.AttributeList(SyntaxFactory.SingletonSeparatedList(SyntaxFactory .Attribute(SyntaxFactory.IdentifierName("AssemblyFileVersion")) .WithArgumentList( SyntaxFactory.AttributeArgumentList(SyntaxFactory.SingletonSeparatedList( SyntaxFactory.AttributeArgument( SyntaxFactory.LiteralExpression(SyntaxKind.StringLiteralExpression, SyntaxFactory.Literal(info.FileVersion)))))))) .WithTarget( SyntaxFactory.AttributeTargetSpecifier( SyntaxFactory.Token(SyntaxKind.AssemblyKeyword))) })) .NormalizeWhitespace() .SyntaxTree); }
public override SyntaxNode VisitFieldDeclaration(FieldDeclarationSyntax node) { string fullName = GetFullName(node); this.GetRemapInfo(fullName, out var listAttributes, out string newType, out string newName); // ClangSharp mistakenly emits string[] for WCHAR[] Foo = "Bar". // Change it to string if (newType == null && node.Declaration.Type.ToString() == "string[]") { newType = "string"; } // Turn public static readonly Guids into string constants with an attribute // to signal language projections to turn them into Guid constants. Guid constants // aren't allowed in metadata, requiring us to surface them this way if (node.Modifiers.ToString() == "public static readonly" && node.Declaration.Type.ToString() == "Guid") { // We're ignoring all the IID_ constants, assuming projections can get them from the interfaces // directly if (fullName.StartsWith("IID_")) { return(null); } string guidVal = null; if (node.Declaration.Variables.First().Initializer.Value is ObjectCreationExpressionSyntax objCreationSyntax) { var args = objCreationSyntax.ArgumentList.Arguments; if (args.Count == 11) { uint p0 = EncodeHelpers.ParseHex(args[0].ToString()); ushort p1 = (ushort)EncodeHelpers.ParseHex(args[1].ToString()); ushort p2 = (ushort)EncodeHelpers.ParseHex(args[2].ToString()); byte p3 = (byte)EncodeHelpers.ParseHex(args[3].ToString()); byte p4 = (byte)EncodeHelpers.ParseHex(args[4].ToString()); byte p5 = (byte)EncodeHelpers.ParseHex(args[5].ToString()); byte p6 = (byte)EncodeHelpers.ParseHex(args[6].ToString()); byte p7 = (byte)EncodeHelpers.ParseHex(args[7].ToString()); byte p8 = (byte)EncodeHelpers.ParseHex(args[8].ToString()); byte p9 = (byte)EncodeHelpers.ParseHex(args[9].ToString()); byte p10 = (byte)EncodeHelpers.ParseHex(args[10].ToString()); guidVal = new Guid(p0, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10).ToString(); } else if (objCreationSyntax.ArgumentList.Arguments.Count == 1) { guidVal = EncodeHelpers.RemoveQuotes(objCreationSyntax.ArgumentList.Arguments[0].ToString()); } } if (guidVal == null) { return(node); } var variableDeclaration = SyntaxFactory.VariableDeclaration(SyntaxFactory.ParseTypeName("string") .WithTrailingTrivia(SyntaxFactory.Space)) .AddVariables( SyntaxFactory.VariableDeclarator(fullName) .WithInitializer(SyntaxFactory.EqualsValueClause(SyntaxFactory.ParseExpression($"\"{guidVal}\"")))); var attrListSyntax = SyntaxFactory.SingletonSeparatedList <AttributeSyntax>(SyntaxFactory.Attribute(SyntaxFactory.ParseName("Windows.Win32.Interop.GuidConst"))); var fieldDeclaration = SyntaxFactory.FieldDeclaration(variableDeclaration) .AddModifiers(SyntaxFactory.Token(SyntaxKind.PublicKeyword).WithTrailingTrivia(SyntaxFactory.Space), SyntaxFactory.Token(SyntaxKind.ConstKeyword).WithTrailingTrivia(SyntaxFactory.Space)) .AddAttributeLists(SyntaxFactory.AttributeList(attrListSyntax)) .WithLeadingTrivia(SyntaxFactory.CarriageReturnLineFeed) .WithTrailingTrivia(SyntaxFactory.CarriageReturnLineFeed); return(fieldDeclaration); } node = (FieldDeclarationSyntax)base.VisitFieldDeclaration(node); if (listAttributes != null) { foreach (var attrNode in listAttributes) { var attrListNode = SyntaxFactory.AttributeList( SyntaxFactory.SingletonSeparatedList <AttributeSyntax>(attrNode)); node = node.WithAttributeLists(node.AttributeLists.Add(attrListNode)); } } var firstVar = node.Declaration.Variables.First(); if (newName != null) { var newVar = SyntaxFactory.VariableDeclarator(SyntaxFactory.Identifier(newName)); node = node.ReplaceNode(firstVar, newVar); } if (newType != null) { node = node.WithDeclaration(node.Declaration.WithType(SyntaxFactory.ParseTypeName(newType).WithTrailingTrivia(SyntaxFactory.Space))); } return(node); }
public static AttributeSyntax Attribute(string name) { return(SyntaxFactory.Attribute(IdentifierName(name))); }
private async Task <bool> TryAddCategoryToTestMethod(RoslynNode roslynNode, ISymbol method, string category, bool recursive) { if (method == null) { throw new ArgumentNullException(nameof(method)); } IEnumerable <ISymbol> testMethods; if (!HasAttribute(method, ATTRIBUTE_TEST_METHOD)) { if (recursive == true) { testMethods = await FindReferencedTestMethods(method).ConfigureAwait(false); } else { testMethods = Array.Empty <ISymbol>(); } } else { testMethods = new ISymbol[] { method }; } foreach (var testMethod in testMethods) { var attrArgument = SyntaxFactory.AttributeArgument(SyntaxFactory.LiteralExpression(SyntaxKind.StringLiteralExpression, SyntaxFactory.Literal(category))); var attrList = SyntaxFactory.AttributeList( SyntaxFactory.SingletonSeparatedList( SyntaxFactory.Attribute( SyntaxFactory.IdentifierName(ATTRIBUTE_TEST_CATEGORY), SyntaxFactory.AttributeArgumentList( SyntaxFactory.SeparatedList(new[] { attrArgument }) ) ) ) ); // We do know that methds only can be declared once, but for the sake of // completeness, let's assume that can have more than one declaration (because partial classes can) foreach (var declaration in testMethod.DeclaringSyntaxReferences) { var node = declaration.GetSyntax(); var methodDeclaration = node as MethodDeclarationSyntax; var newAttributesList = methodDeclaration.AttributeLists.Add(attrList); var newNode = declaration.SyntaxTree.GetRoot().ReplaceNode( methodDeclaration, methodDeclaration.WithAttributeLists(newAttributesList) ); var documentId = roslynNode.Project.GetDocumentId(declaration.SyntaxTree); if (documentId != null) { _solution = _solution.WithDocumentSyntaxRoot(documentId, newNode); } else { _logger.Debug($"Document not found for '{declaration.SyntaxTree.FilePath}' for project '{roslynNode.Project.Name}'. Skiping declaration."); } } } return(testMethods.Any()); }
public override SyntaxNode VisitInterfaceDefinition([NotNull] GrammarParser.InterfaceDefinitionContext context) { if (context == null) { return(null); } var name = SyntaxFactory.IdentifierName(context.name().GetText()); var interfaceDec = SyntaxFactory.InterfaceDeclaration(name.GetFirstToken()) .AddAttributeLists(SyntaxFactory.AttributeList( SyntaxFactory.SingletonSeparatedList(SyntaxFactory.Attribute(SyntaxFactory.IdentifierName("Rpc"))))) .AddModifiers(SyntaxFactory.Token(SyntaxKind.PublicKeyword)) .AddMembers(context.methodDefinition() .Select(VisitMethodDefinition) .ToMemberDeclarationSyntaxArray()); return(interfaceDec); }
private static SyntaxTree CreateClassSyntaxTree(TestClass testClass) { var attributes = testClass.Attributes.Select(i => CSharpSyntaxTree.ParseText(i).GetRoot().DescendantNodes().OfType <AttributeSyntax>().Single()).ToList(); return (SyntaxFactory.CompilationUnit() .AddUsings(GetUsingDirectives().ToArray()) .AddMembers( SyntaxFactory.NamespaceDeclaration(SyntaxFactory.IdentifierName(testClass.NamespaceName)) .AddMembers( SyntaxFactory.ClassDeclaration(testClass.ClassName) .AddModifiers(SyntaxFactory.Token(SyntaxKind.PublicKeyword)) .AddAttributeLists(SyntaxFactory.AttributeList(SyntaxFactory.SingletonSeparatedList(SyntaxFactory.Attribute(SyntaxFactory.IdentifierName("TestFixtureAttribute"))))) .AddAttributeLists(SyntaxFactory.AttributeList(SyntaxFactory.SeparatedList(attributes))) // Ctor .AddMembers( SyntaxFactory.ConstructorDeclaration(testClass.ClassName) .AddModifiers(SyntaxFactory.Token(SyntaxKind.PublicKeyword)) .AddBodyStatements( testClass.CtorMethods.Select(CreateMethodStatement).ToArray())) // Methods .AddMembers(testClass.CtorMethods.Concat(testClass.Methods).Select(CreateMethod).ToArray()))).SyntaxTree); }
/// <summary> /// Generates the attribute on the class or method. /// </summary> public static AttributeSyntax GenerateAttribute(Type type, params ExpressionSyntax[] parameters) { return(SyntaxFactory.Attribute(SyntaxFactory.ParseName(type.FullName), SyntaxFactory.AttributeArgumentList(SyntaxFactory.SeparatedList(parameters.Select(SyntaxFactory.AttributeArgument))) )); }
public SourceText GetTableTypeText(Definition.Schema schema, Definition.TableType tableType) { var rootDir = _output.GetOutputRootDir(); var fileContent = File.ReadAllText(Path.Combine(rootDir.FullName, "DataContext", "TableTypes", "TableType.cs")); var tree = CSharpSyntaxTree.ParseText(fileContent); var root = tree.GetCompilationUnitRoot(); // Replace Namespace if (_configFile.Config.Project.Role.Kind == ERoleKind.Lib) { root = root.ReplaceNamespace(ns => ns.Replace("Source.DataContext", _configFile.Config.Project.Output.Namespace).Replace("Schema", schema.Name)); } else { root = root.ReplaceNamespace(ns => ns.Replace("Source", _configFile.Config.Project.Output.Namespace).Replace("Schema", schema.Name)); } // If its an extension, add usings for the lib if (_configFile.Config.Project.Role.Kind == ERoleKind.Extension) { var libModelUsingDirective = SyntaxFactory.UsingDirective(SyntaxFactory.ParseName($"{_configFile.Config.Project.Role.LibNamespace}.TableTypes")); root = root.AddUsings(libModelUsingDirective).NormalizeWhitespace(); } var nsNode = (NamespaceDeclarationSyntax)root.Members[0]; // Replace ClassName var classNode = (ClassDeclarationSyntax)nsNode.Members[0]; var classIdentifier = SyntaxFactory.ParseToken($"{classNode.Identifier.ValueText.Replace("TableType", $"{GetTypeNameForTableType(tableType)}")} "); classNode = classNode.WithIdentifier(classIdentifier); root = root.ReplaceNode(nsNode, nsNode.AddMembers(classNode)); // Create Properties if (tableType.Columns != null) { foreach (var column in tableType.Columns) { nsNode = (NamespaceDeclarationSyntax)root.Members[0]; classNode = (ClassDeclarationSyntax)nsNode.Members[1]; var propertyNode = (PropertyDeclarationSyntax)classNode.Members[0]; var propertyIdentifier = SyntaxFactory.ParseToken($" {column.Name} "); propertyNode = propertyNode .WithType(ParseTypeFromSqlDbTypeName(column.SqlTypeName, column.IsNullable ?? false)); propertyNode = propertyNode .WithIdentifier(propertyIdentifier); // Add Attribute for NVARCHAR with MaxLength if (column.SqlTypeName.Equals(SqlDbType.NVarChar.ToString(), StringComparison.InvariantCultureIgnoreCase) && column.MaxLength.HasValue) { var attributes = propertyNode.AttributeLists.Add( SyntaxFactory.AttributeList(SyntaxFactory.SingletonSeparatedList <AttributeSyntax>( SyntaxFactory.Attribute(SyntaxFactory.IdentifierName("MaxLength"), SyntaxFactory.ParseAttributeArgumentList($"({column.MaxLength})")) )).NormalizeWhitespace()); propertyNode = propertyNode.WithAttributeLists(attributes); } root = root.AddProperty(ref classNode, propertyNode); } } // Remove template Property nsNode = (NamespaceDeclarationSyntax)root.Members[0]; classNode = (ClassDeclarationSyntax)nsNode.Members[1]; root = root.ReplaceNode(classNode, classNode.WithMembers(new SyntaxList <MemberDeclarationSyntax>(classNode.Members.Cast <PropertyDeclarationSyntax>().Skip(1)))); // Remove template Class nsNode = (NamespaceDeclarationSyntax)root.Members[0]; root = root.ReplaceNode(nsNode, nsNode.WithMembers(new SyntaxList <MemberDeclarationSyntax>(nsNode.Members.Cast <ClassDeclarationSyntax>().Skip(1)))); return(root.NormalizeWhitespace().GetText()); }
private static AttributeSyntax GenerateAttribute(AttributeData attribute, CodeGenerationOptions options) { if (!options.MergeAttributes) { var reusableSyntax = GetReuseableSyntaxNodeForAttribute <AttributeSyntax>(attribute, options); if (reusableSyntax != null) { return(reusableSyntax); } } var attributeArguments = GenerateAttributeArgumentList(attribute); return(!(attribute.AttributeClass.GenerateTypeSyntax() is NameSyntax nameSyntax) ? null : SyntaxFactory.Attribute(nameSyntax, attributeArguments)); }
public SourceText GetInputTextForStoredProcedure(Definition.Schema schema, Definition.StoredProcedure storedProcedure) { var rootDir = _output.GetOutputRootDir(); var fileContent = File.ReadAllText(Path.Combine(rootDir.FullName, "DataContext", "Inputs", "Input.cs")); var tree = CSharpSyntaxTree.ParseText(fileContent); var root = tree.GetCompilationUnitRoot(); // If Inputs contains a TableType, add using for TableTypes var schemesForTableTypes = storedProcedure.Input.Where(i => i.IsTableType ?? false) .GroupBy(t => (t.TableTypeSchemaName, t.TableTypeName), (key, group) => new { TableTypeSchemaName = key.TableTypeSchemaName, Result = group.First() }).Select(g => g.Result).ToList(); var tableTypeSchemas = storedProcedure.Input.Where(i => i.IsTableType ?? false) .GroupBy(t => t.TableTypeSchemaName, (key, group) => key).ToList(); foreach (var tableTypeSchema in tableTypeSchemas) { var tableTypeSchemaConfig = _configFile.Config.Schema.Find(s => s.Name.Equals(tableTypeSchema)); // is schema of table type ignored and its an extension? var useFromLib = tableTypeSchemaConfig?.Status != SchemaStatusEnum.Build && _configFile.Config.Project.Role.Kind == ERoleKind.Extension; var paramUsingDirective = useFromLib ? SyntaxFactory.UsingDirective(SyntaxFactory.ParseName($"{_configFile.Config.Project.Role.LibNamespace}.TableTypes.{tableTypeSchema.FirstCharToUpper()}")) : _configFile.Config.Project.Role.Kind == ERoleKind.Lib ? SyntaxFactory.UsingDirective(SyntaxFactory.ParseName($"{_configFile.Config.Project.Output.Namespace}.TableTypes.{tableTypeSchema.FirstCharToUpper()}")) : SyntaxFactory.UsingDirective(SyntaxFactory.ParseName($"{_configFile.Config.Project.Output.Namespace}.DataContext.TableTypes.{tableTypeSchema.FirstCharToUpper()}")); root = root.AddUsings(paramUsingDirective); } // Replace Namespace if (_configFile.Config.Project.Role.Kind == ERoleKind.Lib) { root = root.ReplaceNamespace(ns => ns.Replace("Source.DataContext", _configFile.Config.Project.Output.Namespace).Replace("Schema", schema.Name)); } else { root = root.ReplaceNamespace(ns => ns.Replace("Source", _configFile.Config.Project.Output.Namespace).Replace("Schema", schema.Name)); } // Replace ClassName root = root.ReplaceClassName(ci => ci.Replace("Input", $"{storedProcedure.Name}Input")); var nsNode = (NamespaceDeclarationSyntax)root.Members[0]; var classNode = (ClassDeclarationSyntax)nsNode.Members[0]; // Create obsolete constructor var obsoleteContructor = classNode.CreateConstructor($"{storedProcedure.Name}Input"); root = root.AddObsoleteAttribute(ref obsoleteContructor, "This empty contructor will be removed in vNext. Please use constructor with parameters."); root = root.AddConstructor(ref classNode, obsoleteContructor); nsNode = (NamespaceDeclarationSyntax)root.Members[0]; classNode = (ClassDeclarationSyntax)nsNode.Members[0]; var inputs = storedProcedure.Input.Where(i => !i.IsOutput).ToList(); // Constructor with params var constructor = classNode.CreateConstructor($"{storedProcedure.Name}Input"); var parameters = inputs.Select(input => { return(SyntaxFactory.Parameter(SyntaxFactory.Identifier(GetIdentifierFromSqlInputTableType(input.Name))) .WithType( input.IsTableType ?? false ? GetTypeSyntaxForTableType(input) : ParseTypeFromSqlDbTypeName(input.SqlTypeName, input.IsNullable ?? false) )); }).ToArray(); var constructorParams = constructor.ParameterList.AddParameters(parameters); constructor = constructor.WithParameterList(constructorParams); foreach (var input in inputs) { var constructorStatement = ExpressionHelper.AssignmentStatement(TokenHelper.Parse(input.Name).ToString(), GetIdentifierFromSqlInputTableType(input.Name)); var newStatements = constructor.Body.Statements.Add(constructorStatement); constructor = constructor.WithBody(constructor.Body.WithStatements(newStatements)); } root = root.AddConstructor(ref classNode, constructor); nsNode = (NamespaceDeclarationSyntax)root.Members[0]; classNode = (ClassDeclarationSyntax)nsNode.Members[0]; // Generate Properies // https://stackoverflow.com/questions/45160694/adding-new-field-declaration-to-class-with-roslyn foreach (var item in storedProcedure.Input) { nsNode = (NamespaceDeclarationSyntax)root.Members[0]; classNode = (ClassDeclarationSyntax)nsNode.Members[0]; var isTableType = item.IsTableType ?? false; var propertyType = isTableType ? GetTypeSyntaxForTableType(item) : ParseTypeFromSqlDbTypeName(item.SqlTypeName, item.IsNullable ?? false); var propertyNode = classNode.CreateProperty(propertyType, item.Name); if (!isTableType) { // Add Attribute for NVARCHAR with MaxLength if ((item.SqlTypeName?.Equals(SqlDbType.NVarChar.ToString(), StringComparison.InvariantCultureIgnoreCase) ?? false) && item.MaxLength.HasValue) { var attributes = propertyNode.AttributeLists.Add( SyntaxFactory.AttributeList(SyntaxFactory.SingletonSeparatedList <AttributeSyntax>( SyntaxFactory.Attribute(SyntaxFactory.IdentifierName("MaxLength"), SyntaxFactory.ParseAttributeArgumentList($"({item.MaxLength})")) )).NormalizeWhitespace()); propertyNode = propertyNode.WithAttributeLists(attributes); } } root = root.AddProperty(ref classNode, propertyNode); } return(root.NormalizeWhitespace().GetText()); }
private IEnumerable <(StatementSyntax Syntax, bool IsFundingLines, string @namespace)> CreateProperties(IEnumerable <string> namespaces) { yield return(CreateProperty("Provider"), false, null); yield return(CreateProperty("Datasets"), false, null); SyntaxList <AttributeListSyntax> list = new SyntaxList <AttributeListSyntax>(SyntaxFactory.AttributeList( SyntaxFactory.SingletonSeparatedList( SyntaxFactory.Attribute(null, SyntaxFactory.IdentifierName("IsAggregable"), SyntaxFactory.ArgumentList( SyntaxFactory.SeparatedList <ArgumentSyntax>(new[] { SyntaxFactory.SimpleArgument( SyntaxFactory.NameColonEquals(SyntaxFactory.IdentifierName("IsAggregable")), SyntaxFactory.LiteralExpression( SyntaxKind.StringLiteralExpression, SyntaxFactory.Literal(@"True")) ) })))))); yield return(CreateProperty("Calculations", "AdditionalCalculations", list), false, null); foreach (var @namespace in namespaces) { yield return(CreateProperty(@namespace, $"{@namespace}Calculations", list), false, @namespace); yield return(CreateProperty("FundingLines", $"{@namespace}FundingLines"), true, @namespace); } }
public MethodDeclarationSyntax GenerateUnitTestMethodDeclaration(string returnTypeName, SyntaxTokenList modifiers, string methodName, string testFramework, GeneratedTest generatedTestModel) { var annotation = "nunit".Equals(testFramework) ? "Test" : "Fact"; var bodyStatements = new List <StatementSyntax>(); var addedArrange = false; if (!string.IsNullOrWhiteSpace(generatedTestModel.ReturnType)) { bodyStatements.Add(SyntaxFactory.ParseStatement($"var expected = default({generatedTestModel.ReturnType});\n").WithLeadingTrivia(SyntaxFactory.Comment("//Arrange\n"))); addedArrange = true; } var methodParams = ""; if (generatedTestModel.MethodParameters != null && generatedTestModel.MethodParameters.Any()) { foreach (var parameter in generatedTestModel.MethodParameters) { if (!addedArrange) { bodyStatements.Add(SyntaxFactory.ParseStatement($"var {parameter.Name} = default({parameter.ClassName});\n").WithLeadingTrivia(SyntaxFactory.Comment("//Arrange\n"))); addedArrange = true; } else { bodyStatements.Add(SyntaxFactory.ParseStatement($"var {parameter.Name} = default({parameter.ClassName});\n")); } methodParams += $"{parameter.Name}, "; } } var ctorParams = ""; if (generatedTestModel.ClassConstructorParameters != null && generatedTestModel.ClassConstructorParameters.Any()) { foreach (var parameter in generatedTestModel.ClassConstructorParameters) { if (!addedArrange) { if (parameter.IsInterface) { bodyStatements.Add(SyntaxFactory.ParseStatement($"var {parameter.Name} = new Mock<{parameter.ClassName}>();\n").WithLeadingTrivia(SyntaxFactory.Comment("//Arrange\n"))); } else { bodyStatements.Add(SyntaxFactory.ParseStatement($"var {parameter.Name} = default({parameter.ClassName});\n").WithLeadingTrivia(SyntaxFactory.Comment("//Arrange\n"))); } addedArrange = true; } else { if (parameter.IsInterface) { bodyStatements.Add(SyntaxFactory.ParseStatement($"var {parameter.Name} = new Mock<{parameter.ClassName}>();\n")); } else { bodyStatements.Add(SyntaxFactory.ParseStatement($"var {parameter.Name} = default({parameter.ClassName});\n")); } } ctorParams += parameter.IsInterface ? $"{parameter.Name}.Object, " : $"{parameter.Name}, "; } } var classCtor = SyntaxFactory.ParseStatement($"var vm = new {generatedTestModel.ClassName}({ctorParams.TrimEnd(' ').TrimEnd(',')});\n").WithTrailingTrivia(SyntaxFactory.CarriageReturnLineFeed); bodyStatements.Add(classCtor); var resultSection = string.IsNullOrWhiteSpace(generatedTestModel.ReturnType) ? "" : "var result = "; var awaitSection = generatedTestModel.IsTask ? "await " : ""; bodyStatements.Add(SyntaxFactory.ParseStatement($"{resultSection}{awaitSection}vm.{generatedTestModel.MethodName}({methodParams.TrimEnd(' ').TrimEnd(',')});\n").WithLeadingTrivia(SyntaxFactory.Comment("//Act\n"))); //Generate the assert section if ("nunit".Equals(testFramework)) { if (!string.IsNullOrWhiteSpace(generatedTestModel.ReturnType)) { bodyStatements.Add(SyntaxFactory.ParseStatement("Assert.That(expected == result);\n").WithLeadingTrivia(SyntaxFactory.Comment("//Assert\n"))); } else { bodyStatements.Add(SyntaxFactory.ParseStatement("Assert.That(true);\n").WithLeadingTrivia(SyntaxFactory.Comment("//Assert\n"))); } } else { if (!string.IsNullOrWhiteSpace(generatedTestModel.ReturnType)) { bodyStatements.Add(SyntaxFactory.ParseStatement($"Assert.Equal<{generatedTestModel.ReturnType}>(expected, result);\n").WithLeadingTrivia(SyntaxFactory.Comment("//Assert\n"))); } else { bodyStatements.Add(SyntaxFactory.ParseStatement("Assert.True(true);\n").WithLeadingTrivia(SyntaxFactory.Comment("//Assert\n"))); } } var method = SyntaxFactory.MethodDeclaration(attributeLists: SyntaxFactory.List <AttributeListSyntax>(), modifiers: modifiers, returnType: SyntaxFactory.ParseTypeName(returnTypeName), explicitInterfaceSpecifier: null, identifier: SyntaxFactory.Identifier(methodName), typeParameterList: null, parameterList: SyntaxFactory.ParameterList(), constraintClauses: SyntaxFactory.List <TypeParameterConstraintClauseSyntax>(), body: SyntaxFactory.Block(bodyStatements), semicolonToken: SyntaxFactory.Token(SyntaxKind.None)) // Annotate that this node should be formatted .WithAdditionalAnnotations(Formatter.Annotation) .WithAttributeLists( SyntaxFactory.SingletonList( SyntaxFactory.AttributeList( SyntaxFactory.SingletonSeparatedList( SyntaxFactory.Attribute( SyntaxFactory.IdentifierName(annotation)))))); return(method); }