Пример #1
0
        /// <summary>
        /// From a FieldDeclarationSyntax, returns the field name.
        /// </summary>
        /// <param name="field"></param>
        /// <returns></returns>
        public static String FieldName(this FieldDeclarationSyntax field)
        {
            var vars = field.DescendantNodes().Where(i => i.IsKind(SyntaxKind.VariableDeclarator));
            VariableDeclaratorSyntax varName = (VariableDeclaratorSyntax)vars.First();

            return(varName.Identifier.ToString());
        }
        public void Then_result_should_be_VariableDeclaration_with_Identifier_Bla()
        {
            var variableDeclaratorSyntax =
                _fieldDeclaration.DescendantNodes().OfType <VariableDeclaratorSyntax>().FirstOrDefault();

            variableDeclaratorSyntax.Identifier.Text.Should().Be("Bla");
        }
        /// <summary>
        /// Analyzes node.
        /// </summary>
        /// <param name="context">The context.</param>
        private static void AnalyzeNode(SyntaxNodeAnalysisContext context)
        {
            FieldDeclarationSyntax node = context.Node as FieldDeclarationSyntax;

            // Only const field.
            if (!node.Modifiers.Any(SyntaxKind.ConstKeyword))
            {
                return;
            }

            if (Configuration.IsEnabledForPublicMembersOnly && PrivateMemberChecker.IsPrivateMember(node))
            {
                return;
            }

            DocumentationCommentTriviaSyntax commentTriviaSyntax = node
                                                                   .GetLeadingTrivia()
                                                                   .Select(o => o.GetStructure())
                                                                   .OfType <DocumentationCommentTriviaSyntax>()
                                                                   .FirstOrDefault();

            if (commentTriviaSyntax != null && CommentHelper.HasComment(commentTriviaSyntax))
            {
                return;
            }

            VariableDeclaratorSyntax field = node.DescendantNodes().OfType <VariableDeclaratorSyntax>().First();

            context.ReportDiagnostic(Diagnostic.Create(Rule, field.GetLocation()));
        }
Пример #4
0
        /// <summary>
        /// Analyzes node.
        /// </summary>
        /// <param name="context">The context.</param>
        private static void AnalyzeNode(SyntaxNodeAnalysisContext context)
        {
            FieldDeclarationSyntax node = context.Node as FieldDeclarationSyntax;

            // Only const.
            if (!node.Modifiers.Any(SyntaxKind.ConstKeyword))
            {
                return;
            }

            DocumentationCommentTriviaSyntax commentTriviaSyntax = node
                                                                   .GetLeadingTrivia()
                                                                   .Select(o => o.GetStructure())
                                                                   .OfType <DocumentationCommentTriviaSyntax>()
                                                                   .FirstOrDefault();

            if (commentTriviaSyntax != null)
            {
                bool hasSummary = commentTriviaSyntax
                                  .ChildNodes()
                                  .OfType <XmlElementSyntax>()
                                  .Any(o => o.StartTag.Name.ToString().Equals(DocumentationHeaderHelper.Summary));

                if (hasSummary)
                {
                    return;
                }
            }

            VariableDeclaratorSyntax field = node.DescendantNodes().OfType <VariableDeclaratorSyntax>().First();

            context.ReportDiagnostic(Diagnostic.Create(Rule, field.GetLocation()));
        }
        public static bool ImplementsInterface <T>(this FieldDeclarationSyntax field, SemanticModel semanticModel)
        {
            var variableDeclaration = field.DescendantNodes().OfType <VariableDeclarationSyntax>().First();
            var variableType        = semanticModel.GetTypeInfo(variableDeclaration.Type).Type;

            return(variableType.ImplementsInterface <T>());
        }
        private Task <Document> AddConstructorAsync(Document document, SyntaxNode root, FieldDeclarationSyntax fieldDeclaration)
        {
            var variableDeclaration = fieldDeclaration.DescendantNodes().OfType <VariableDeclarationSyntax>().FirstOrDefault();
            var variableDeclarator  = variableDeclaration.DescendantNodes().OfType <VariableDeclaratorSyntax>().FirstOrDefault();
            var fieldName           = variableDeclarator.Identifier.ValueText;

            var typeDeclaration = fieldDeclaration.GetParentTypeDeclaration();

            var newConstructor = CreateEmptyConstructor(typeDeclaration.Identifier.ValueText);
            var parameterName  = nameGenerator.GetNewParameterName(newConstructor.ParameterList, fieldName);

            newConstructor = newConstructor.WithParameterList(
                ParameterList(
                    SingletonSeparatedList(
                        Parameter(Identifier(parameterName))
                        .WithType(variableDeclaration.Type))));

            var assignment = newConstructor.ParameterList.Parameters.Any(p => p.Identifier.ValueText == fieldName)
                    ? CreateThisAssignmentStatement(fieldName, parameterName)
                    : CreateAssignmentStatement(fieldName, parameterName);

            newConstructor = newConstructor.WithBody(newConstructor.Body.AddStatements(assignment));
            newConstructor = InitializeStructFields(fieldDeclaration, typeDeclaration, newConstructor);

            var newRoot = root.InsertNodesAfter(FindInsertionPoint(fieldDeclaration), SingletonList(newConstructor));

            return(Task.FromResult(document.WithSyntaxRoot(newRoot)));
        }
