public override SyntaxNode VisitAttributeList(AttributeListSyntax node) { var firstAttr = node.Attributes[0]; var attrName = firstAttr.Name.ToString(); switch (attrName) { case "Guid": { return(this.ProcessGuidAttr(firstAttr)); } case "UnmanagedFunctionPointer": { // ClangSharp is emitting this attribute with no arguments. // The typedef we're using of this attribute has no such ctor, // so emit one that does, using WinApi as the default calling convention if (firstAttr.ArgumentList == null) { return (SyntaxFactory.AttributeList( SyntaxFactory.SingletonSeparatedList <AttributeSyntax>( SyntaxFactory.Attribute( SyntaxFactory.ParseName("UnmanagedFunctionPointer"), SyntaxFactory.ParseAttributeArgumentList("(CallingConvention.Winapi)"))))); } break; } case "NativeTypeName": { var ret = this.ProcessNativeTypeNameAttr(firstAttr); return(ret == null ? node : ret); } case "CppAttributeList": { return(this.CreateAttributeListForSal(node)); } } return(base.VisitAttributeList(node)); }
static FieldDeclarationSyntax MakeConstantSyntax(string messageFormat, string constantName, int code, string severity) { var messageFormatArgument = SyntaxFactory.AttributeArgument( SyntaxFactory.LiteralExpression( SyntaxKind.StringLiteralExpression, SyntaxFactory.Literal(messageFormat))); var sepSyntaxList = SyntaxFactory.SingletonSeparatedList(messageFormatArgument); if (severity != DefaultSeverity) { var severityArgument = SyntaxFactory.AttributeArgument( SyntaxFactory.NameEquals("Severity"), null, SyntaxFactory.ParseExpression("Severity." + severity)); sepSyntaxList = sepSyntaxList.Add(severityArgument); } var messageArgumentList = SyntaxFactory.AttributeArgumentList(sepSyntaxList); return(SyntaxFactory.FieldDeclaration( attributeLists: SyntaxFactory.List(new[] { SyntaxFactory.AttributeList(SyntaxFactory.SingletonSeparatedList( SyntaxFactory.Attribute( name: SyntaxFactory.ParseName("Message"), argumentList: messageArgumentList))) }), modifiers: SyntaxFactory.TokenList( SyntaxFactory.Token(SyntaxKind.PublicKeyword), SyntaxFactory.Token(SyntaxKind.ConstKeyword)), declaration: SyntaxFactory.VariableDeclaration( type: SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.IntKeyword)), variables: SyntaxFactory.SingletonSeparatedList( SyntaxFactory.VariableDeclarator( identifier: SyntaxFactory.Identifier(constantName), argumentList: null, initializer: SyntaxFactory.EqualsValueClause( SyntaxFactory.LiteralExpression(SyntaxKind.NumericLiteralExpression, SyntaxFactory.Literal(code)))))), semicolonToken: SyntaxFactory.Token(SyntaxKind.SemicolonToken))); }
public static AttributeListSyntax Create(IAttribute element) { NameSyntax name = SyntaxFactory.ParseName(element.Name); AttributeArgumentListSyntax arguments = null; if (element.Arguments?.Any() ?? false) { arguments = SyntaxFactory.ParseAttributeArgumentList($"({string.Join(", ", element.Arguments)})"); } var attribute = SyntaxFactory.Attribute(name, arguments); var attributeList = new SeparatedSyntaxList <AttributeSyntax>(); attributeList = attributeList.Add(attribute); return(SyntaxFactory.AttributeList(attributeList)); }
public PropertyDeclarationSyntax Convert(CsSchema.Property source, PropertyDeclarationSyntax destination, ResolutionContext context) { var syntax = SyntaxFactory.PropertyDeclaration( SyntaxFactory.ParseTypeName(source.TypeName), source.Name) .AddModifiers(mapper.Map <IEnumerable <SyntaxToken> >(source.Access).ToArray()) .AddAccessorListAccessors( SyntaxFactory.AccessorDeclaration(SyntaxKind.GetAccessorDeclaration).WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.SemicolonToken)), SyntaxFactory.AccessorDeclaration(SyntaxKind.SetAccessorDeclaration).WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.SemicolonToken))); if (source.Attributes != null) { syntax = syntax.AddAttributeLists( SyntaxFactory.AttributeList( new SeparatedSyntaxList <AttributeSyntax>().AddRange( mapper.Map <AttributeSyntax[]>(source.Attributes)))); } return(syntax); }
public static MethodDeclarationSyntax AddAttribute(this MethodDeclarationSyntax node, AttributeSyntax attr) { var existing = node.AttributeLists; var last = existing.Last(); var list = new SeparatedSyntaxList <AttributeSyntax>(); list = list.Add(attr); var newList = SyntaxFactory.AttributeList(list) .WithLeadingTrivia(last.GetClosestWhitespaceTrivia(true)) .WithTrailingTrivia(last.GetClosestWhitespaceTrivia(false)); existing = existing.Add(newList); node = node.WithAttributeLists(existing); return(node); }
protected SyntaxNode VisitDeclaration <T>(T node, Func <T, SyntaxList <AttributeListSyntax> > getAttributeLists, Func <T, SyntaxList <AttributeListSyntax>, T> withAttributeLists) where T : SyntaxNode { var newAttributeLists = VisitList(getAttributeLists(node)); T withAttribute; if (NewAttribute == null) { withAttribute = withAttributeLists(node, newAttributeLists); } else { newAttributeLists = newAttributeLists.Add(SyntaxFactory.AttributeList(SyntaxFactory.SingletonSeparatedList(NewAttribute))); NewAttribute = null; withAttribute = withAttributeLists(node.WithoutTrivia(), newAttributeLists); } return(withAttribute.WithTriviaFrom(node)); }
private static Task <Document> AddExportMetadata(Document document, CompilationUnitSyntax root, ClassDeclarationSyntax classDeclaration, string[] missingMetadata) { var newSyntax = classDeclaration; //値は空の状態で、必要なExportMetadataを全部追加 foreach (var metadata in missingMetadata) { var attributeList = SyntaxFactory.AttributeList( SyntaxFactory.SingletonSeparatedList( SyntaxFactory.Attribute(SyntaxFactory.ParseName("ExportMetadata"), SyntaxFactory.ParseAttributeArgumentList($"(\"{metadata}\", \"\")")))); newSyntax = newSyntax.AddAttributeLists(attributeList); } var newRoot = root.ReplaceNode(classDeclaration, newSyntax); var newDocument = document.WithSyntaxRoot(newRoot); return(Task.FromResult(newDocument)); }
public static AttributeListSyntax ConvertGuidToAttributeList(Guid guid) { // Outputs in format: {0x00000000,0x0000,0x0000,{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00}} string formattedGuid = guid.ToString("x"); // Get rid of leading { and trailing }} formattedGuid = formattedGuid.Substring(1, formattedGuid.Length - 3); // There's one more { we need to get rid of formattedGuid = formattedGuid.Replace("{", string.Empty); string args = $"({formattedGuid})"; return (SyntaxFactory.AttributeList( SyntaxFactory.SingletonSeparatedList <AttributeSyntax>( SyntaxFactory.Attribute( SyntaxFactory.ParseName("Windows.Win32.Interop.Guid"), SyntaxFactory.ParseAttributeArgumentList(args))))); }
public static string CreateTest(IEnumerable <UsingDirectiveSyntax> usings, ClassDeclarationSyntax @class) { var syntaxFactory = SyntaxFactory.CompilationUnit(); usings = usings.Append(CreateUsing("NUnit.Framework")); usings = usings.Append(CreateUsing(GetClassFullName(@class))); syntaxFactory = syntaxFactory.AddUsings(usings.ToArray()); NamespaceDeclarationSyntax testNamespace = SyntaxFactory.NamespaceDeclaration(SyntaxFactory.ParseName(usings.Last().Name + ".Tests")); ClassDeclarationSyntax testClass = SyntaxFactory.ClassDeclaration(@class.Identifier.Text + "Test").AddModifiers(SyntaxFactory.Token(SyntaxKind.PublicKeyword)); testClass = testClass.AddMembers(CreateMethods(@class)) .AddAttributeLists(SyntaxFactory.AttributeList().AddAttributes(SyntaxFactory.Attribute(SyntaxFactory.IdentifierName("TestFixture")))); testNamespace = testNamespace.AddMembers(testClass); syntaxFactory = syntaxFactory.AddMembers(testNamespace); return(syntaxFactory.NormalizeWhitespace().ToFullString()); }
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); }
/// <summary> /// Generates the class. /// </summary> public static ClassDeclarationSyntax GenerateClass(string className, SyntaxKind[] modifiers, MemberDeclarationSyntax[] methods, AttributeSyntax[] attributes = null) { var classDeclaration = SyntaxFactory.ClassDeclaration(className) .WithModifiers( modifiers.Select(SyntaxFactory.Token).ToArray() ) .WithMembers( SyntaxFactory.List(methods) ); if (attributes != null) { classDeclaration = classDeclaration.WithAttributeLists(SyntaxFactory.List(new[] { SyntaxFactory.AttributeList(SyntaxFactory.SeparatedList(attributes)) })); } return(classDeclaration); }
public ClassDeclarationSyntax Convert(CsSchema.Class source, ClassDeclarationSyntax destination, ResolutionContext context) { var syntax = SyntaxFactory.ClassDeclaration(source.Name) .AddModifiers(mapper.Map <IEnumerable <SyntaxToken> >(source.Access).ToArray()) .NormalizeWhitespace(); if (source.InheritTypeNames != null) { foreach (string inherit in source.InheritTypeNames) { syntax = syntax.AddBaseListTypes( SyntaxFactory.SimpleBaseType(SyntaxFactory.ParseTypeName(inherit))); } } if (source.Attributes != null) { syntax = syntax.AddAttributeLists( SyntaxFactory.AttributeList( new SeparatedSyntaxList <AttributeSyntax>().AddRange( mapper.Map <AttributeSyntax[]>(source.Attributes)))); } if (source.Fields != null) { foreach (CsSchema.Field field in source.Fields) { syntax = syntax.AddMembers(mapper.Map <FieldDeclarationSyntax>(field)); } } if (source.Properties != null) { foreach (CsSchema.Property property in source.Properties) { syntax = syntax.AddMembers(mapper.Map <PropertyDeclarationSyntax>(property)); } } if (source.Classes != null) { foreach (CsSchema.Class @class in source.Classes) { syntax = syntax.AddMembers(mapper.Map <ClassDeclarationSyntax>(@class)); } } return(syntax); }
private async Task <Document> InsertTypeAttributeAsync(Document document, SyntaxNode root, PropertyDeclarationSyntax propertyDeclaration, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); IPropertySymbol property = semanticModel?.GetDeclaredSymbol(propertyDeclaration, cancellationToken); if (property == null) { return(document); } var pxContext = new PXContext(semanticModel.Compilation, codeAnalysisSettings: null); var lists = new List <INamedTypeSymbol> { pxContext.AttributeTypes.PXIntListAttribute.Type, pxContext.AttributeTypes.PXStringListAttribute.Type }; var attributeTypes = property.GetAttributes() .Select(a => a.AttributeClass); var listAttribute = attributeTypes.FirstOrDefault(attributeType => lists.Any(lAttribute => attributeType.InheritsFromOrEquals(lAttribute, true))); cancellationToken.ThrowIfCancellationRequested(); string attributeIdentifier = listAttribute.InheritsFromOrEquals(pxContext.AttributeTypes.PXIntListAttribute.Type) ? pxContext.FieldAttributes.PXIntAttribute.Name : pxContext.FieldAttributes.PXStringAttribute.Name; AttributeSyntax attributeNode = SyntaxFactory.Attribute( SyntaxFactory.IdentifierName(attributeIdentifier)); var attributes = propertyDeclaration.AttributeLists.Add( SyntaxFactory.AttributeList( SyntaxFactory.SingletonSeparatedList(attributeNode))); var modifiedRoot = root.ReplaceNode(propertyDeclaration, propertyDeclaration.WithAttributeLists(attributes)); return(document.WithSyntaxRoot(modifiedRoot)); }
public static SyntaxNode VbGenerateAttribute(this SyntaxNode syntaxNode, string name, SyntaxTrivia?leadingWhitespaceTrivia, SyntaxNode[] arguments, SyntaxAnnotation argumentListAnnotation) { var leadingTrivia = syntaxNode.GetLeadingTrivia(); var attribute = VbGetAttributeSyntax(name, arguments, argumentListAnnotation); var attributeList = SyntaxFactory.AttributeList(SyntaxFactory.SeparatedList(new AttributeSyntax[] { attribute })) .NormalizeWhitespace() .WithTrailingTrivia(SyntaxFactory.EndOfLine(Environment.NewLine)); if (syntaxNode is ClassBlockSyntax classBlock) { return(classBlock.WithClassStatement((ClassStatementSyntax)VbGenerateAttribute(classBlock.ClassStatement, name, leadingWhitespaceTrivia, arguments, argumentListAnnotation))); } if (syntaxNode is PropertyBlockSyntax propertyBlock) { return(propertyBlock.WithPropertyStatement((PropertyStatementSyntax)VbGenerateAttribute(propertyBlock.PropertyStatement, name, leadingWhitespaceTrivia, arguments, argumentListAnnotation))); } if (syntaxNode is MethodBlockSyntax methodBlock) { return(methodBlock.WithSubOrFunctionStatement((MethodStatementSyntax)VbGenerateAttribute(methodBlock.SubOrFunctionStatement, name, leadingWhitespaceTrivia, arguments, argumentListAnnotation))); } if (syntaxNode is PropertyStatementSyntax propertySyntax) { return(propertySyntax.WithLeadingWhitespaceTrivia(propertySyntax.AttributeLists, leadingWhitespaceTrivia) .AddAttributeLists(attributeList.WithLeadingTrivia(propertySyntax.AttributeLists, leadingTrivia, leadingWhitespaceTrivia))); } else if (syntaxNode is ClassStatementSyntax classSyntax) { return(classSyntax.WithLeadingWhitespaceTrivia(classSyntax.AttributeLists, leadingWhitespaceTrivia) .AddAttributeLists(attributeList.WithLeadingTrivia(classSyntax.AttributeLists, leadingTrivia, leadingWhitespaceTrivia))); } else if (syntaxNode is MethodStatementSyntax methodSyntax) { return(methodSyntax.WithLeadingWhitespaceTrivia(methodSyntax.AttributeLists, leadingWhitespaceTrivia) .AddAttributeLists(attributeList.WithLeadingTrivia(methodSyntax.AttributeLists, leadingTrivia, leadingWhitespaceTrivia))); } else { Debug.Fail("Only property or class syntax node supported."); return(null); } }
public override SyntaxNode VisitMethodDeclaration(MethodDeclarationSyntax node) { using (_methodDeclarationContext.Enter(node)) { BaseMethodDeclarationSyntax newDeclaration = base.VisitMethodDeclaration(node) as MethodDeclarationSyntax; // Add Theory if no Test attribute to replace. if ((_methodDeclarationContext.Current.HasTestCase || _methodDeclarationContext.Current.HasTestCaseSourceAttribute) && !_methodDeclarationContext.Current.HasTestAttribute) { var theoryAttribute = SyntaxFactory.AttributeList(SyntaxFactory.SingletonSeparatedList(SyntaxFactory.Attribute(SyntaxFactory.IdentifierName("Theory")))); newDeclaration = newDeclaration.WithAttributeLists(newDeclaration.AttributeLists.Insert(0, theoryAttribute)); } newDeclaration = ReplaceBlocks(newDeclaration); newDeclaration = HandleSetup(newDeclaration); newDeclaration = HandleTearDown(newDeclaration); return(newDeclaration); } }
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)); }
private MethodDeclarationSyntax ScaffoldTestMethod() { var method = SyntaxFactory.MethodDeclaration(SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.VoidKeyword)), "MyTestMethod") .WithModifiers(SyntaxFactory.TokenList(SyntaxFactory.Token(SyntaxKind.PublicKeyword))) .AddAttributeLists(SyntaxFactory.AttributeList(SyntaxFactory.SeparatedList(new[] { SyntaxFactory.Attribute(SyntaxFactory.IdentifierName("TestMethod")) }))) .WithBody(SyntaxFactory.Block().WithCloseBraceToken(SyntaxFactory.Token(SyntaxKind.CloseBraceToken) .WithLeadingTrivia( SyntaxFactory.TriviaList( SyntaxFactory.SyntaxTrivia(SyntaxKind.SingleLineCommentTrivia, "// Arrange."), SyntaxFactory.CarriageReturnLineFeed, SyntaxFactory.CarriageReturnLineFeed, SyntaxFactory.SyntaxTrivia(SyntaxKind.SingleLineCommentTrivia, "// Act."), SyntaxFactory.CarriageReturnLineFeed, SyntaxFactory.CarriageReturnLineFeed, SyntaxFactory.SyntaxTrivia(SyntaxKind.SingleLineCommentTrivia, "// Assert."), SyntaxFactory.CarriageReturn)))); return(method.WithIdentifier(method.Identifier.WithAdditionalAnnotations(RenameAnnotation.Create()))); }
internal ClassDeclarationSyntax CreateClass(Class classDeclaration) { var @class = SyntaxFactory.ClassDeclaration(classDeclaration.Name + "Tests") .WithAttributeLists( SyntaxFactory.SingletonList <AttributeListSyntax>( SyntaxFactory.AttributeList( SyntaxFactory.SingletonSeparatedList <AttributeSyntax>( SyntaxFactory.Attribute( SyntaxFactory.IdentifierName("TestFixture")))))) .WithModifiers( SyntaxFactory.TokenList( SyntaxFactory.Token(SyntaxKind.PublicKeyword))); if (!classDeclaration.IsStatic) { @class = @class.AddMembers(classDeclaration.Parameters.Select( pr => SyntaxFactory.FieldDeclaration( SyntaxFactory.VariableDeclaration(pr.Type.GetMockOrDefaultType()) .WithVariables( SyntaxFactory.SingletonSeparatedList <VariableDeclaratorSyntax>( SyntaxFactory.VariableDeclarator( SyntaxFactory.Identifier(pr.Name + "Global"))))) .WithModifiers( SyntaxFactory.TokenList( SyntaxFactory.Token( SyntaxKind.PrivateKeyword)))) .ToArray()); @class = @class.AddMembers(SyntaxFactory.FieldDeclaration( SyntaxFactory.VariableDeclaration( SyntaxFactory.IdentifierName(classDeclaration.Name)) .WithVariables( SyntaxFactory.SingletonSeparatedList <VariableDeclaratorSyntax>( SyntaxFactory.VariableDeclarator( SyntaxFactory.Identifier(classDeclaration.Name + "Global"))))) .WithModifiers( SyntaxFactory.TokenList( SyntaxFactory.Token( SyntaxKind.PrivateKeyword)))); @class = @class.AddMembers(CreateSetUpMethod(classDeclaration)); } @class = @class.AddMembers(classDeclaration.Methods.Select(mt => CreateTestMethod(mt)).ToArray()); return(@class); }
internal static CompilationUnitSyntax AddCustomAttribute(this CompilationUnitSyntax root, ref ConstructorDeclarationSyntax constructorDeclaration, string name, AttributeArgumentListSyntax arguments = default) { var attributes = constructorDeclaration.AttributeLists.Add( SyntaxFactory.AttributeList(SyntaxFactory.SingletonSeparatedList <AttributeSyntax>( SyntaxFactory.Attribute(SyntaxFactory.IdentifierName(name)) .WithArgumentList(arguments) )).NormalizeWhitespace()); var newConstructorDeclaration = constructorDeclaration.WithAttributeLists(attributes); root = root.ReplaceNode( constructorDeclaration, newConstructorDeclaration ); constructorDeclaration = newConstructorDeclaration; return(root); }
private void AddNode(Architecture arch, SyntaxNode node) { string name = SyntaxUtils.GetFullName(node, true); string fullSignature = GetFullSignature(node); string altSignature = string.Empty; if (arch == Architecture.X86 && node is StructDeclarationSyntax structNode) { var packing4AttrList = SyntaxFactory.AttributeList( SyntaxFactory.SingletonSeparatedList <AttributeSyntax>( SyntaxFactory.Attribute( SyntaxFactory.ParseName("StructLayout"), SyntaxFactory.ParseAttributeArgumentList("(LayoutKind.Sequential, Pack = 4)")))); var tempNode = structNode.AddAttributeLists(packing4AttrList); altSignature = GetFullSignature(tempNode); } lock (this.namesToInfos) { if (!this.namesToInfos.TryGetValue(name, out var crossArchInfos)) { crossArchInfos = new List <CrossArchInfo>(); this.namesToInfos[name] = crossArchInfos; } foreach (var info in crossArchInfos) { if (info.FullSignature == fullSignature || info.FullSignature == altSignature) { info.Arch |= arch; return; } } var newInfo = new CrossArchInfo() { Arch = arch, FullSignature = fullSignature }; crossArchInfos.Add(newInfo); } }
public static string GenerateTestCode(List <NamespaceData> namespaces, string fileName) { CompilationUnitSyntax tree = SyntaxFactory.CompilationUnit() .AddUsings( SyntaxFactory.UsingDirective(SyntaxFactory.ParseName("NUnit.Framework")), SyntaxFactory.UsingDirective(SyntaxFactory.ParseName(fileName.Replace(".cs", "")))); foreach (NamespaceData namespaceData in namespaces) { NamespaceDeclarationSyntax ns = SyntaxFactory.NamespaceDeclaration(SyntaxFactory.IdentifierName(namespaceData.Name + ".Tests")); foreach (ClassData classData in namespaceData.ClassList) { ClassDeclarationSyntax classNode = SyntaxFactory .ClassDeclaration(classData.Name + "TestClass") .AddModifiers(SyntaxFactory.Token(SyntaxKind.PublicKeyword)) .AddAttributeLists(SyntaxFactory.AttributeList(SyntaxFactory.SingletonSeparatedList(SyntaxFactory.Attribute(SyntaxFactory.IdentifierName("TestFixture")))).NormalizeWhitespace()); foreach (MethodData methodData in classData.MethodList) { MethodDeclarationSyntax method = SyntaxFactory .MethodDeclaration(SyntaxFactory.ParseTypeName("void"), methodData.Name + "TestMethod") .AddAttributeLists(SyntaxFactory.AttributeList(SyntaxFactory.SingletonSeparatedList(SyntaxFactory.Attribute(SyntaxFactory.IdentifierName("Test")))).NormalizeWhitespace()) .AddModifiers(SyntaxFactory.Token(SyntaxKind.PublicKeyword)) .AddModifiers(SyntaxFactory.Token(SyntaxKind.StaticKeyword)) .AddBodyStatements( SyntaxFactory.ExpressionStatement( SyntaxFactory.InvocationExpression( SyntaxFactory.MemberAccessExpression(SyntaxKind.SimpleMemberAccessExpression, SyntaxFactory.IdentifierName("Assert"), SyntaxFactory.IdentifierName("Fail")), SyntaxFactory.ArgumentList(SyntaxFactory.SingletonSeparatedList(SyntaxFactory.Argument(SyntaxFactory.LiteralExpression(SyntaxKind.StringLiteralExpression, SyntaxFactory.Literal("autogenerated")))))))); classNode = classNode .AddMembers(method); } ns = ns .AddMembers(classNode); } tree = tree .AddMembers(ns); } AdhocWorkspace cw = new AdhocWorkspace(); return(Formatter.Format(tree.SyntaxTree.GetRoot(), cw, null).ToFullString()); }
private static async Task TestAsync(string initialText, string attributeAddedText) { var doc = GetDocument(initialText); var options = await doc.GetOptionsAsync(); var attributeList = SyntaxFactory .AttributeList( SyntaxFactory.SingletonSeparatedList( SyntaxFactory.Attribute( SyntaxFactory.IdentifierName( "System.Reflection.AssemblyVersion(\"1.0.0.0\")" ) ) ) ) .WithTarget( SyntaxFactory.AttributeTargetSpecifier( SyntaxFactory.Token(SyntaxKind.AssemblyKeyword) ) ); var syntaxRoot = await doc.GetSyntaxRootAsync(); var editor = await DocumentEditor.CreateAsync(doc); editor.AddAttribute(syntaxRoot, attributeList); var changedDoc = editor.GetChangedDocument(); if (attributeAddedText != null) { var formatted = await Formatter.FormatAsync( changedDoc, SyntaxAnnotation.ElasticAnnotation, options ); var actualText = (await formatted.GetTextAsync()).ToString(); Assert.Equal(attributeAddedText, actualText); } }
public override SyntaxNode VisitDelegateDeclaration(DelegateDeclarationSyntax node) { string fullName = SyntaxUtils.GetFullName(node); // Remove duplicate delegates in this tree if (this.visitedDelegateNames.Contains(fullName)) { return(null); } this.visitedDelegateNames.Add(fullName); string returnFullName = $"{fullName}::return"; if (this.GetRemapInfo(returnFullName, out List <AttributeSyntax> listAttributes, node.ReturnType.ToString(), out var newType, out _)) { node = (DelegateDeclarationSyntax)base.VisitDelegateDeclaration(node); if (listAttributes != null) { foreach (var attrNode in listAttributes) { var attrListNode = SyntaxFactory.AttributeList( SyntaxFactory.SingletonSeparatedList <AttributeSyntax>(attrNode)) .WithTarget( SyntaxFactory.AttributeTargetSpecifier( SyntaxFactory.Token(SyntaxKind.ReturnKeyword))); node = node.WithAttributeLists(node.AttributeLists.Add(attrListNode)); } if (newType != null) { node = node.WithReturnType(SyntaxFactory.ParseTypeName(newType).WithTrailingTrivia(SyntaxFactory.Space)); } } return(node); } return(base.VisitDelegateDeclaration(node)); }
private async Task <Document> CreateInitilizeFieldAsync(Document document, ParameterSyntax parameter, string underscoreName, CancellationToken cancellationToken) { var oldClass = parameter.Ancestors() .OfType <ClassDeclarationSyntax>() .First(); var oldConstructor = parameter.Ancestors() .OfType <ConstructorDeclarationSyntax>() .First(); StatementSyntax initilizationStatement = SyntaxFactory.ExpressionStatement( SyntaxFactory.AssignmentExpression( SyntaxKind.SimpleAssignmentExpression, SyntaxFactory.IdentifierName(underscoreName), SyntaxFactory.IdentifierName(parameter.Identifier))); var newConstructor = oldConstructor.WithBody( oldConstructor.Body.AddStatements(initilizationStatement)); var classWithNewConstructor = oldClass.ReplaceNode(oldConstructor, newConstructor); var newFieldDeclaration = SyntaxFactory.FieldDeclaration(SyntaxFactory.VariableDeclaration(parameter.Type)) .WithModifiers(SyntaxFactory.TokenList( SyntaxFactory.Token(SyntaxKind.PrivateKeyword), SyntaxFactory.Token(SyntaxKind.ReadOnlyKeyword))) .WithAttributeLists(SyntaxFactory.AttributeList(SyntaxFactory.VariableDeclarator(underscoreName))); var fieldDeclaration = classWithNewConstructor.Members .OfType <FieldDeclarationSyntax>() .ToList(); fieldDeclaration.Add(newFieldDeclaration); var classWithNewConstructorAndField = classWithNewConstructor.AddMembers(newFieldDeclaration); var oldRoot = await document.GetSyntaxRootAsync(cancellationToken) .ConfigureAwait(false); var newRoot = oldRoot.ReplaceNode(oldClass, classWithNewConstructorAndField); return(document.WithSyntaxRoot(newRoot)); }
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())); }
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); }
public static TestClassInfo[] Generate(string content) { var treeRoot = CSharpSyntaxTree.ParseText(content).GetRoot(); return((from userClass in treeRoot.DescendantNodes().OfType <ClassDeclarationSyntax>() let className = userClass.Identifier.ValueText let currentNamespace = SyntaxFactory.NamespaceDeclaration(SyntaxFactory.ParseName(className + "UnitTests")) let classSignature = SyntaxFactory.ClassDeclaration($"{className}Test") .AddModifiers(SyntaxFactory.Token(SyntaxKind.PublicKeyword)) .AddAttributeLists( SyntaxFactory.AttributeList(SyntaxFactory.AttributeList().Attributes.Add(TestClassAttribute))) let classMethods = Enumerable.OfType <MethodDeclarationSyntax>(userClass.DescendantNodes()) .Where(method => method.Modifiers.Any(SyntaxKind.PublicKeyword)) let classCode = SyntaxFactory.CompilationUnit() .AddUsings(CreateUsing(treeRoot)) .AddMembers(currentNamespace.AddMembers(classSignature.AddMembers(classMethods .Select(method => CreateMethod($"Test{method.Identifier.ValueText}")).ToArray()))) select new TestClassInfo(className, classCode.NormalizeWhitespace().ToFullString())).ToArray()); }
public void AddAttribute(string attributeName, params string[] verbatimArguments) { NameSyntax name = SyntaxFactory.ParseName(attributeName); AttributeSyntax attribute; if (verbatimArguments.Length > 0) { string argsCsv = string.Join(", ", verbatimArguments); AttributeArgumentListSyntax arguments = SyntaxFactory.ParseAttributeArgumentList($"({argsCsv})"); attribute = SyntaxFactory.Attribute(name, arguments); } else { attribute = SyntaxFactory.Attribute(name); } AttributeListSyntax attributeList = SyntaxFactory.AttributeList(SyntaxFactory.SingletonSeparatedList(attribute)); Info = Info.AddAttributeLists(attributeList); }
/// <summary> /// Create attribute list of the supplied type /// </summary> /// <param name="type"></param> /// <returns></returns> public static AttributeListSyntax GetAttributeList(this INamedTypeSymbol type, AttributeArgumentListSyntax argumentList = null) { type.ThrowOnNull(nameof(type)); var node = SyntaxFactory.Attribute( SyntaxFactory.IdentifierName( type.Name)) .WithAdditionalAnnotations(Simplifier.Annotation); if (argumentList != null) { node = node.WithArgumentList(argumentList); } var list = SyntaxFactory.AttributeList( SyntaxFactory.SingletonSeparatedList( node)); return(list); }
/// <summary> /// Generates the extension method. /// </summary> public static MethodDeclarationSyntax GenerateExtensionMethod(string methodName, string returnTypeName, ParameterSyntax[] parameters, AttributeSyntax[] attributes = null) { var methodDeclaration = SyntaxFactory.MethodDeclaration(SyntaxFactory.ParseTypeName(returnTypeName ?? "void"), methodName) .WithModifiers( SyntaxFactory.Token(SyntaxKind.PublicKeyword), SyntaxFactory.Token(SyntaxKind.StaticKeyword) ) .WithParameterList( parameters ); if (attributes != null) { methodDeclaration = methodDeclaration.WithAttributeLists(SyntaxFactory.List(new[] { SyntaxFactory.AttributeList(SyntaxFactory.SeparatedList(attributes)) })); } return(methodDeclaration); }