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);
            }
Ejemplo n.º 2
0
        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);
        }
Ejemplo n.º 3
0
        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)))))));
        }
Ejemplo n.º 4
0
        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));
        }
Ejemplo n.º 6
0
        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))));
        }
Ejemplo n.º 7
0
        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);
        }
Ejemplo n.º 8
0
        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}")))))));
        }
Ejemplo n.º 9
0
        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)
                                     )
                                 )
     }
                                                    )
                        )
                    )
                ));
 }
Ejemplo n.º 11
0
 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")))
     })))))));
 }
Ejemplo n.º 12
0
        public override SyntaxNode MakeSyntaxNode()
        {
            var res = SyntaxFactory.AttributeArgumentList(OpenParenToken, Arguments, CloseParenToken);

            IsChanged = false;
            return(res);
        }
        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)))
            }))))))));
        }
Ejemplo n.º 14
0
        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)));
        }
Ejemplo n.º 15
0
        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);
        }
Ejemplo n.º 16
0
        private async Task <Solution> CreateTestCategoryAttribute(Document document, Diagnostic diagnostic, MethodDeclarationSyntax methodDeclaration, CancellationToken cancellationToken)
        {
            var root = await document.GetSyntaxRootAsync(cancellationToken);

            var frameworkAnalyzerUsed = FrameworkAnalyzers.FirstOrDefault(analyzer => analyzer.GetType().FullName == diagnostic.Properties[nameof(IFrameworkAnalyzer)]);

            string testCategoryAttribute = frameworkAnalyzerUsed.TestCategoryAttribute;

            SyntaxNodeOrTokenList attributeArguments = frameworkAnalyzerUsed.GetTestCategoryAttributeArguments();

            var currentIndent = methodDeclaration.GetLeadingTrivia().Where(t => t.IsKind(SyntaxKind.WhitespaceTrivia));

            var attributes = methodDeclaration.AttributeLists.Add(
                SyntaxFactory.AttributeList(
                    SyntaxFactory.SingletonSeparatedList(
                        SyntaxFactory.Attribute(
                            SyntaxFactory.IdentifierName(testCategoryAttribute))
                        .WithArgumentList(SyntaxFactory
                                          .AttributeArgumentList(SyntaxFactory
                                                                 .SeparatedList <AttributeArgumentSyntax>(attributeArguments)))

                        )).NormalizeWhitespace()
                .WithLeadingTrivia(currentIndent)
                .WithTrailingTrivia(SyntaxFactory.Whitespace(Environment.NewLine)));

            document = document.WithSyntaxRoot(
                root.ReplaceNode(
                    methodDeclaration,
                    methodDeclaration.WithAttributeLists(attributes)
                    ));

            return(document.Project.Solution);
        }
Ejemplo n.º 17
0
        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));
        }
Ejemplo n.º 18
0
        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);
        }
Ejemplo n.º 19
0
        private IEnumerable <SyntaxNode> BuildSyntax(IAttribute item)
        {
            var itemAsT    = item as IAttribute;
            var nameSyntax = SyntaxFactory.ParseName(itemAsT.Name);

            var node = SyntaxFactory.Attribute(nameSyntax);

            node = BuildSyntaxHelpers.AttachWhitespace(node, item.Whitespace2Set, WhitespaceLookup);
            var attributeArgList = itemAsT.AttributeValues
                                   .SelectMany(x => RDom.CSharp.GetSyntaxGroup(x))
                                   .OfType <AttributeArgumentSyntax>()
                                   .ToList();

            if (attributeArgList.Any())
            {
                var argList = SyntaxFactory.AttributeArgumentList(
                    SyntaxFactory.SeparatedList(attributeArgList));
                argList = BuildSyntaxHelpers.AttachWhitespace(argList, item.Whitespace2Set, WhitespaceLookup);
                node    = node.WithArgumentList(argList);
            }

            var nodeList = SyntaxFactory.AttributeList(
                SyntaxFactory.SeparatedList(
                    new AttributeSyntax[] {
                (AttributeSyntax)BuildSyntaxHelpers.PrepareForBuildItemSyntaxOutput(node, item, OutputContext)
            }));

            nodeList = BuildSyntaxHelpers.AttachWhitespace(nodeList, item.Whitespace2Set, WhitespaceLookup);

            return(nodeList.PrepareForBuildSyntaxOutput(item, OutputContext));
        }
Ejemplo n.º 20
0
        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));
        }
Ejemplo n.º 21
0
        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);
        }
Ejemplo n.º 22
0
        public override SyntaxNode VisitClassDeclaration(ClassDeclarationSyntax node)
        {
            var identifierToken = node.Identifier.ToString();

            var leadingTrivia = node.GetLeadingTrivia();

            var obsoleteExpression =

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

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


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

                node = node.AddAttributeLists(obsoleteExpression);
            }

            return(base.VisitClassDeclaration(node));
        }