Пример #7
0
        /// <summary>
        /// Get summary.
        /// </summary>
        /// <param name="theSyntaxNode">The syntax node to add the summary.</param>
        /// <returns>The syntax list.</returns>
        private static DocumentationCommentTriviaSyntax GetSummary(FieldDeclarationSyntax theSyntaxNode)
        {
            var summaryStart = XmlElementStartTag(XmlName(Identifier(Constants.Summary)))
                               .WithLessThanToken(Token(SyntaxKind.LessThanToken))
                               .WithGreaterThanToken(Token(SyntaxKind.GreaterThanToken)).NormalizeWhitespace();

            var summaryEnd = XmlElementEndTag(XmlName(Identifier(Constants.Summary))).NormalizeWhitespace()
                             .WithLessThanSlashToken(Token(SyntaxKind.LessThanSlashToken))
                             .WithGreaterThanToken(Token(SyntaxKind.GreaterThanToken));

            var summaryComment = string.Empty;
            var field          = theSyntaxNode.DescendantNodes().OfType <VariableDeclaratorSyntax>().FirstOrDefault();

            if (field != null)
            {
                var hasConst    = theSyntaxNode.Modifiers.Any(SyntaxKind.ConstKeyword);
                var hasReadOnly = theSyntaxNode.Modifiers.Any(SyntaxKind.ReadOnlyKeyword);

                var equals = field.DescendantNodes().OfType <EqualsValueClauseSyntax>().FirstOrDefault();

                summaryComment = " " + Convert.Field(field.Identifier.ValueText, hasConst, hasReadOnly, equals);
            }

            var summaryText = SingletonList <XmlNodeSyntax>(
                XmlText().NormalizeWhitespace()
                .WithTextTokens(
                    TokenList(
                        XmlTextNewLine(TriviaList(), Environment.NewLine, Environment.NewLine, TriviaList()).NormalizeWhitespace(),
                        XmlTextLiteral(
                            TriviaList(DocumentationCommentExterior("///")),
                            summaryComment,
                            summaryComment,
                            TriviaList()).NormalizeWhitespace(),
                        XmlTextNewLine(TriviaList(), Environment.NewLine, Environment.NewLine, TriviaList()).NormalizeWhitespace(),
                        XmlTextLiteral(
                            TriviaList(DocumentationCommentExterior("///")),
                            " ",
                            " ",
                            TriviaList()))).NormalizeWhitespace());

            var xmlComment = XmlText()
                             .WithTextTokens(
                TokenList(
                    XmlTextLiteral(
                        TriviaList(DocumentationCommentExterior("///")),
                        " ",
                        " ",
                        TriviaList()))).NormalizeWhitespace();

            var newLine = XmlText().WithTextTokens(TokenList(XmlTextNewLine(TriviaList(), Environment.NewLine, Environment.NewLine, TriviaList()))).NormalizeWhitespace();

            var summaryElement = XmlElement(summaryStart, summaryEnd).WithContent(summaryText);

            var list = List(new XmlNodeSyntax[] { xmlComment, summaryElement, newLine });

            return(DocumentationCommentTrivia(SyntaxKind.SingleLineDocumentationCommentTrivia, list));
        }
