public static ValueTuple <SyntaxToken, SyntaxToken> GetFirstAndLastMemberDeclarationTokensAfterAttributes(this MemberDeclarationSyntax node) { Contract.ThrowIfNull(node); // there are no attributes associated with the node. return back first and last token of the node. var attributes = node.GetAttributes(); if (attributes.Count == 0) { return(ValueTuple.Create(node.GetFirstToken(includeZeroWidth: true), node.GetLastToken(includeZeroWidth: true))); } var lastToken = node.GetLastToken(includeZeroWidth: true); var lastAttributeToken = attributes.Last().GetLastToken(includeZeroWidth: true); if (lastAttributeToken.Equals(lastToken)) { return(ValueTuple.Create(default(SyntaxToken), default(SyntaxToken))); } var firstTokenAfterAttribute = lastAttributeToken.GetNextToken(includeZeroWidth: true); // there are attributes, get first token after the tokens belong to attributes return(ValueTuple.Create(firstTokenAfterAttribute, lastToken)); }
internal static SyntaxToken FindIdentifier(MemberDeclarationSyntax member) { if (member.TryFirstAncestorOrSelf(out PropertyDeclarationSyntax property)) { return(property.Identifier); } if (member.TryFirstAncestorOrSelf(out FieldDeclarationSyntax field)) { if (field.Declaration.Variables.TrySingle(out var variable)) { return(variable.Identifier); } } return(member.GetFirstToken()); }
private static bool ContainsPosition(this MemberDeclarationSyntax currMember, int caretPosition) { var trivia = currMember?.GetFirstToken().LeadingTrivia; foreach (var t in trivia) { if (t.IsKind(SyntaxKind.SingleLineDocumentationCommentTrivia) || t.IsKind(SyntaxKind.MultiLineDocumentationCommentTrivia) || t.IsKind(SyntaxKind.SingleLineCommentTrivia) || t.IsKind(SyntaxKind.MultiLineCommentTrivia)) { break; } if (t.IsKind(SyntaxKind.EndOfLineTrivia) && t.Span.Start <= caretPosition && t.Span.End >= caretPosition) { return(false); } } return(true); }
internal static async Task <Document> RefactorAsync( Document document, MemberDeclarationSyntax declaration, AccessModifier accessModifier, CancellationToken cancellationToken) { SyntaxNode root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); SyntaxToken[] accessModifiers = CreateModifiers(accessModifier); List <SyntaxToken> modifiers = declaration.GetModifiers().ToList(); MemberDeclarationSyntax newDeclaration = declaration; if (modifiers.Count > 0) { accessModifiers[0] = accessModifiers[0].WithLeadingTrivia(modifiers[0].LeadingTrivia); modifiers[0] = modifiers[0].WithoutLeadingTrivia(); modifiers.InsertRange(0, accessModifiers); } else { SyntaxToken token = declaration.GetFirstToken(); accessModifiers[0] = accessModifiers[0].WithLeadingTrivia(token.LeadingTrivia); modifiers = accessModifiers.ToList(); newDeclaration = declaration.ReplaceToken( token, token.WithoutLeadingTrivia()); } newDeclaration = newDeclaration.SetModifiers(TokenList(modifiers)); SyntaxNode newRoot = root.ReplaceNode(declaration, newDeclaration); return(document.WithSyntaxRoot(newRoot)); }