Ejemplo n.º 23
0
        public DummyRewriter()
        {
            var expArg          = SyntaxFactory.AttributeArgument(SyntaxFactory.LiteralExpression(SyntaxKind.StringLiteralExpression, SyntaxFactory.Literal("EXP")));
            var conditionalArgs = SyntaxFactory.AttributeArgumentList(SyntaxFactory.SeparatedList(new[] { expArg }));
            var conditionalAttr = SyntaxFactory.Attribute(SyntaxFactory.IdentifierName("Conditional"), conditionalArgs);

            conditionalAttributeSyntax = SyntaxFactory.AttributeList(SyntaxFactory.SeparatedList(new[] { conditionalAttr }));
        }
Ejemplo n.º 24
0
 private static AttributeSyntax CreateProducesResponseTypeAttribute(int statusCode)
 {
     return(SyntaxFactory.Attribute(
                SyntaxFactory.ParseName(ApiSymbolNames.ProducesResponseTypeAttribute)
                .WithAdditionalAnnotations(Simplifier.Annotation),
                SyntaxFactory.AttributeArgumentList().AddArguments(
                    SyntaxFactory.AttributeArgument(
                        SyntaxFactory.LiteralExpression(SyntaxKind.NumericLiteralExpression, SyntaxFactory.Literal(statusCode))))));
 }
        private static AttributeSyntax CreateProducesResponseTypeAttribute(CodeActionContext context, int statusCode, out bool addUsingDirective)
        {
            var statusCodeSyntax = CreateStatusCodeSyntax(context, statusCode, out addUsingDirective);

            return(SyntaxFactory.Attribute(
                       SyntaxFactory.ParseName(ApiSymbolNames.ProducesResponseTypeAttribute)
                       .WithAdditionalAnnotations(Simplifier.Annotation),
                       SyntaxFactory.AttributeArgumentList().AddArguments(
                           SyntaxFactory.AttributeArgument(statusCodeSyntax))));
        }
        private SeparatedSyntaxList <AttributeSyntax> CreateAttribute(SeparatedSyntaxList <AttributeArgumentSyntax> arguments)
        {
            AttributeArgumentListSyntax newArguments = SyntaxFactory.AttributeArgumentList(SyntaxFactory.Token(SyntaxKind.OpenParenToken),
                                                                                           arguments, SyntaxFactory.Token(SyntaxKind.CloseParenToken));
            SeparatedSyntaxList <AttributeSyntax> attributeWhole = new SeparatedSyntaxList <AttributeSyntax>();

            attributeWhole = attributeWhole.Add(
                SyntaxFactory.Attribute(SyntaxFactory.ParseName(AttributeName), newArguments));

            return(attributeWhole);
        }
Ejemplo n.º 27
0
        private static AttributeArgumentListSyntax GetAttributeArgumentListSyntax(List <AttributeArgumentData> arguments)
        {
            var argumentListSyntax = SyntaxFactory.AttributeArgumentList();

            for (int i = 0, count = arguments.Count; i < count; i++)
            {
                argumentListSyntax = argumentListSyntax.AddArguments(GetAttributeArgumentSyntax(arguments[i]));
            }

            return(argumentListSyntax);
        }
Ejemplo n.º 28
0
        private static SyntaxNode Snooze(SyntaxNode root, AttributeSyntax attributeSyntax, string message)
        {
            var newMessage = ObsoleteAfterAnalyzer.Regex.Replace(message, $"{DateTime.Now.AddDays(1):yyyy-MM-dd}");

            var newAttribute = attributeSyntax
                .WithArgumentList(SyntaxFactory.AttributeArgumentList())
                .AddArgumentListArguments(SyntaxFactory.AttributeArgument(SyntaxFactory.LiteralExpression(SyntaxKind.StringLiteralExpression, SyntaxFactory.Literal(newMessage))))
                .NormalizeWhitespace();

            return root.ReplaceNode(attributeSyntax, newAttribute);
        }
Ejemplo n.º 29
0
        protected AttributeListSyntax GetTypeAttributes(string typeName)
        {
            var attributeArguments = SyntaxFactory.SingletonSeparatedList(
                SyntaxFactory.AttributeArgument(SyntaxFactory.ParseExpression($"\"{typeName}\"")));

            var attribute = SyntaxFactory.Attribute(
                SyntaxFactory.ParseName("GraphQLType"),
                SyntaxFactory.AttributeArgumentList(attributeArguments));

            return(SyntaxFactory.AttributeList(
                       SyntaxFactory.SingletonSeparatedList(attribute)));
        }
Ejemplo n.º 30
0
        private AttributeSyntax GenerateStructLayout()
        {
            var arg = SyntaxFactory.AttributeArgument(
                SyntaxFactory.MemberAccessExpression(
                    SyntaxKind.SimpleMemberAccessExpression,
                    SyntaxFactory.IdentifierName(nameof(LayoutKind)),
                    SyntaxFactory.IdentifierName(nameof(LayoutKind.Sequential))));

            return(SyntaxFactory.Attribute(
                       SyntaxFactory.ParseName("System.Runtime.InteropServices.StructLayoutAttribute"),
                       SyntaxFactory.AttributeArgumentList(SyntaxFactory.SeparatedList(new[] { arg }))));
        }