Пример #8
0
        /// <summary>
        /// Adds documentation header async.
        /// </summary>
        /// <param name="document">The document.</param>
        /// <param name="root">The root.</param>
        /// <param name="declarationSyntax">The declaration syntax.</param>
        /// <param name="cancellationToken">The cancellation token.</param>
        /// <returns>A Document.</returns>
        private async Task <Document> AddDocumentationHeaderAsync(Document document, SyntaxNode root, FieldDeclarationSyntax declarationSyntax, CancellationToken cancellationToken)
        {
            SyntaxTriviaList leadingTrivia = declarationSyntax.GetLeadingTrivia();

            VariableDeclaratorSyntax field = declarationSyntax.DescendantNodes().OfType <VariableDeclaratorSyntax>().First();
            string comment = CommentHelper.CreateFieldComment(field.Identifier.ValueText);
            DocumentationCommentTriviaSyntax commentTrivia = await Task.Run(() => DocumentationHeaderHelper.CreateOnlySummaryDocumentationCommentTrivia(comment), cancellationToken);

            SyntaxTriviaList       newLeadingTrivia = leadingTrivia.Insert(leadingTrivia.Count - 1, SyntaxFactory.Trivia(commentTrivia));
            FieldDeclarationSyntax newDeclaration   = declarationSyntax.WithLeadingTrivia(newLeadingTrivia);

            SyntaxNode newRoot = root.ReplaceNode(declarationSyntax, newDeclaration);

            return(document.WithSyntaxRoot(newRoot));
        }
Пример #9
0
        private async Task <Document> InitializeFieldInConstructorsAsync(Document document, SyntaxNode root,
                                                                         FieldDeclarationSyntax fieldDeclaration, IEnumerable <ConstructorDeclarationSyntax> constructors,
                                                                         CancellationToken cancellationToken)
        {
            var variableDeclaration = fieldDeclaration.DescendantNodes().OfType <VariableDeclarationSyntax>().FirstOrDefault();
            var variableDeclarator  = variableDeclaration.DescendantNodes().OfType <VariableDeclaratorSyntax>().FirstOrDefault();
            var fieldName           = variableDeclarator.Identifier.ValueText;

            var model = await document.GetSemanticModelAsync(cancellationToken);

            var fieldSymbol = model.GetDeclaredSymbol(variableDeclarator, cancellationToken) as IFieldSymbol;

            var trackedRoot = root.TrackNodes(constructors);

            foreach (var constructor in constructors)
            {
                var currentConstructor = trackedRoot.GetCurrentNode(constructor);
                var newConstructor     = currentConstructor;

                string parameterName;
                var    existingParameter = FindExistingParameter(model, fieldSymbol, constructor, cancellationToken);
                if (existingParameter != null)
                {
                    parameterName = existingParameter.Identifier.ValueText;
                }
                else
                {
                    parameterName  = nameGenerator.GetNewParameterName(currentConstructor.ParameterList, fieldName);
                    newConstructor = currentConstructor.WithParameterList(currentConstructor.ParameterList.AddParameters(
                                                                              Parameter(Identifier(parameterName))
                                                                              .WithType(variableDeclaration.Type)));
                }

                var assignment = newConstructor.ParameterList.Parameters.Any(p => p.Identifier.ValueText == fieldName)
                    ? CreateThisAssignmentStatement(fieldName, parameterName)
                    : CreateAssignmentStatement(fieldName, parameterName);
                newConstructor = newConstructor.WithBody(newConstructor.Body.AddStatements(assignment));

                trackedRoot = trackedRoot.ReplaceNode(currentConstructor, newConstructor);
            }

            return(document.WithSyntaxRoot(trackedRoot));
        }
            public override void VisitFieldDeclaration(FieldDeclarationSyntax node)
            {
                VariableDeclaratorSyntax variableDeclaration = node.DescendantNodes().OfType<VariableDeclaratorSyntax>().First();

                FieldSymbol field = (FieldSymbol) _semanticModel.GetDeclaredSymbol(variableDeclaration);

                if (field != null)
                {

                    var attributes = field.GetAttributes();

                    foreach (AttributeData attribute in attributes)
                    {
                        if (attribute.IsInstanceOfAttributeType<GuardedByAttribute>())
                        {
                            GuardedFieldInfo guardedField = new GuardedFieldInfo(node, field, attribute, _semanticModel);

                            _guardedFields.Add(guardedField);
                        }
                        else if (attribute.IsInstanceOfAttributeType<LockAttribute>())
                        {
                            LockInfo lockField = new LockInfo(node, field, attribute, _semanticModel);

                            _locks.Add(lockField);
                        }
                        else
                        {
                            //do nothing
                        }
                    }
                }
                base.VisitFieldDeclaration(node);
            }