public override void VisitConstructorDeclaration(ConstructorDeclarationSyntax node) { var docComment = node.GetLeadingTrivia().Select(i => i.GetStructure()).OfType <DocumentationCommentTriviaSyntax>().FirstOrDefault(); _parsedMembers.Add(new ParsedMember(node, docComment)); base.VisitConstructorDeclaration(node); }
private async Task <Document> UpdateDataRowConstructor(Document document, TypeDeclarationSyntax typeDeclaration, ConstructorDeclarationSyntax constructorDeclaration, CancellationToken ct) { var unsetProperties = Helper.GetClassUnsetProperties(typeDeclaration, constructorDeclaration); SyntaxTriviaList leadingTrivia; SyntaxList <StatementSyntax> statements; if (constructorDeclaration.Body is null) { leadingTrivia = constructorDeclaration.GetLeadingTrivia(); } else { statements = constructorDeclaration.Body.Statements; leadingTrivia = statements.Any() ? statements.First().GetLeadingTrivia() : constructorDeclaration.GetLeadingTrivia(); } foreach (var property in unsetProperties) { var assigment = CreatePropertyAssigmentExpression(constructorDeclaration.ParameterList.Parameters[0], property); statements = statements.Add(SyntaxFactory.ExpressionStatement(assigment).WithLeadingTrivia(leadingTrivia)); } // Копируем параметры конструктора, заменяя только Body. var updatedConstructor = SyntaxFactory.ConstructorDeclaration(constructorDeclaration.AttributeLists, constructorDeclaration.Modifiers, constructorDeclaration.Identifier, constructorDeclaration.ParameterList, constructorDeclaration.Initializer, SyntaxFactory.Block(statements)); // Replace the old constructor declaration with the new local declaration. var oldRoot = await document.GetSyntaxRootAsync(ct); var newRoot = oldRoot.ReplaceNode(constructorDeclaration, updatedConstructor); // Return document with transformed tree. return(document.WithSyntaxRoot(newRoot)); }
/// <summary> /// Analyzes node. /// </summary> /// <param name="context">The context.</param> private static void AnalyzeNode(SyntaxNodeAnalysisContext context) { ConstructorDeclarationSyntax node = context.Node as ConstructorDeclarationSyntax; 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; } } context.ReportDiagnostic(Diagnostic.Create(Rule, node.Identifier.GetLocation())); }
/// <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, ConstructorDeclarationSyntax declarationSyntax, CancellationToken cancellationToken) { SyntaxTriviaList leadingTrivia = declarationSyntax.GetLeadingTrivia(); DocumentationCommentTriviaSyntax commentTrivia = await Task.Run(() => CreateDocumentationCommentTriviaSyntax(declarationSyntax), cancellationToken); SyntaxTriviaList newLeadingTrivia = leadingTrivia.Insert(leadingTrivia.Count - 1, SyntaxFactory.Trivia(commentTrivia)); ConstructorDeclarationSyntax newDeclaration = declarationSyntax.WithLeadingTrivia(newLeadingTrivia); SyntaxNode newRoot = root.ReplaceNode(declarationSyntax, newDeclaration); return(document.WithSyntaxRoot(newRoot)); }
private static ConstructorDeclarationSyntax UpdateConstructor(ConstructorDeclarationSyntax constructor, ParameterSyntax parameter, ExpressionStatementSyntax assignment) { var constructorWithParams = constructor.AddParameterListParameters(parameter); var body = constructorWithParams.Body ?? Block(); var newBody = body.Statements.Insert(0, assignment); return(constructorWithParams .WithBody(body.WithStatements(newBody)) .WithLeadingTrivia(constructor.GetLeadingTrivia()) .WithTrailingTrivia(constructor.GetTrailingTrivia())); }
private async Task <Document> RemoveConstructor(Document document, Diagnostic diagnostic, ConstructorDeclarationSyntax ctor, CancellationToken c) { SyntaxNode rootNode = await document.GetSyntaxRootAsync(c).ConfigureAwait(false); var newCtor = ctor.WithLeadingTrivia(ctor.GetLeadingTrivia().Where(x => !(x.IsKind(SyntaxKind.SingleLineDocumentationCommentTrivia) || x.IsKind(SyntaxKind.MultiLineDocumentationCommentTrivia))).ToArray()); rootNode = rootNode.ReplaceNode(ctor, newCtor); ClassDeclarationSyntax cls = (ClassDeclarationSyntax)rootNode.DescendantNodesAndSelf().OfType <ClassDeclarationSyntax>().First(x => x.Identifier.Text == ctor.Identifier.Text); ctor = (ConstructorDeclarationSyntax)cls.Members.Where(x => x.IsKind(SyntaxKind.ConstructorDeclaration) && ((ConstructorDeclarationSyntax)x).Modifiers.Any(SyntaxKind.StaticKeyword)).First(); rootNode = rootNode.RemoveNode(ctor, SyntaxRemoveOptions.KeepDirectives | SyntaxRemoveOptions.KeepExteriorTrivia); return(document.WithSyntaxRoot(rootNode)); }
private async Task <ConstructorDeclarationSyntax> DocumentConstructorAsync(CodeFixContext context, ConstructorDeclarationSyntax constructor, CancellationToken cancellationToken) { if (constructor == null) { return(null); } SemanticModel semanticModel = await context.Document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); INamedTypeSymbol apiCallClass = semanticModel.GetDeclaredSymbol(constructor.FirstAncestorOrSelf <ClassDeclarationSyntax>(), cancellationToken); string parameterName = constructor.ParameterList.Parameters[0].Identifier.ValueText; DocumentationCommentTriviaSyntax documentationComment = XmlSyntaxFactory.DocumentationComment( XmlSyntaxFactory.SummaryElement( XmlSyntaxFactory.Text("Initializes a new instance of the "), XmlSyntaxFactory.SeeElement(SyntaxFactory.TypeCref(SyntaxFactory.ParseTypeName(apiCallClass.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat)))), XmlSyntaxFactory.Text(" class"), XmlSyntaxFactory.NewLine(), XmlSyntaxFactory.Text("with the behavior provided by another "), XmlSyntaxFactory.SeeElement(SyntaxFactory.TypeCref(SyntaxFactory.ParseTypeName("global::OpenStack.Net.IHttpApiCall<T>"))), XmlSyntaxFactory.Text(" instance.")), XmlSyntaxFactory.NewLine(), XmlSyntaxFactory.ParamElement( parameterName, XmlSyntaxFactory.List( XmlSyntaxFactory.Text("The "), XmlSyntaxFactory.SeeElement(SyntaxFactory.TypeCref(SyntaxFactory.ParseTypeName("global::OpenStack.Net.IHttpApiCall<T>"))), XmlSyntaxFactory.Text(" providing the behavior for the API call."))), XmlSyntaxFactory.NewLine(), XmlSyntaxFactory.ExceptionElement( SyntaxFactory.TypeCref(SyntaxFactory.ParseTypeName("global::System.ArgumentNullException")), XmlSyntaxFactory.List( XmlSyntaxFactory.Text("If "), XmlSyntaxFactory.ParamRefElement(parameterName), XmlSyntaxFactory.Text(" is "), XmlSyntaxFactory.NullKeywordElement(), XmlSyntaxFactory.Text(".")))) .WithAdditionalAnnotations(Simplifier.Annotation); SyntaxTrivia documentationTrivia = SyntaxFactory.Trivia(documentationComment); return(constructor.WithLeadingTrivia(constructor.GetLeadingTrivia().Add(documentationTrivia))); }
private static ConstructorDeclarationSyntax MakeConstructor( TypeDeclarationSyntax type, IEnumerable <Field> fields, ConstructorDeclarationSyntax maybePreviousConstructor) { var fieldsList = fields.ToList(); var constructorParameters = SF.ParameterList( SF.SeparatedList( fieldsList.Select( field => SF.Parameter(SF.Identifier(field.Name)) .WithType(field.Type) .WithAttributeLists(field.Attributes) ) ) ); var constructorBodyStatements = fieldsList.Select( field => SF.ExpressionStatement( SF.AssignmentExpression( SyntaxKind.SimpleAssignmentExpression, SF.MemberAccessExpression( SyntaxKind.SimpleMemberAccessExpression, SF.ThisExpression(), SF.IdentifierName(field.Name) ), SF.IdentifierName(field.Name) ) ) ); var previousAttributes = maybePreviousConstructor?.AttributeLists ?? new SyntaxList <AttributeListSyntax>(); var res = SF.ConstructorDeclaration(type.Identifier.Text) .WithAttributeLists(previousAttributes) .WithModifiers(SF.TokenList(new[] { SF.Token(SyntaxKind.PublicKeyword) })) .WithParameterList(constructorParameters) .WithBody(SF.Block(constructorBodyStatements)); res = fieldsList.Any(x => x.StructuredTrivia != null) ? res.WithLeadingTrivia( MakeXmlDocComments(maybePreviousConstructor, fieldsList, Constants.DefaultCtorSummary) ) : maybePreviousConstructor?.HasLeadingTrivia ?? false? res.WithLeadingTrivia(maybePreviousConstructor.GetLeadingTrivia()) : res; return(res); }
public override void VisitConstructorDeclaration(ConstructorDeclarationSyntax node) { var classDeclaration = node.Parent as ClassDeclarationSyntax; if (classDeclaration != null) { _visitingClass = classDeclaration.Identifier.ToString(); } { bool isPublic = node.IsPublic(); if (isPublic) { var docComment = node.GetLeadingTrivia().Select(i => i.GetStructure()).OfType <DocumentationCommentTriviaSyntax>().FirstOrDefault(); RhinoCommonClass.Get(_visitingClass).Constructors.Add(new Tuple <ConstructorDeclarationSyntax, DocumentationCommentTriviaSyntax>(node, docComment)); } } base.VisitConstructorDeclaration(node); }
private static Document ConstructorWithCommentPrepended( Document document, SyntaxNode root, ClassDeclarationSyntax @class, ConstructorDeclarationSyntax constructor, string errorMessage) { var commentWithEndOfLine = new[] { SF.Comment("//" + errorMessage) }; var existingLeadingTrivia = constructor.GetLeadingTrivia(); var combinedTrivia = SF.TriviaList( Enumerable.Concat(commentWithEndOfLine, existingLeadingTrivia)); var constructorWithNewLeadingTrivia = constructor.WithLeadingTrivia(combinedTrivia); var newClass = @class.ReplaceNode(constructor, constructorWithNewLeadingTrivia); var newDocumentRoot = root.ReplaceNode(@class, newClass); var newDocument = document.WithSyntaxRoot(newDocumentRoot); return(newDocument); }
public ConstructorInfo(ConstructorDeclarationSyntax decl, IMemberContainer parent) { var paramTypes = decl.ParameterList.Parameters .Select(p => p.Type.ToString()); if (decl.HasLeadingTrivia) { Documentation = GetDocumentation(decl.GetLeadingTrivia()); } Name = $"{decl.Identifier.Text}({string.Join(", ", paramTypes)})"; _parameters = Parse(decl.ParameterList); _modifiers = decl.Modifiers .ParseModifiers() .WithDefaultVisibility(Modifier.Private); Signature = $"{decl.Identifier.Text}({ParamSyntax()})"; ReturnType = "void"; Parent = parent; }
/// <summary> /// Analyzes node. /// </summary> /// <param name="context">The context.</param> private static void AnalyzeNode(SyntaxNodeAnalysisContext context) { ConstructorDeclarationSyntax node = context.Node as ConstructorDeclarationSyntax; 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; } context.ReportDiagnostic(Diagnostic.Create(Rule, node.Identifier.GetLocation())); }
public override SyntaxNode VisitConstructorDeclaration(ConstructorDeclarationSyntax node) { SyntaxTriviaList existingTrivia = node.GetLeadingTrivia(); // TODO: just existingTrivia.Any(SyntaxKind.DocumentationComment) should work here // but sometimes doc comments aren't picked up by Roslyn June 2012. if (!HasDocumentationComment(existingTrivia)) { MethodSymbol symbol = this.semanticModel.GetDeclaredSymbol(node); NamedTypeSymbol containingType = symbol.ContainingType; string containingTypeKind = symbol.ContainingType.TypeKind.ToString().ToLower(); string summary = string.Format( "/// <summary>\n" + "/// Initializes a new instance of the <see cref=\"{0}\"/> {1}.\n" + "/// </summary>\n", node.Identifier, containingTypeKind); var trivia = existingTrivia.Concat(Syntax.ParseLeadingTrivia(summary)); return node.WithLeadingTrivia(trivia); } return base.VisitConstructorDeclaration(node); }
public override SyntaxNode VisitConstructorDeclaration(ConstructorDeclarationSyntax node) { String name = node.Identifier.ValueText; String replaceName = ""; if (SharedContainer.Instance.nameMap.ContainsKey(name)) { replaceName = SharedContainer.Instance.nameMap[name]; } else { replaceName = SharedContainer.Instance.RandomString(SharedContainer.Instance.nameMap.Count() + 1); SharedContainer.Instance.nameMap[name] = replaceName; } ConstructorDeclarationSyntax newSyntax = node.WithIdentifier(Identifier(replaceName)).WithLeadingTrivia(node.GetLeadingTrivia()).WithTrailingTrivia(node.GetTrailingTrivia()); return(node.ReplaceNode(node, newSyntax)); }
public static SyntaxNode RemoveModifierFromNode(SyntaxNode node, SyntaxKind modifier) { //there seem to be no base classes to support WithModifiers. //dynamic modifiersNode = node; //return modifiersNode.WithModifiers(SyntaxFactory.TokenList(modifiersNode.Modifiers.Where(m => !m.IsKind(SyntaxKind.PrivateKeyword)))); MethodDeclarationSyntax methodNode = node as MethodDeclarationSyntax; if (methodNode != null) { return(methodNode.WithModifiers(SyntaxFactory.TokenList(methodNode.Modifiers.Where(m => !m.IsKind(modifier)))) .WithLeadingTrivia(methodNode.GetLeadingTrivia())); } FieldDeclarationSyntax fieldNode = node as FieldDeclarationSyntax; if (fieldNode != null) { return(fieldNode.WithModifiers(SyntaxFactory.TokenList(fieldNode.Modifiers.Where(m => !m.IsKind(modifier)))) .WithLeadingTrivia(fieldNode.GetLeadingTrivia())); } PropertyDeclarationSyntax propertyNode = node as PropertyDeclarationSyntax; if (propertyNode != null) { return(propertyNode.WithModifiers(SyntaxFactory.TokenList(propertyNode.Modifiers.Where(m => !m.IsKind(modifier)))) .WithLeadingTrivia(propertyNode.GetLeadingTrivia())); } IndexerDeclarationSyntax indexerNode = node as IndexerDeclarationSyntax; if (indexerNode != null) { return(indexerNode.WithModifiers(SyntaxFactory.TokenList(indexerNode.Modifiers.Where(m => !m.IsKind(modifier)))) .WithLeadingTrivia(indexerNode.GetLeadingTrivia())); } EventDeclarationSyntax eventNode = node as EventDeclarationSyntax; if (eventNode != null) { return(eventNode.WithModifiers(SyntaxFactory.TokenList(eventNode.Modifiers.Where(m => !m.IsKind(modifier)))) .WithLeadingTrivia(eventNode.GetLeadingTrivia())); } ConstructorDeclarationSyntax ctrNode = node as ConstructorDeclarationSyntax; if (ctrNode != null) { return(ctrNode.WithModifiers(SyntaxFactory.TokenList(ctrNode.Modifiers.Where(m => !m.IsKind(modifier)))) .WithLeadingTrivia(ctrNode.GetLeadingTrivia())); } OperatorDeclarationSyntax opNode = node as OperatorDeclarationSyntax; if (opNode != null) { return(opNode.WithModifiers(SyntaxFactory.TokenList(opNode.Modifiers.Where(m => !m.IsKind(modifier)))) .WithLeadingTrivia(opNode.GetLeadingTrivia())); } ClassDeclarationSyntax classNode = node as ClassDeclarationSyntax; if (classNode != null) { return(classNode.WithModifiers(SyntaxFactory.TokenList(classNode.Modifiers.Where(m => !m.IsKind(modifier)))) .WithLeadingTrivia(classNode.GetLeadingTrivia())); } InterfaceDeclarationSyntax interfaceNode = node as InterfaceDeclarationSyntax; if (interfaceNode != null) { return(interfaceNode.WithModifiers(SyntaxFactory.TokenList(interfaceNode.Modifiers.Where(m => !m.IsKind(modifier)))) .WithLeadingTrivia(interfaceNode.GetLeadingTrivia())); } StructDeclarationSyntax structNode = node as StructDeclarationSyntax; if (structNode != null) { return(structNode.WithModifiers(SyntaxFactory.TokenList(structNode.Modifiers.Where(m => !m.IsKind(modifier)))) .WithLeadingTrivia(structNode.GetLeadingTrivia())); } var enumNode = node as EnumDeclarationSyntax; if (enumNode != null) { return(enumNode.WithModifiers(SyntaxFactory.TokenList(enumNode.Modifiers.Where(m => !m.IsKind(modifier)))) .WithLeadingTrivia(enumNode.GetLeadingTrivia())); } var delegateNode = node as DelegateDeclarationSyntax; if (delegateNode != null) { return(delegateNode.WithModifiers(SyntaxFactory.TokenList(delegateNode.Modifiers.Where(m => !m.IsKind(modifier)))) .WithLeadingTrivia(delegateNode.GetLeadingTrivia())); } return(node); }
public override SyntaxNode VisitConstructorDeclaration(ConstructorDeclarationSyntax node) { return(base.VisitConstructorDeclaration(node).WithLeadingTrivia(node.GetLeadingTrivia())); }
public static ConstructorDeclarationSyntax ConvertToExpressionBodiedHelper(ConstructorDeclarationSyntax constructorDeclaration) { if (constructorDeclaration.Body == null) { return(constructorDeclaration); } if (constructorDeclaration.Body.Statements.Count != 1) { return(constructorDeclaration); } if (constructorDeclaration.Body.ContainsDirectives) { return(constructorDeclaration); } var singleStatement = constructorDeclaration.Body.Statements.First(); if (singleStatement is IfStatementSyntax) { return(constructorDeclaration); } if (singleStatement is ThrowStatementSyntax) { return(constructorDeclaration); } if (singleStatement is YieldStatementSyntax) { return(constructorDeclaration); } if (singleStatement is ExpressionStatementSyntax == false) { return(constructorDeclaration); } if (singleStatement.HasLeadingTrivia) { if (HasNoneWhitespaceTrivia(singleStatement.GetLeadingTrivia()) == false) { return(constructorDeclaration); } } if (singleStatement.HasTrailingTrivia) { if (HasNoneWhitespaceTrivia(singleStatement.GetTrailingTrivia()) == false) { return(constructorDeclaration); } } if (constructorDeclaration.Body.CloseBraceToken.HasLeadingTrivia) { if (HasNoneWhitespaceTrivia(constructorDeclaration.Body.CloseBraceToken.LeadingTrivia) == false) { return(constructorDeclaration); } } if (constructorDeclaration.Body.OpenBraceToken.HasLeadingTrivia) { if (HasNoneWhitespaceTrivia(constructorDeclaration.Body.OpenBraceToken.LeadingTrivia) == false) { return(constructorDeclaration); } } var expression = (singleStatement as ExpressionStatementSyntax).Expression .WithoutLeadingTrivia(); var length = expression.WithoutTrivia().Span.Length + constructorDeclaration.Span.Length - constructorDeclaration.Body.FullSpan.Length; if (length > MembersToExpressionBodied.Options.MAX_EXPRESSION_BODIED_MEMBER_LENGTH) { return(constructorDeclaration); } if (constructorDeclaration.Body.ChildNodes().OfType <UsingStatementSyntax>().Any()) { return(constructorDeclaration); } var newconstructorDeclaration = constructorDeclaration .WithIdentifier(constructorDeclaration.Identifier.WithTrailingTrivia(_spaceTrivia)) .WithBody(null) .WithTrailingTrivia(_spaceTrivia) .WithLeadingTrivia(constructorDeclaration.GetLeadingTrivia()) .WithExpressionBody( SyntaxFactory.ArrowExpressionClause(expression.WithLeadingTrivia(_spaceTrivia))) .WithSemicolonToken(GetSemicolon(constructorDeclaration.Body)) .WithAdditionalAnnotations(Formatter.Annotation); return(newconstructorDeclaration); }
internal static DocumentedElement LoadFromSyntaxNode(ConstructorDeclarationSyntax node) { SyntaxToken syntaxToken = node.ChildTokens().First(token => token.IsKind(SyntaxKind.IdentifierToken)); return(DocumentedElement.LoadFromSyntaxTokenAndTrivia(syntaxToken, node.GetLeadingTrivia())); }