private AttributeListSyntax GenerateTermAttribute(FieldType metaData, IGeneratorConfiguration config) { LiteralExpressionSyntax literalExpression = null; switch (config.TermAttribute) { case TermAttributeType.name: literalExpression = SyntaxFactory.LiteralExpression( SyntaxKind.StringLiteralExpression, SyntaxFactory.Literal(metaData.Term)); break; case TermAttributeType.index: literalExpression = SyntaxFactory.LiteralExpression( SyntaxKind.NumericLiteralExpression, SyntaxFactory.Literal(metaData.Index)); break; default: throw new Exception("Invalid term attribute configuration"); } ; return(SyntaxFactory.AttributeList( SyntaxFactory.SingletonSeparatedList( SyntaxFactory.Attribute( SyntaxFactory.IdentifierName("Term")) .WithArgumentList( SyntaxFactory.AttributeArgumentList( SyntaxFactory.SingletonSeparatedList( SyntaxFactory.AttributeArgument(literalExpression))))))); }
private static async Task <Document> AddFriendClassAttributeAsync(Document document, ClassDeclarationSyntax?classDeclaration, string friendClassType, CancellationToken cancellationToken) { // 构造FriendClassAttribute 语法节点 AttributeArgumentSyntax attributeArgument = SyntaxFactory.AttributeArgument(SyntaxFactory.TypeOfExpression(SyntaxFactory.ParseTypeName(friendClassType))); AttributeSyntax attributeSyntax = SyntaxFactory.Attribute(SyntaxFactory.IdentifierName("FriendClassAttribute")) .WithArgumentList(SyntaxFactory.AttributeArgumentList(SyntaxFactory.SingletonSeparatedList(attributeArgument))); // 构造添加构造FriendClassAttribute 得AttributeList语法节点 SyntaxList <AttributeListSyntax>?attributes = classDeclaration?.AttributeLists.Add( SyntaxFactory.AttributeList(SyntaxFactory.SingletonSeparatedList(attributeSyntax)).NormalizeWhitespace()); if (attributes == null) { return(document); } // 构造替换AttributeList的 ClassDeclaration语法节点 ClassDeclarationSyntax?newClassDeclaration = classDeclaration?.WithAttributeLists(attributes.Value).WithAdditionalAnnotations(Formatter.Annotation); SyntaxNode?root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); if (root == null || classDeclaration == null || newClassDeclaration == null) { return(document); } // 构造替换classDeclaration的root语法节点 var newRoot = root.ReplaceNode(classDeclaration, newClassDeclaration); // 替换root语法节点 return(document.WithSyntaxRoot(newRoot)); }
public static Task <Document> Fix( Document orig, SyntaxNode root, AttributeSyntax attr, string maxExceptionsAllowed ) { var syntaxForExcepts = maxExceptionsAllowed .Split(',') .Select(GetSyntaxForExceptName) .ToImmutableArray(); var expr = CombineReasons(syntaxForExcepts); // newAttr will always have fewer exceptions than attr: see the // note in the analyzer attached to maximalExceptions var newAttr = attr.WithArgumentList( SyntaxFactory.AttributeArgumentList( SyntaxFactory.SingletonSeparatedList( SyntaxFactory.AttributeArgument( expr ).WithNameEquals(SyntaxFactory.NameEquals("Except")) ) ) ); var newRoot = root.ReplaceNode(attr, newAttr); var newDoc = orig.WithSyntaxRoot(newRoot); return(Task.FromResult(newDoc)); }
static CodeAction CreateAttributeCodeAction(Document document, SyntaxNode root, ExpressionSyntax node, IMethodSymbol constructor, AttributeSyntax attribute) { var arguments = attribute.ArgumentList.Arguments; var idx = arguments.IndexOf(node.Parent as AttributeArgumentSyntax); var name = constructor.Parameters[idx].Name; return(CodeActionFactory.Create( node.Span, DiagnosticSeverity.Info, string.Format(GettextCatalog.GetString("Add argument name '{0}'"), name), t2 => { var newArguments = SyntaxFactory.SeparatedList <AttributeArgumentSyntax>( attribute.ArgumentList.Arguments.Take(idx).Concat( attribute.ArgumentList.Arguments.Skip(idx).Select((arg, i) => { if (arg.NameEquals != null) { return arg; } return SyntaxFactory.AttributeArgument(null, SyntaxFactory.NameColon(constructor.Parameters[i + idx].Name), arg.Expression); }) ) ); var newAttribute = attribute.WithArgumentList(attribute.ArgumentList.WithArguments(newArguments)); var newRoot = root.ReplaceNode((SyntaxNode)attribute, newAttribute).WithAdditionalAnnotations(Formatter.Annotation); return Task.FromResult(document.WithSyntaxRoot(newRoot)); } )); }
public static SyntaxList <AttributeListSyntax> BuildOperationContractAttributeForAsyncMethod(string existingServiceActionName, SyntaxList <AttributeListSyntax> existingAttributeLists) { var actionAttributeValue = SyntaxFactory.LiteralExpression(SyntaxKind.StringLiteralExpression, SyntaxFactory.Literal(existingServiceActionName)); var actionAttribute = SyntaxFactory.AttributeArgument(SyntaxFactory.NameEquals("Action"), null, actionAttributeValue); var replyAttributeValue = SyntaxFactory.LiteralExpression(SyntaxKind.StringLiteralExpression, SyntaxFactory.Literal($"{existingServiceActionName}Response")); var replyActionAttribute = SyntaxFactory.AttributeArgument(SyntaxFactory.NameEquals("ReplyAction"), null, replyAttributeValue); var separatedSyntaxListForAttribArgs = new SeparatedSyntaxList <AttributeArgumentSyntax>(); separatedSyntaxListForAttribArgs = separatedSyntaxListForAttribArgs.Add(actionAttribute); separatedSyntaxListForAttribArgs = separatedSyntaxListForAttribArgs.Add(replyActionAttribute); var attributeArgs = SyntaxFactory.AttributeArgumentList(separatedSyntaxListForAttribArgs); var operationContractAttribute = existingAttributeLists.First().Attributes.First(); var newOperationContractAttribute = operationContractAttribute.WithArgumentList(attributeArgs); var separatedAttributeList = SyntaxFactory.SeparatedList <AttributeSyntax>(); separatedAttributeList = separatedAttributeList.Add(newOperationContractAttribute); var attrList = SyntaxFactory.AttributeList(separatedAttributeList); var yetAnotherFuckingList = new SyntaxList <AttributeListSyntax>(); yetAnotherFuckingList = yetAnotherFuckingList.Add(attrList); return(yetAnotherFuckingList); }
private async Task <Document> GetTransformedDocumentAsync(Document document, Diagnostic diagnostic, CancellationToken cancellationToken) { SyntaxNode root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var declaration = root.FindToken(diagnostic.Location.SourceSpan.Start).Parent.AncestorsAndSelf().OfType <AttributeSyntax>().First(); var property = declaration.FirstAncestorOrSelf <PropertyDeclarationSyntax>(); var maxOrderNumber = property.GetMaxOrderNumber(); var newList = declaration.ArgumentList ?? SyntaxFactory.AttributeArgumentList(); newList = newList.WithArguments( SyntaxFactory.SeparatedList(newList.Arguments.Add( SyntaxFactory.AttributeArgument( SyntaxFactory.NameEquals("Order"), null, SyntaxFactory.ParseExpression($"{maxOrderNumber + 1}"))))); var newDeclaration = declaration.WithArgumentList(newList); var newRoot = root.ReplaceNode(declaration, newDeclaration); return(document.WithSyntaxRoot(newRoot)); }
private static AttributeListSyntax CreateAttribute(string fieldName) { AttributeArgumentSyntax arg = SyntaxFactory.AttributeArgument(SyntaxFactory.ParseExpression("\"" + fieldName + "\"")); AttributeSyntax attr = SyntaxFactory.Attribute(SyntaxFactory.ParseName("XmlAttribute")).AddArgumentListArguments(arg); return(SyntaxFactory.AttributeList(SyntaxFactory.SeparatedList(new[] { attr }))); }
public override PropertyDeclarationSyntax GetSyntax() { var format = DateFormat == "date" ? TypeHelpers.PythonDateFormatString : TypeHelpers.DateTimeFormatString; var syntax = base.GetSyntax(); return(syntax.WithAttributeLists( SyntaxFactory.SingletonList <AttributeListSyntax>( SyntaxFactory.AttributeList( SyntaxFactory.SingletonSeparatedList <AttributeSyntax>( SyntaxFactory.Attribute( SyntaxFactory.IdentifierName("JsonConverter")) .WithArgumentList( SyntaxFactory.AttributeArgumentList( SyntaxFactory.SeparatedList <AttributeArgumentSyntax>( new SyntaxNodeOrToken[] { SyntaxFactory.AttributeArgument( SyntaxFactory.TypeOfExpression( SyntaxFactory.IdentifierName("CustomDateConverter"))), SyntaxFactory.Token(SyntaxKind.CommaToken), SyntaxFactory.AttributeArgument( SyntaxFactory.LiteralExpression( SyntaxKind.StringLiteralExpression, SyntaxFactory.Literal(format))) })))))))); }
private static void AddRouteAttribute(SemanticModel semanticModel, SyntaxNode root, DocumentEditor documentEditor, TextSpan diagnosticSpan, CancellationToken cancellationToken) { var methodDeclaration = root.FindToken(diagnosticSpan.Start).Parent.AncestorsAndSelf().OfType <MethodDeclarationSyntax>().First(); var method = semanticModel.GetDeclaredSymbol(methodDeclaration, cancellationToken); string?route = null; foreach (var parameter in method.Parameters) { // Simple types participate in overload selection. We'll assume they all come from route and use it to produce a route for this action. // https://github.com/aspnet/AspNetWebStack/blob/749384689e027a2fcd29eb79a9137b94cea611a8/src/System.Web.Http/Internal/TypeHelper.cs#L63-L72 if (parameter.Type.IsValueType || SymbolEqualityComparer.Default.Equals(parameter.Type, semanticModel.Compilation.GetSpecialType(SpecialType.System_String)) || SymbolEqualityComparer.Default.Equals(parameter.Type, semanticModel.Compilation.GetSpecialType(SpecialType.System_DateTime)) || SymbolEqualityComparer.Default.Equals(parameter.Type, semanticModel.Compilation.GetSpecialType(SpecialType.System_Decimal))) { route += $"/{{{parameter.Name}}}"; } } if (route is null) { return; } route = "[controller]/[action]" + route; var actionAttribute = SyntaxFactory.Attribute( SyntaxFactory.ParseName("Microsoft.AspNetCore.Mvc.Route").WithAdditionalAnnotations(Simplifier.Annotation)) .AddArgumentListArguments( SyntaxFactory.AttributeArgument( SyntaxFactory.LiteralExpression(SyntaxKind.StringLiteralExpression, SyntaxFactory.Literal(route)))); documentEditor.AddAttribute(methodDeclaration, actionAttribute); }
public static InterfaceDeclarationSyntax AddGeneratedCodeAttribute(this InterfaceDeclarationSyntax interfaceDeclaration, string toolName, string version) { if (interfaceDeclaration == null) { throw new ArgumentNullException(nameof(interfaceDeclaration)); } if (toolName == null) { throw new ArgumentNullException(nameof(toolName)); } if (version == null) { throw new ArgumentNullException(nameof(version)); } var attributeArgumentList = SyntaxFactory.AttributeArgumentList( SyntaxFactory.SeparatedList <AttributeArgumentSyntax>(SyntaxFactory.NodeOrTokenList( SyntaxFactory.AttributeArgument(SyntaxLiteralExpressionFactory.Create(toolName)), SyntaxTokenFactory.Comma(), SyntaxFactory.AttributeArgument(SyntaxLiteralExpressionFactory.Create(version))))); return(interfaceDeclaration .AddAttributeLists(SyntaxAttributeListFactory.Create(nameof(GeneratedCodeAttribute), attributeArgumentList))); }
public static ClassDeclarationSyntax AddDataAnnotation(this ClassDeclarationSyntax cls, string annotationKey, string annotationValue, string parameter, string parameterValues) { return(cls.WithAttributeLists( SyntaxFactory.SingletonList <AttributeListSyntax>( SyntaxFactory.AttributeList( SyntaxFactory.SeparatedList(new[] { SyntaxFactory.Attribute(SyntaxFactory.ParseName(annotationKey), SyntaxFactory.AttributeArgumentList( SyntaxFactory.Token(SyntaxKind.OpenParenToken), SyntaxFactory.SeparatedList <AttributeArgumentSyntax>(new[] { SyntaxFactory.AttributeArgument(SyntaxFactory.IdentifierName(annotationValue)), SyntaxFactory.AttributeArgument( SyntaxFactory.NameEquals(SyntaxFactory.IdentifierName(parameter), SyntaxFactory.Token(SyntaxKind.EqualsToken)), null, SyntaxFactory.LiteralExpression(SyntaxKind.StringLiteralExpression, SyntaxFactory.Literal(parameterValues)) ) }), SyntaxFactory.Token(SyntaxKind.CloseParenToken) ) ) } ) ) ) )); }
public static ClassDeclarationSyntax AddSuppressMessageAttribute(this ClassDeclarationSyntax classDeclaration, SuppressMessageAttribute suppressMessage) { if (classDeclaration == null) { throw new ArgumentNullException(nameof(classDeclaration)); } if (suppressMessage == null) { throw new ArgumentNullException(nameof(suppressMessage)); } if (string.IsNullOrEmpty(suppressMessage.Justification)) { throw new ArgumentException(nameof(suppressMessage.Justification)); } var attributeArgumentList = SyntaxFactory.AttributeArgumentList( SyntaxFactory.SeparatedList <AttributeArgumentSyntax>(SyntaxFactory.NodeOrTokenList( SyntaxFactory.AttributeArgument(SyntaxLiteralExpressionFactory.Create(suppressMessage.Category)), SyntaxTokenFactory.Comma(), SyntaxFactory.AttributeArgument(SyntaxLiteralExpressionFactory.Create(suppressMessage.CheckId)), SyntaxTokenFactory.Comma(), SyntaxFactory.AttributeArgument(SyntaxLiteralExpressionFactory.Create(suppressMessage.Justification !)) .WithNameEquals( SyntaxNameEqualsFactory.Create(nameof(SuppressMessageAttribute.Justification)) .WithEqualsToken(SyntaxTokenFactory.Equals()))))); return(classDeclaration .AddAttributeLists(SyntaxAttributeListFactory.Create(nameof(SuppressMessageAttribute), attributeArgumentList))); }
public static T ApplyAttributes <T>(this T syntaxNode, string attributeName, params object[] attributeArguments) where T : MemberDeclarationSyntax { if (attributeName.EndsWith("Attribute", StringComparison.OrdinalIgnoreCase)) { attributeName = attributeName.Substring(0, attributeName.LastIndexOf("Attribute")); } var nameSyntax = attributeName.ParseCSharpName(); var seperatedList = SyntaxFactory.SeparatedList <AttributeSyntax>(); var attributeList = SyntaxFactory.AttributeList(seperatedList); var attribute = SyntaxFactory.Attribute(nameSyntax); if (null != attributeArguments && 0 < attributeArguments.Length) { List <AttributeArgumentSyntax> attributesSyntax = new List <AttributeArgumentSyntax>(); foreach (var attributeArgument in attributeArguments) { var literalExpression = Extensions.CreateLiteralExpression(attributeArgument); var argument = SyntaxFactory.AttributeArgument(literalExpression); attributesSyntax.Add(argument); } attribute = attribute.AddArgumentListArguments(attributesSyntax.ToArray()); } return((T)syntaxNode.AddAttributeLists(attributeList.AddAttributes(attribute))); }
private AttributeArgumentListSyntax CreateAttributeArguments(ISymbol targetSymbol, Diagnostic diagnostic) { // SuppressMessage("Rule Category", "Rule Id", Justification = nameof(Justification), Scope = nameof(Scope), Target = nameof(Target)) var category = SyntaxFactory.LiteralExpression(SyntaxKind.StringLiteralExpression, SyntaxFactory.Literal(diagnostic.Descriptor.Category)); var categoryArgument = SyntaxFactory.AttributeArgument(category); var title = diagnostic.Descriptor.Title.ToString(CultureInfo.CurrentUICulture); var ruleIdText = string.IsNullOrWhiteSpace(title) ? diagnostic.Id : string.Format("{0}:{1}", diagnostic.Id, title); var ruleId = SyntaxFactory.LiteralExpression(SyntaxKind.StringLiteralExpression, SyntaxFactory.Literal(ruleIdText)); var ruleIdArgument = SyntaxFactory.AttributeArgument(ruleId); var justificationExpr = SyntaxFactory.LiteralExpression(SyntaxKind.StringLiteralExpression, SyntaxFactory.Literal(FeaturesResources.Pending)); var justificationArgument = SyntaxFactory.AttributeArgument(SyntaxFactory.NameEquals("Justification"), nameColon: null, expression: justificationExpr); var attributeArgumentList = SyntaxFactory.AttributeArgumentList().AddArguments(categoryArgument, ruleIdArgument, justificationArgument); var scopeString = GetScopeString(targetSymbol.Kind); if (scopeString != null) { var scopeExpr = SyntaxFactory.LiteralExpression(SyntaxKind.StringLiteralExpression, SyntaxFactory.Literal(scopeString)); var scopeArgument = SyntaxFactory.AttributeArgument(SyntaxFactory.NameEquals("Scope"), nameColon: null, expression: scopeExpr); var targetString = GetTargetString(targetSymbol); var targetExpr = SyntaxFactory.LiteralExpression(SyntaxKind.StringLiteralExpression, SyntaxFactory.Literal(targetString)); var targetArgument = SyntaxFactory.AttributeArgument(SyntaxFactory.NameEquals("Target"), nameColon: null, expression: targetExpr); attributeArgumentList = attributeArgumentList.AddArguments(scopeArgument, targetArgument); } return(attributeArgumentList); }
public SyntaxList <AttributeListSyntax> Convert( SyntaxList <AttributeListSyntax> attributeList, bool isSkip, string skipText) { var attributes = attributeList.First(a => a.Attributes.Any(at => at.Name.ToString().Equals("Test", StringComparison.OrdinalIgnoreCase))); var attribute = attributes.Attributes.First(at => at.Name.ToString().Equals("Test", StringComparison.OrdinalIgnoreCase)); var newAttribute = attribute.WithName(SyntaxFactory.IdentifierName("Fact")); if (isSkip) { newAttribute = newAttribute.WithArgumentList( SyntaxFactory.AttributeArgumentList( SyntaxFactory.SeparatedList(new[] { SyntaxFactory.AttributeArgument( SyntaxFactory.NameEquals("Skip"), null, SyntaxFactory.IdentifierName(skipText)) }))); } return(attributeList.Replace(attributes, attributes.WithAttributes( attributes.Attributes.Replace(attribute, newAttribute)))); }
public override SyntaxNode MakeSyntaxNode() { var res = SyntaxFactory.AttributeArgument(NameEquals, NameColon, Expression); IsChanged = false; return(res); }
private AttributeSyntax GetRouteAttributeForWebmethod(string routeName, SemanticModel semanticModel, IEnumerable <ParameterSyntax> routeParams) { var parameters = new List <String>(); foreach (var routeParam in routeParams) { var paramName = routeParam.Identifier.Text; parameters.Add($"{{{paramName}}}"); } var route = $"{routeName}"; if (routeParams.Any()) { route = $"{route}/{String.Join("/", parameters)}"; } return(SyntaxFactory.Attribute( SyntaxFactory.IdentifierName("Route")) .WithArgumentList( SyntaxFactory.AttributeArgumentList( SyntaxFactory.SingletonSeparatedList <AttributeArgumentSyntax>( SyntaxFactory.AttributeArgument( SyntaxFactory.LiteralExpression( SyntaxKind.StringLiteralExpression, SyntaxFactory.Literal($"{route}"))))))); }
public override SyntaxNode VisitClassDeclaration(ClassDeclarationSyntax node) { var declaration = (TypeDeclarationSyntax)base.VisitClassDeclaration(node); var guid = Guid.NewGuid().ToString(); var containerProviderAttribute = SyntaxFactory .AttributeList ( SyntaxFactory.SingletonSeparatedList ( SyntaxFactory.Attribute(SyntaxFactory.IdentifierName("ContainerProvider")) .WithArgumentList ( SyntaxFactory.AttributeArgumentList ( SyntaxFactory.SingletonSeparatedList ( SyntaxFactory.AttributeArgument ( SyntaxFactory.LiteralExpression(SyntaxKind.StringLiteralExpression, SyntaxFactory.Literal(guid)) ) ) ) ) ) ) .NormalizeWhitespace(); var newDeclaration = declaration.AddAttributeLists(containerProviderAttribute); return(newDeclaration); }
private async static Task <Document> ChangeAttribute(Document document, Diagnostic diagnostic, CancellationToken cancellationToken) { if (diagnostic.Properties.TryGetValue("numericValue", out var value) && diagnostic.Properties.TryGetValue("type", out var type)) { var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var variable = root.FindNode(diagnostic.Location.SourceSpan) as VariableDeclaratorSyntax; var attributeArgument = SyntaxFactory.AttributeArgument( null, null, SyntaxFactory.LiteralExpression(SyntaxKind.StringLiteralExpression, CreateMagicStringValue(value, type))); var attribute = ((FieldDeclarationSyntax)variable.Parent.Parent).AttributeLists.First(); var newAttribute = SyntaxFactory.AttributeList(SyntaxFactory.SingletonSeparatedList( SyntaxFactory.Attribute(SyntaxFactory.IdentifierName("MagicNumber")) .WithArgumentList(SyntaxFactory.AttributeArgumentList(SyntaxFactory.SingletonSeparatedList(attributeArgument)))) ) .WithTriviaFrom(attribute); var newRoot = root.ReplaceNode(attribute, newAttribute); document = document.WithSyntaxRoot(newRoot); } return(document); }
public void ParameterTest(string attributeName, string[] attributeParameters, [Frozen] Mock <IAttributeArgumentDefinitionFactory> attributeParameterDefinitionFactoryMock, AttributeDefinitionFactory factory) { Expression <Func <IAttributeArgumentDefinitionFactory, AttributeArgumentDefinition> > attributeParameterExpression = f => f.CreateAttributeParameterFromSyntax(It.IsAny <AttributeArgumentSyntax>()); attributeParameterDefinitionFactoryMock.Setup(attributeParameterExpression).Returns(() => null) .Verifiable(); var attribute = SyntaxFactory.Attribute(SyntaxFactory.IdentifierName(attributeName)); foreach (var attributeParameter in attributeParameters) { attribute = attribute.AddArgumentListArguments( SyntaxFactory.AttributeArgument(SyntaxFactory.LiteralExpression(SyntaxKind.StringLiteralExpression, SyntaxFactory.Token(SyntaxFactory.TriviaList(), SyntaxKind.StringLiteralToken, attributeParameter, attributeParameter, SyntaxFactory.TriviaList())))); } var result = factory.CreateAttributeFromSyntax(attribute); Assert.Equal(attributeName, result.Name); Assert.Equal(attributeParameters.Length, result.Parameters.Length); attributeParameterDefinitionFactoryMock.Verify(attributeParameterExpression, Times.Exactly(attributeParameters.Length)); }
public static AttributeSyntax AddQuotedArgument(this AttributeSyntax attributeSyntax, object value) { var expression = SyntaxFactory.ParseExpression(string.Format("\"{0}\"", value)); var argument = SyntaxFactory.AttributeArgument(expression); return(attributeSyntax.AddArgumentListArguments(argument)); }
public static AttributeSyntax AddArgument(this AttributeSyntax attributeSyntax, object value) { var expression = SyntaxFactory.ParseExpression(value.ToString()); var argument = SyntaxFactory.AttributeArgument(expression); return(attributeSyntax.AddArgumentListArguments(argument)); }
public override SyntaxNode VisitAttributeList(AttributeListSyntax node) { // Override ettiğimi fonksiyon içerisinde Metotlara uygulanan Attribute'ları dolaşıyoruz. if (node.Parent is MethodDeclarationSyntax && node.Attributes.Any(attr => attr.Name.GetText().ToString() == "WSATEnable")) { /* * Aşağıdaki kod parçasında WSATEnable niteliği için yeni bir argüman listesi oluşturuyoruz. * Buna göre Niteliğin adı yine WSATEnable. * Diğer yandan Active parametresini false, * Target parametresini de MQ olarak değiştirmekteyiz. */ return(SyntaxFactory.AttributeList( SyntaxFactory.SingletonSeparatedList( SyntaxFactory.Attribute(SyntaxFactory.IdentifierName("WSATEnable"), SyntaxFactory.AttributeArgumentList( SyntaxFactory.SeparatedList(new[] { SyntaxFactory.AttributeArgument( nameEquals: SyntaxFactory.NameEquals("Active"), nameColon: null, SyntaxFactory.LiteralExpression(SyntaxKind.FalseLiteralExpression)), SyntaxFactory.AttributeArgument( nameEquals: SyntaxFactory.NameEquals("Target"), nameColon: null, SyntaxFactory.LiteralExpression(SyntaxKind.StringLiteralExpression, SyntaxFactory.Literal(@"MQ"))) }))))).WithTrailingTrivia(SyntaxFactory.ElasticCarriageReturnLineFeed)); // ElasticCarriageReturnLineFeed ile alt satır inilmesini sağladık. Aksi durumda class ile attribute aynı satırda oluyordu. } // Tabii if koşuluna uymayan bir ifade ile karşılaştıysak yolumuza devam ediyoruz return(base.VisitAttributeList(node)); }
private async Task <Solution> AddSwaggerOperationAttribute(Document document, MethodDeclarationSyntax methodDeclaration, CancellationToken cancellationToken) { var attributeValue = GetAttributeValue(methodDeclaration); var liralExpression = SyntaxFactory.LiteralExpression(SyntaxKind.StringLiteralExpression, SyntaxFactory.Token(default(SyntaxTriviaList), SyntaxKind.StringLiteralToken, attributeValue, attributeValue, default(SyntaxTriviaList))); var attributeArgument = SyntaxFactory.AttributeArgument(liralExpression); var attributeList = new SeparatedSyntaxList <AttributeArgumentSyntax>(); attributeList = attributeList.Add(attributeArgument); var argumentList = SyntaxFactory.AttributeArgumentList(attributeList); var attributes = methodDeclaration.AttributeLists.Add( SyntaxFactory.AttributeList(SyntaxFactory.SingletonSeparatedList <AttributeSyntax>( SyntaxFactory.Attribute(SyntaxFactory.IdentifierName(swaggerOperationAttributeName)) .WithArgumentList(argumentList) ) ) ); var root = await document.GetSyntaxRootAsync(cancellationToken); return(document.WithSyntaxRoot( root.ReplaceNode( methodDeclaration, methodDeclaration.WithAttributeLists(attributes) )).Project.Solution); }
private AttributeSyntax TransformExplicitAttribute(AttributeSyntax node) { var location = node.GetLocation(); var original = node.ToFullString(); // MSTest V2 does not support "[Explicit]". // Convert "[Explicit]" to "[Ignore("EXPLICIT")]" // Convert "[Explicit("yadayada")]" to "[Ignore("EXPLICIT: yadayada")]" string text = "EXPLICIT"; var description = node.GetPositionExpression(0); if (description != null) { text += ": " + description.GetFirstToken().ValueText; } var literalExpression = SyntaxFactory.LiteralExpression( SyntaxKind.StringLiteralExpression, SyntaxFactory.Literal("\"" + text + "\"", text)); var arguments = new SeparatedSyntaxList <AttributeArgumentSyntax>(); arguments = arguments.Add(SyntaxFactory.AttributeArgument(literalExpression)); node = node.WithName(SyntaxFactory.IdentifierName("Ignore")).WithArgumentList( SyntaxFactory.AttributeArgumentList(arguments)); m_diagnostics.Add(Diagnostic.Create(DiagnosticsDescriptors.TransformedUnsupported, location, original, node.ToFullString())); return(node); }
private static AttributeArgumentListSyntax?GenerateAttributeArgumentList( AttributeData attribute ) { if (attribute.ConstructorArguments.Length == 0 && attribute.NamedArguments.Length == 0) { return(null); } var arguments = new List <AttributeArgumentSyntax>(); arguments.AddRange( attribute.ConstructorArguments.Select( c => SyntaxFactory.AttributeArgument(ExpressionGenerator.GenerateExpression(c)) ) ); arguments.AddRange( attribute.NamedArguments.Select( kvp => SyntaxFactory.AttributeArgument( SyntaxFactory.NameEquals(SyntaxFactory.IdentifierName(kvp.Key)), null, ExpressionGenerator.GenerateExpression(kvp.Value) ) ) ); return(SyntaxFactory.AttributeArgumentList(SyntaxFactory.SeparatedList(arguments))); }
public override IEnumerable <SyntaxNode> BuildSyntax(IDom item) { var itemAsT = item as IAttributeValue; var argNameSyntax = SyntaxFactory.IdentifierName(itemAsT.Name); argNameSyntax = BuildSyntaxHelpers.AttachWhitespaceToFirst(argNameSyntax, item.Whitespace2Set[LanguageElement.AttributeValueName]); argNameSyntax = BuildSyntaxHelpers.AttachWhitespaceToLast(argNameSyntax, item.Whitespace2Set[LanguageElement.AttributeValueName]); //var kind = Mappings.SyntaxKindFromLiteralKind(itemAsT.ValueType, itemAsT.Value); ExpressionSyntax expr = BuildSyntaxHelpers.BuildArgValueExpression( itemAsT.Value, itemAsT.ValueConstantIdentifier, itemAsT.ValueType); var node = SyntaxFactory.AttributeArgument(expr); if (itemAsT.Style == AttributeValueStyle.Colon) { var nameColon = SyntaxFactory.NameColon(argNameSyntax); nameColon = BuildSyntaxHelpers.AttachWhitespaceToLast(nameColon, item.Whitespace2Set[LanguageElement.AttributeValueEqualsOrColon]); node = node.WithNameColon(nameColon); } else if (itemAsT.Style == AttributeValueStyle.Equals) { var nameEquals = SyntaxFactory.NameEquals(argNameSyntax); nameEquals = BuildSyntaxHelpers.AttachWhitespaceToLast(nameEquals, item.Whitespace2Set[LanguageElement.AttributeValueEqualsOrColon]); node = node.WithNameEquals(nameEquals); } node = BuildSyntaxHelpers.AttachWhitespaceToFirstAndLast(node, item.Whitespace2Set[LanguageElement.AttributeValueValue]); return(node.PrepareForBuildSyntaxOutput(item, OutputContext)); }
public SyntaxList <AttributeListSyntax> AddIniOptionsAttributeToProperty(string section, string key) { return(SyntaxFactory.SingletonList <AttributeListSyntax>( SyntaxFactory.AttributeList( SyntaxFactory.SingletonSeparatedList <AttributeSyntax>( SyntaxFactory.Attribute( SyntaxFactory.IdentifierName("IniOptions")) .WithArgumentList( SyntaxFactory.AttributeArgumentList( SyntaxFactory.SeparatedList <AttributeArgumentSyntax>( new SyntaxNodeOrToken[] { SyntaxFactory.AttributeArgument( SyntaxFactory.LiteralExpression( SyntaxKind.StringLiteralExpression, SyntaxFactory.Literal(section))) .WithNameEquals( SyntaxFactory.NameEquals( SyntaxFactory.IdentifierName("Section"))), SyntaxFactory.Token(SyntaxKind.CommaToken), SyntaxFactory.AttributeArgument( SyntaxFactory.LiteralExpression( SyntaxKind.StringLiteralExpression, SyntaxFactory.Literal(key))) .WithNameEquals( SyntaxFactory.NameEquals( SyntaxFactory.IdentifierName("Key"))) }))))))); }
public override SyntaxNode VisitClassDeclaration(ClassDeclarationSyntax node) { var identifierToken = node.Identifier.ToString(); var leadingTrivia = node.GetLeadingTrivia(); var obsoleteExpression = SyntaxFactory.AttributeList ( SyntaxFactory.SingletonSeparatedList <AttributeSyntax> ( SyntaxFactory.Attribute ( SyntaxFactory.IdentifierName("Obsolete") ) .WithArgumentList ( SyntaxFactory.AttributeArgumentList ( SyntaxFactory.SingletonSeparatedList <AttributeArgumentSyntax> ( SyntaxFactory.AttributeArgument ( SyntaxFactory.LiteralExpression ( SyntaxKind.StringLiteralExpression, SyntaxFactory.Literal("Use " + identifierToken[0].ToString().ToUpper() + identifierToken.Substring(1) + " instead") ) ) ) ) ) ) ).WithLeadingTrivia(leadingTrivia); //char.IsLower(identifierToken[0]) if (identifierToken[0] >= 'a' && identifierToken[0] <= 'z') { //identifierToken[0].ToString().ToUpper(); /* var obsoleteExpression = * SyntaxFactory.AttributeList( * SyntaxFactory.Attribute( * SyntaxFactory.IdentifierName("Obsolete").WithLeadingTrivia(leadingTrivia)), * SyntaxFactory.AttributeArgumentList( * SyntaxFactory.SingletonSeparatedList<AttributeArgumentSyntax>( * SyntaxFactory.AttributeArgument( * SyntaxFactory.LiteralExpression(SyntaxKind.StringLiteralExpression, SyntaxFactory.Literal(node.Identifier) * * * ))))); */ node = node.AddAttributeLists(obsoleteExpression); } return(base.VisitClassDeclaration(node)); }
internal override Task <Document> GetUpdatedDocumentAsync(Document document, SemanticModel model, SyntaxNode root, SyntaxNode nodeToFix, Diagnostic diagnostic, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); var charSetType = WellKnownTypes.CharSet(model.Compilation); var dllImportType = WellKnownTypes.DllImportAttribute(model.Compilation); var marshalAsType = WellKnownTypes.MarshalAsAttribute(model.Compilation); var unmanagedType = WellKnownTypes.UnmanagedType(model.Compilation); if (charSetType == null || dllImportType == null || marshalAsType == null || unmanagedType == null) { return(Task.FromResult(document)); } var syntaxFactoryService = document.Project.LanguageServices.GetService <SyntaxGenerator>(); // return the unchanged root if no fix is available var newRoot = root; if (nodeToFix.Kind() == SyntaxKind.Attribute) { // could be either a [DllImport] or [MarshalAs] attribute var attribute = (AttributeSyntax)nodeToFix; var attributeType = model.GetSymbolInfo(attribute).Symbol; var arguments = attribute.ArgumentList.Arguments; if (dllImportType.Equals(attributeType.ContainingType)) { // [DllImport] attribute, add or replace CharSet named parameter var argumentValue = CreateCharSetArgument(syntaxFactoryService, charSetType).WithAdditionalAnnotations(Formatter.Annotation); var namedParameter = arguments.FirstOrDefault(arg => arg.NameEquals != null && arg.NameEquals.Name.Identifier.Text == CharSetText); if (namedParameter == null) { // add the parameter namedParameter = SyntaxFactory.AttributeArgument(SyntaxFactory.NameEquals(CharSetText), null, (ExpressionSyntax)argumentValue) .WithAdditionalAnnotations(Formatter.Annotation); var newArguments = arguments.Add(namedParameter); var newArgumentList = attribute.ArgumentList.WithArguments(newArguments); newRoot = root.ReplaceNode(attribute.ArgumentList, newArgumentList); } else { // replace the parameter var newNamedParameter = namedParameter.WithExpression((ExpressionSyntax)argumentValue); newRoot = root.ReplaceNode(namedParameter, newNamedParameter); } } else if (marshalAsType.Equals(attributeType.ContainingType) && arguments.Count == 1) { // [MarshalAs] attribute, replace the only argument var newExpression = CreateMarshalAsArgument(syntaxFactoryService, unmanagedType) .WithLeadingTrivia(arguments[0].GetLeadingTrivia()) .WithTrailingTrivia(arguments[0].GetTrailingTrivia()); var newArgument = arguments[0].WithExpression((ExpressionSyntax)newExpression); newRoot = root.ReplaceNode(arguments[0], newArgument); } } return(Task.FromResult(document.WithSyntaxRoot(newRoot))); }