public static SyntaxList <TDeclaration> Insert <TDeclaration>( SyntaxList <TDeclaration> declarationList, TDeclaration declaration, CodeGenerationOptions options, IList <bool> availableIndices, Func <SyntaxList <TDeclaration>, TDeclaration> after = null, Func <SyntaxList <TDeclaration>, TDeclaration> before = null) where TDeclaration : SyntaxNode { var index = GetInsertionIndex( declarationList, declaration, options, availableIndices, CSharpDeclarationComparer.Instance, after, before); if (availableIndices != null) { availableIndices.Insert(index, true); } if (index != 0 && declarationList[index - 1].ContainsDiagnostics && AreBracesMissing(declarationList[index - 1])) { return(declarationList.Insert(index, declaration.WithLeadingTrivia(SyntaxFactory.ElasticCarriageReturnLineFeed))); } return(declarationList.Insert(index, declaration)); }
public static Task <Document> RefactorAsync( Document document, LocalFunctionStatementSyntax localFunction, CancellationToken cancellationToken = default(CancellationToken)) { if (document == null) { throw new ArgumentNullException(nameof(document)); } if (localFunction == null) { throw new ArgumentNullException(nameof(localFunction)); } StatementsInfo statementsInfos = SyntaxInfo.StatementsInfo(localFunction); SyntaxList <StatementSyntax> statements = statementsInfos.Statements; int index = statements.IndexOf(localFunction); if (index == 0 && statementsInfos.Block.OpenBraceToken.GetFullSpanEndLine() == localFunction.GetFullSpanStartLine()) { localFunction = localFunction.WithLeadingTrivia(localFunction.GetLeadingTrivia().Insert(0, NewLine())); } SyntaxList <StatementSyntax> newStatements = statements.Insert(index + 1, localFunction.WithNavigationAnnotation()); return(document.ReplaceStatementsAsync(statementsInfos, newStatements, cancellationToken)); }
public static XmlElementSyntax MultiLineElement(XmlNameSyntax name, string newLineText, SyntaxList <XmlNodeSyntax> content) { return(SyntaxFactory.XmlElement( SyntaxFactory.XmlElementStartTag(name), content.Insert(0, NewLine(newLineText)).Add(NewLine(newLineText)), SyntaxFactory.XmlElementEndTag(name))); }
public static XmlElementSyntax MultiLineElement(XmlNameSyntax name, string newLineText, SyntaxList <XmlNodeSyntax> content) { var newContent = content.Insert(0, NewLine(newLineText)).Add(NewLine(newLineText)); for (var i = 1; i < newContent.Count; i++) { if (newContent[i] is XmlTextSyntax xmlTextSyntax && xmlTextSyntax.TextTokens[0].ValueText == newLineText) { var previousTrailingTrivia = newContent[i - 1].GetTrailingTrivia(); if (previousTrailingTrivia.Count > 0) { var lastTrivia = previousTrailingTrivia.Last(); var updatedLastTriviaText = lastTrivia.ToString().TrimEnd(' ', '\t'); var updatedTrailingTrivia = previousTrailingTrivia.Replace(lastTrivia, SyntaxFactory.SyntaxTrivia(lastTrivia.Kind(), updatedLastTriviaText)); newContent = newContent.Replace(newContent[i - 1], newContent[i - 1].WithTrailingTrivia(updatedTrailingTrivia)); } } } return(SyntaxFactory.XmlElement( SyntaxFactory.XmlElementStartTag(name), newContent, SyntaxFactory.XmlElementEndTag(name))); }
private static SyntaxNode InsertStatement( SyntaxNode node, StatementSyntax statement) { var body = (BlockSyntax)GetBodyOrExpressionBody(node); SyntaxList <StatementSyntax> statements = body.Statements; StatementSyntax lastStatement = statements.LastOrDefault(f => !f.IsKind(SyntaxKind.LocalFunctionStatement, SyntaxKind.ReturnStatement)); int index = (lastStatement != null) ? statements.IndexOf(lastStatement) + 1 : 0; BlockSyntax newBody = body.WithStatements(statements.Insert(index, statement)); if (node.IsKind(SyntaxKind.MethodDeclaration)) { return(((MethodDeclarationSyntax)node).WithBody(newBody)); } else { return(((LocalFunctionStatementSyntax)node).WithBody(newBody)); } }
private static SyntaxList <StatementSyntax> InsertWithinTriviaOfNext( SyntaxList <StatementSyntax> oldStatements, StatementSyntax newStatement, int statementIndex) { var nextStatement = oldStatements.ElementAtOrDefault(statementIndex); if (nextStatement == null) { return(oldStatements.Insert(statementIndex, newStatement)); } // Grab all the trivia before the line the next statement is on and move it to the new node. var nextStatementLeading = nextStatement.GetLeadingTrivia(); var precedingEndOfLine = nextStatementLeading.LastOrDefault(t => t.Kind() == SyntaxKind.EndOfLineTrivia); if (precedingEndOfLine == default) { return(oldStatements.ReplaceRange( nextStatement, new[] { newStatement, nextStatement })); } var endOfLineIndex = nextStatementLeading.IndexOf(precedingEndOfLine) + 1; return(oldStatements.ReplaceRange( nextStatement, new[] { newStatement.WithLeadingTrivia(nextStatementLeading.Take(endOfLineIndex)), nextStatement.WithLeadingTrivia(nextStatementLeading.Skip(endOfLineIndex)), })); }
public static Task <Document> RefactorAsync( Document document, LocalFunctionStatementSyntax localFunction, bool copyAfter = true, CancellationToken cancellationToken = default) { StatementListInfo statementsInfos = SyntaxInfo.StatementListInfo(localFunction); SyntaxList <StatementSyntax> statements = statementsInfos.Statements; int index = statements.IndexOf(localFunction); if (index == 0) { if (copyAfter) { if (statementsInfos.ParentAsBlock.OpenBraceToken.GetFullSpanEndLine() == localFunction.GetFullSpanStartLine()) { localFunction = localFunction.WithLeadingTrivia(localFunction.GetLeadingTrivia().Insert(0, NewLine())); } } else { localFunction = localFunction.WithTrailingTrivia(localFunction.GetTrailingTrivia().Add(NewLine())); } } int insertIndex = (copyAfter) ? index + 1 : index; SyntaxList <StatementSyntax> newStatements = statements.Insert(insertIndex, localFunction.WithNavigationAnnotation()); return(document.ReplaceStatementsAsync(statementsInfos, newStatements, cancellationToken)); }
private void DoTestAddInsertRemoveReplaceOnEmptyList(SyntaxList <SyntaxNode> list) { Assert.Equal(0, list.Count); SyntaxNode nodeD = SyntaxFactory.ParseExpression("D "); SyntaxNode nodeE = SyntaxFactory.ParseExpression("E "); var newList = list.Add(nodeD); Assert.Equal(1, newList.Count); Assert.Equal("D ", newList.ToFullString()); newList = list.AddRange(new[] { nodeD, nodeE }); Assert.Equal(2, newList.Count); Assert.Equal("D E ", newList.ToFullString()); newList = list.Insert(0, nodeD); Assert.Equal(1, newList.Count); Assert.Equal("D ", newList.ToFullString()); newList = list.InsertRange(0, new[] { nodeD, nodeE }); Assert.Equal(2, newList.Count); Assert.Equal("D E ", newList.ToFullString()); newList = list.Remove(nodeD); Assert.Equal(0, newList.Count); Assert.Equal(-1, list.IndexOf(nodeD)); Assert.Throws <ArgumentOutOfRangeException>(() => list.RemoveAt(0)); Assert.Throws <ArgumentOutOfRangeException>(() => list.Insert(1, nodeD)); Assert.Throws <ArgumentOutOfRangeException>(() => list.Insert(-1, nodeD)); Assert.Throws <ArgumentOutOfRangeException>(() => list.InsertRange(1, new[] { nodeD })); Assert.Throws <ArgumentOutOfRangeException>(() => list.InsertRange(-1, new[] { nodeD })); Assert.Throws <ArgumentException>(() => list.Replace(nodeD, nodeE)); Assert.Throws <ArgumentException>(() => list.ReplaceRange(nodeD, new[] { nodeE })); Assert.Throws <ArgumentNullException>(() => list.Add(null)); Assert.Throws <ArgumentNullException>( () => list.AddRange((IEnumerable <SyntaxNode>)null) ); Assert.Throws <ArgumentNullException>(() => list.Insert(0, null)); Assert.Throws <ArgumentNullException>( () => list.InsertRange(0, (IEnumerable <SyntaxNode>)null) ); }
private static SyntaxList<StatementSyntax> InsertWithinTriviaOfNext( SyntaxList<StatementSyntax> oldStatements, StatementSyntax newStatement, int statementIndex) { var nextStatement = oldStatements.ElementAtOrDefault(statementIndex); return nextStatement == null ? oldStatements.Insert(statementIndex, newStatement) : oldStatements.ReplaceRange(nextStatement, new[] { newStatement.WithLeadingTrivia(nextStatement.GetLeadingTrivia()), nextStatement.WithoutLeadingTrivia() }); }
private static SyntaxList <StatementSyntax> InsertReturnStatement(SyntaxList <StatementSyntax> newStatements, ReturnStatementSyntax returnStatement) { int insertIndex = newStatements.Count; while (insertIndex > 0 && newStatements[insertIndex - 1].IsKind(SyntaxKind.LocalFunctionStatement)) { insertIndex--; } return(newStatements.Insert(insertIndex, returnStatement)); }
protected static SyntaxList <XmlNodeSyntax> CommentStartingWith(SyntaxList <XmlNodeSyntax> content, string phrase) { // when necessary adjust beginning text // Note: when on new line, then the text is not the 1st one but the 2nd one var index = GetIndex(content); if (index < 0) { return(content.Add(SyntaxFactory.XmlText(phrase))); } if (content[index] is XmlTextSyntax text) { // we have to remove the element as otherwise we duplicate the comment content = content.Remove(content[index]); if (phrase.IsNullOrWhiteSpace()) { var textTokens = text.TextTokens.Count; if (textTokens > 2) { // TODO: RKN find a better solution this as it is not good code // remove last "\r\n" token and remove ' /// ' trivia of last token if (text.TextTokens[textTokens - 2].IsKind(SyntaxKind.XmlTextLiteralNewLineToken) && text.TextTokens[textTokens - 1].ValueText.IsNullOrWhiteSpace()) { var newTokens = text.TextTokens.Take(textTokens - 2).ToArray(); text = SyntaxFactory.XmlText(newTokens); } } } var newText = text.WithStartText(phrase); return(content.Insert(index, newText)); } return(content.Insert(index, SyntaxFactory.XmlText(phrase))); }
protected static SyntaxList <UsingDirectiveSyntax> AddUsingDirectiveIfMissing(SyntaxList <UsingDirectiveSyntax> usings, NameSyntax namespaceName) { string namespaceToImport = namespaceName.ToString(); int? insertionIndex = null; // If the `using` directive is missing, then when we add it, we'll // attempt to keep the existing statements in alphabetical order. for (int i = 0; i < usings.Count; i++) { // Type aliases are usually put last, so if we haven't found an // insertion index yet, then we can insert it before this statement. if (usings[i].Alias is not null) { if (!insertionIndex.HasValue) { insertionIndex = i; } } else { string name = usings[i].Name.ToString(); // If the namespace is already imported, then we can return // the original list of `using` directives without modifying them. if (string.Equals(name, namespaceToImport, System.StringComparison.Ordinal)) { return(usings); } // If we don't have an insertion index, and this `using` directive is // greater than the one we want to insert, then this is the first // directive that should appear after the one we insert. if (!insertionIndex.HasValue && string.Compare(name, namespaceToImport) > 0) { insertionIndex = i; } } } UsingDirectiveSyntax directive = SyntaxFactory.UsingDirective(namespaceName); // If we found where to insert the new directive, then insert // it at that index; otherwise, it must be greater than all // existing directives, so add it to the end of the list. if (insertionIndex.HasValue) { return(usings.Insert(insertionIndex.Value, directive)); } else { return(usings.Add(directive)); } }
private SyntaxList <StatementSyntax> InsertRequiredDeclarations( SyntaxList <StatementSyntax> convertedStatements, CSharpSyntaxNode originaNode) { var descendantNodes = originaNode.DescendantNodes().ToList(); var declarationExpressions = descendantNodes.OfType <DeclarationExpressionSyntax>().ToList(); var isPatternExpressions = descendantNodes.OfType <IsPatternExpressionSyntax>().ToList(); if (declarationExpressions.Any() || isPatternExpressions.Any()) { convertedStatements = convertedStatements.Insert(0, ConvertToDeclarationStatement(declarationExpressions, isPatternExpressions)); } return(convertedStatements); }
private static SyntaxList <MemberDeclarationSyntax> WithMoved(SyntaxList <MemberDeclarationSyntax> members, MemberDeclarationSyntax member) { members = members.Remove(member); for (var i = 0; i < members.Count; i++) { var current = members[i]; if (MemberDeclarationComparer.Compare(member, current) < 0) { return(RemoveLeadingEndOfLine(members.Insert(i, UpdateLineFeed(member)))); } } return(RemoveLeadingEndOfLine(members.Add(UpdateLineFeed(member)))); }
private static SyntaxList <StatementSyntax> InsertLocalDeclarationStatement( SyntaxList <StatementSyntax> statements, LocalDeclarationStatementSyntax localDeclarationStatement) { int insertIndex = 0; while (insertIndex < statements.Count && IsParameterCheck(statements[insertIndex])) { insertIndex++; } return(statements.Insert(insertIndex, localDeclarationStatement)); }
public SyntaxList <StatementSyntax> InsertGeneratedClassMemberDeclarations( SyntaxList <StatementSyntax> convertedStatements, CSharpSyntaxNode originaNode) { var descendantNodes = originaNode.DescendantNodes().ToList(); var propertyBlocks = descendantNodes.OfType <PropertyDeclarationSyntax>() .Where(e => e.AccessorList != null && e.AccessorList.Accessors.Any(a => a.Body == null && a.ExpressionBody == null && a.Modifiers.ContainsDeclaredVisibility())) .ToList(); if (propertyBlocks.Any()) { convertedStatements = convertedStatements.Insert(0, ConvertToDeclarationStatement(propertyBlocks)); } return(convertedStatements); }
private SyntaxList <StatementSyntax> InsertRequiredDeclarations( SyntaxList <StatementSyntax> convertedStatements, CSharpSyntaxNode originaNode) { var descendantNodes = originaNode.DescendantNodes().ToList(); var declarationExpressions = descendantNodes.OfType <DeclarationExpressionSyntax>() .Where(e => !e.Parent.IsKind(CSSyntaxKind.ForEachVariableStatement)) //Handled inline for tuple loop .ToList(); var isPatternExpressions = descendantNodes.OfType <IsPatternExpressionSyntax>().ToList(); if (declarationExpressions.Any() || isPatternExpressions.Any()) { convertedStatements = convertedStatements.Insert(0, ConvertToDeclarationStatement(declarationExpressions, isPatternExpressions)); } return(convertedStatements); }
public override SyntaxNode VisitMethodDeclaration(MethodDeclarationSyntax node) { SyntaxList <StatementSyntax> blockWithNewStatements = node.Body.Statements; for (int i = 0; i < RandomUtils.GenerateLittleInt(); i++) { blockWithNewStatements = blockWithNewStatements.Insert(0, StatementGenerator.GenerateSingleStatement()); } BlockSyntax newBlock = SyntaxFactory.Block(blockWithNewStatements); MethodDeclarationSyntax newMethod2 = node.WithBody(newBlock); var newNode = node.ReplaceNode(node, newMethod2); return(base.VisitMethodDeclaration(newNode)); }
protected static SyntaxList <TDeclaration> Insert <TDeclaration>( SyntaxList <TDeclaration> declarationList, TDeclaration declaration, CodeGenerationOptions options, IList <bool> availableIndices, Func <SyntaxList <TDeclaration>, TDeclaration> after = null, Func <SyntaxList <TDeclaration>, TDeclaration> before = null) where TDeclaration : SyntaxNode { var index = GetInsertionIndex(declarationList, declaration, options, availableIndices, after, before); if (availableIndices != null) { availableIndices.Insert(index, true); } return(declarationList.Insert(index, declaration)); }
public async Task <Document> RefactorAsync( Document document, SelectedStatementsInfo info, CancellationToken cancellationToken = default(CancellationToken)) { SyntaxNode root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); StatementContainer container = info.Container; StatementSyntax[] statements = info.SelectedNodes().ToArray(); int index = info.FirstSelectedNodeIndex; SyntaxTriviaList leadingTrivia = statements[0].GetLeadingTrivia(); SyntaxTriviaList trailingTrivia = statements[statements.Length - 1].GetTrailingTrivia(); statements[0] = statements[0].WithLeadingTrivia(); statements[statements.Length - 1] = statements[statements.Length - 1].WithTrailingTrivia(); SyntaxList <StatementSyntax> newStatements = container.Statements; int cnt = statements.Length; while (cnt > 0) { newStatements = newStatements.RemoveAt(index); cnt--; } TStatement statement = CreateStatement(statements.ToImmutableArray()); statement = statement .WithLeadingTrivia(leadingTrivia) .WithTrailingTrivia(trailingTrivia) .WithFormatterAnnotation(); newStatements = newStatements.Insert(index, statement); root = root.ReplaceNode(container.Node, container.NodeWithStatements(newStatements)); return(document.WithSyntaxRoot(root)); }
private static SyntaxList <StatementSyntax> RewriteStatements(SyntaxList <StatementSyntax> statements) { for (int i = statements.Count - 1; i >= 0; i--) { StatementSyntax statement = statements[i]; if (statement.HasAnnotation(_asyncAwaitAnnotation[0])) { statements = statements.Replace( statement, statement.WithoutAnnotations(_asyncAwaitAnnotation).WithTrailingTrivia(NewLine())); statements = statements.Insert( i + 1, ReturnStatement().WithTrailingTrivia(statement.GetTrailingTrivia()).WithFormatterAnnotation()); } } return(statements); }
private static Task <Document> CopySwitchSectionAsync( Document document, SwitchSectionSyntax switchSection, bool insertNewLine, CancellationToken cancellationToken) { var switchStatement = (SwitchStatementSyntax)switchSection.Parent; SyntaxList <SwitchSectionSyntax> sections = switchStatement.Sections; int index = sections.IndexOf(switchSection); SwitchLabelSyntax label = switchSection.Labels[0]; SyntaxToken firstToken = label.GetFirstToken(); SyntaxToken newFirstToken = firstToken.WithNavigationAnnotation(); if (insertNewLine && !firstToken.LeadingTrivia.Contains(SyntaxKind.EndOfLineTrivia)) { newFirstToken = newFirstToken.PrependToLeadingTrivia(CSharpFactory.NewLine()); } SwitchSectionSyntax newSection = switchSection .WithLabels(switchSection.Labels.ReplaceAt(0, label.ReplaceToken(firstToken, newFirstToken))) .WithFormatterAnnotation(); if (index == sections.Count - 1) { newSection = newSection.TrimTrailingTrivia(); } SyntaxList <SwitchSectionSyntax> newSections = sections.Insert(index + 1, newSection); SwitchStatementSyntax newSwitchStatement = switchStatement.WithSections(newSections); return(document.ReplaceNodeAsync(switchStatement, newSwitchStatement, cancellationToken)); }
public Task <Document> RefactorAsync( Document document, StatementsSelection selectedStatements, CancellationToken cancellationToken = default(CancellationToken)) { StatementsInfo statementsInfo = selectedStatements.Info; StatementSyntax[] statements = selectedStatements.ToArray(); int index = selectedStatements.StartIndex; SyntaxTriviaList leadingTrivia = statements[0].GetLeadingTrivia(); SyntaxTriviaList trailingTrivia = statements[statements.Length - 1].GetTrailingTrivia(); statements[0] = statements[0].WithLeadingTrivia(); statements[statements.Length - 1] = statements[statements.Length - 1].WithTrailingTrivia(); SyntaxList <StatementSyntax> newStatements = statementsInfo.Statements; int cnt = statements.Length; while (cnt > 0) { newStatements = newStatements.RemoveAt(index); cnt--; } TStatement statement = CreateStatement(statements.ToImmutableArray()); statement = statement .WithLeadingTrivia(leadingTrivia) .WithTrailingTrivia(trailingTrivia) .WithFormatterAnnotation(); newStatements = newStatements.Insert(index, statement); return(document.ReplaceStatementsAsync(statementsInfo, newStatements, cancellationToken)); }
public Task <Document> RefactorAsync( Document document, SelectedStatementCollection selectedStatements, CancellationToken cancellationToken = default(CancellationToken)) { IStatementContainer container = selectedStatements.Container; StatementSyntax[] statements = selectedStatements.ToArray(); int index = selectedStatements.FirstIndex; SyntaxTriviaList leadingTrivia = statements[0].GetLeadingTrivia(); SyntaxTriviaList trailingTrivia = statements[statements.Length - 1].GetTrailingTrivia(); statements[0] = statements[0].WithLeadingTrivia(); statements[statements.Length - 1] = statements[statements.Length - 1].WithTrailingTrivia(); SyntaxList <StatementSyntax> newStatements = container.Statements; int cnt = statements.Length; while (cnt > 0) { newStatements = newStatements.RemoveAt(index); cnt--; } TStatement statement = CreateStatement(statements.ToImmutableArray()); statement = statement .WithLeadingTrivia(leadingTrivia) .WithTrailingTrivia(trailingTrivia) .WithFormatterAnnotation(); newStatements = newStatements.Insert(index, statement); return(document.ReplaceNodeAsync(container.Node, container.NodeWithStatements(newStatements), cancellationToken)); }
private static async Task <Document> CreateChangedDocumentAsync( Document document, MemberDeclarationSyntax declaration, List <MemberDeclarationSyntax> declarations, CancellationToken cancellationToken) { SyntaxNode oldRoot = await document.GetSyntaxRootAsync(cancellationToken); MemberDeclarationSyntax parentDeclaration = GetContainingDeclaration(declaration); SyntaxList <MemberDeclarationSyntax> members = GetMembers(parentDeclaration); SyntaxList <MemberDeclarationSyntax> newMembers = members.Insert( IndexOfLastConstructorOrField(members) + 1, CreateConstructor(GetConstructorIdentifierText(parentDeclaration), declarations)); MemberDeclarationSyntax newNode = SetMembers(parentDeclaration, newMembers) .WithAdditionalAnnotations(Formatter.Annotation); SyntaxNode newRoot = oldRoot.ReplaceNode(parentDeclaration, newNode); return(document.WithSyntaxRoot(newRoot)); }
private static async Task <Document> RefactorAsync( Document document, MemberDeclarationSyntax declaration, List <MemberDeclarationSyntax> assignableMembers, CancellationToken cancellationToken = default(CancellationToken)) { SyntaxNode oldRoot = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); MemberDeclarationSyntax parentMember = GetContainingMember(declaration); SyntaxList <MemberDeclarationSyntax> members = parentMember.GetMembers(); SyntaxList <MemberDeclarationSyntax> newMembers = members.Insert( IndexOfLastConstructorOrField(members) + 1, CreateConstructor(GetConstructorIdentifierText(parentMember), assignableMembers)); MemberDeclarationSyntax newNode = parentMember.SetMembers(newMembers) .WithFormatterAnnotation(); SyntaxNode newRoot = oldRoot.ReplaceNode(parentMember, newNode); return(document.WithSyntaxRoot(newRoot)); }
private static SyntaxNode Refactor(MemberDeclarationSyntax member) { switch (member.Parent.Kind()) { case SyntaxKind.CompilationUnit: { var parent = (CompilationUnitSyntax)member.Parent; SyntaxList <MemberDeclarationSyntax> members = parent.Members; int index = members.IndexOf(member); return(parent.WithMembers(members.Insert(index + 1, member))); } case SyntaxKind.NamespaceDeclaration: { var parent = (NamespaceDeclarationSyntax)member.Parent; SyntaxList <MemberDeclarationSyntax> members = parent.Members; int index = members.IndexOf(member); if (index == 0 && parent.OpenBraceToken.GetFullSpanEndLine() == member.GetFullSpanStartLine()) { member = member.WithLeadingTrivia(member.GetLeadingTrivia().Insert(0, NewLineTrivia())); } return(parent.WithMembers(members.Insert(index + 1, member))); } case SyntaxKind.ClassDeclaration: { var parent = (ClassDeclarationSyntax)member.Parent; SyntaxList <MemberDeclarationSyntax> members = parent.Members; int index = members.IndexOf(member); if (index == 0 && parent.OpenBraceToken.GetFullSpanEndLine() == member.GetFullSpanStartLine()) { member = member.WithLeadingTrivia(member.GetLeadingTrivia().Insert(0, NewLineTrivia())); } return(parent.WithMembers(members.Insert(index + 1, member))); } case SyntaxKind.StructDeclaration: { var parent = (StructDeclarationSyntax)member.Parent; SyntaxList <MemberDeclarationSyntax> members = parent.Members; int index = members.IndexOf(member); if (index == 0 && parent.OpenBraceToken.GetFullSpanEndLine() == member.GetFullSpanStartLine()) { member = member.WithLeadingTrivia(member.GetLeadingTrivia().Insert(0, NewLineTrivia())); } return(parent.WithMembers(members.Insert(index + 1, member))); } case SyntaxKind.InterfaceDeclaration: { var parent = (InterfaceDeclarationSyntax)member.Parent; SyntaxList <MemberDeclarationSyntax> members = parent.Members; int index = members.IndexOf(member); if (index == 0 && parent.OpenBraceToken.GetFullSpanEndLine() == member.GetFullSpanStartLine()) { member = member.WithLeadingTrivia(member.GetLeadingTrivia().Insert(0, NewLineTrivia())); } return(parent.WithMembers(members.Insert(index + 1, member))); } } return(null); }
public static SyntaxList <MemberDeclarationSyntax> InsertMember(SyntaxList <MemberDeclarationSyntax> members, MemberDeclarationSyntax member) { return(members.Insert(GetMemberInsertIndex(members, member), member)); }
Document PerformAction(Document document, SemanticModel model, SyntaxNode root, PropertyBlockSyntax propertyDeclaration, bool needsSetter) { AccessorBlockSyntax accessor = null; PropertyBlockSyntax newProp = null; if (needsSetter) { accessor = SyntaxFactory.AccessorBlock( SyntaxKind.SetAccessorBlock, SyntaxFactory.AccessorStatement(SyntaxKind.SetAccessorStatement, SyntaxFactory.Token(SyntaxKind.SetKeyword)) .WithParameterList(SyntaxFactory.ParameterList(SyntaxFactory.SeparatedList(new[] { SyntaxFactory.Parameter(SyntaxFactory.List<AttributeListSyntax>(), SyntaxFactory.TokenList(SyntaxFactory.Token(SyntaxKind.ByValKeyword)), SyntaxFactory.ModifiedIdentifier("value"), SyntaxFactory.SimpleAsClause(propertyDeclaration.PropertyStatement.AsClause.Type().WithoutTrailingTrivia()), null) }))), SyntaxFactory.EndBlockStatement(SyntaxKind.EndSetStatement, SyntaxFactory.Token(SyntaxKind.SetKeyword))); var getter = propertyDeclaration.Accessors.FirstOrDefault(m => m.IsKind(SyntaxKind.GetAccessorBlock)); if (getter != null) { var getField = getter.ScanGetter(model); if (getField == null || getField.IsReadOnly) { // Readonly or no field can be found accessor = accessor.WithStatements(SyntaxFactory.List<StatementSyntax>(new[] { GetNotImplementedThrowStatement() })); } else { // Now we add a 'field = value'. accessor = accessor.WithStatements(SyntaxFactory.List<StatementSyntax>(new[] { SyntaxFactory.AssignmentStatement(SyntaxKind.SimpleAssignmentStatement, SyntaxFactory.IdentifierName(getField.Name), SyntaxFactory.Token(SyntaxKind.EqualsToken), SyntaxFactory.IdentifierName("value")) })); } } var modifierList = SyntaxFactory.TokenList(propertyDeclaration.PropertyStatement.Modifiers.Where(m => !m.IsKind(SyntaxKind.ReadOnlyKeyword))); newProp = propertyDeclaration .WithAccessors(propertyDeclaration.Accessors.Add(accessor)) .WithPropertyStatement(propertyDeclaration.PropertyStatement.WithModifiers(modifierList)); } else { accessor = SyntaxFactory.AccessorBlock(SyntaxKind.GetAccessorBlock, SyntaxFactory.AccessorStatement(SyntaxKind.GetAccessorStatement, SyntaxFactory.Token(SyntaxKind.GetKeyword)), SyntaxFactory.EndBlockStatement(SyntaxKind.EndGetStatement, SyntaxFactory.Token(SyntaxKind.GetKeyword))); var setter = propertyDeclaration.Accessors.FirstOrDefault(m => m.IsKind(SyntaxKind.SetAccessorBlock)); var accessorDeclList = new SyntaxList<AccessorBlockSyntax>(); if (setter != null) { var setField = setter.ScanSetter(model); if (setField == null) { // No field can be found accessor = accessor.WithStatements(SyntaxFactory.List<StatementSyntax>(new[] { GetNotImplementedThrowStatement() })); } else { // Add a 'Return field'. accessor = accessor.WithStatements(SyntaxFactory.List<StatementSyntax>( new[] { SyntaxFactory.ReturnStatement(SyntaxFactory.IdentifierName(setField.Name)) })); } accessorDeclList = accessorDeclList.Add(propertyDeclaration.Accessors.First(m => m.IsKind(SyntaxKind.SetAccessorBlock))); } accessorDeclList = accessorDeclList.Insert(0, accessor); var accessorList = SyntaxFactory.List(accessorDeclList); var modifierList = SyntaxFactory.TokenList(propertyDeclaration.PropertyStatement.Modifiers.Where(m => !m.IsKind(SyntaxKind.WriteOnlyKeyword))); newProp = propertyDeclaration .WithAccessors(accessorList) .WithPropertyStatement(propertyDeclaration.PropertyStatement.WithModifiers(modifierList)); } var newRoot = root.ReplaceNode(propertyDeclaration, newProp).WithAdditionalAnnotations(Formatter.Annotation); return document.WithSyntaxRoot(newRoot); }
public static SyntaxList <XmlNodeSyntax> WithoutFirstAndLastNewlines(this SyntaxList <XmlNodeSyntax> summaryContent) { if (summaryContent.Count == 0) { return(summaryContent); } XmlTextSyntax firstSyntax = summaryContent[0] as XmlTextSyntax; if (firstSyntax == null) { return(summaryContent); } XmlTextSyntax lastSyntax = summaryContent[summaryContent.Count - 1] as XmlTextSyntax; if (lastSyntax == null) { return(summaryContent); } SyntaxTokenList firstSyntaxTokens = firstSyntax.TextTokens; int removeFromStart; if (IsXmlNewLine(firstSyntaxTokens[0])) { removeFromStart = 1; } else { if (!IsXmlWhitespace(firstSyntaxTokens[0])) { return(summaryContent); } if (!IsXmlNewLine(firstSyntaxTokens[1])) { return(summaryContent); } removeFromStart = 2; } SyntaxTokenList lastSyntaxTokens = lastSyntax.TextTokens; int removeFromEnd; if (IsXmlNewLine(lastSyntaxTokens[lastSyntaxTokens.Count - 1])) { removeFromEnd = 1; } else { if (!IsXmlWhitespace(lastSyntaxTokens[lastSyntaxTokens.Count - 1])) { return(summaryContent); } if (!IsXmlNewLine(lastSyntaxTokens[lastSyntaxTokens.Count - 2])) { return(summaryContent); } removeFromEnd = 2; } for (int i = 0; i < removeFromStart; i++) { firstSyntaxTokens = firstSyntaxTokens.RemoveAt(0); } if (firstSyntax == lastSyntax) { lastSyntaxTokens = firstSyntaxTokens; } for (int i = 0; i < removeFromEnd; i++) { if (!lastSyntaxTokens.Any()) { break; } lastSyntaxTokens = lastSyntaxTokens.RemoveAt(lastSyntaxTokens.Count - 1); } summaryContent = summaryContent.RemoveAt(summaryContent.Count - 1); if (lastSyntaxTokens.Count != 0) { summaryContent = summaryContent.Add(lastSyntax.WithTextTokens(lastSyntaxTokens)); } if (firstSyntax != lastSyntax) { summaryContent = summaryContent.RemoveAt(0); if (firstSyntaxTokens.Count != 0) { summaryContent = summaryContent.Insert(0, firstSyntax.WithTextTokens(firstSyntaxTokens)); } } if (summaryContent.Count > 0) { // Make sure to remove the leading trivia summaryContent = summaryContent.Replace(summaryContent[0], summaryContent[0].WithLeadingTrivia()); // Remove leading spaces (between the <para> start tag and the start of the paragraph content) XmlTextSyntax firstTextSyntax = summaryContent[0] as XmlTextSyntax; if (firstTextSyntax != null && firstTextSyntax.TextTokens.Count > 0) { SyntaxToken firstTextToken = firstTextSyntax.TextTokens[0]; string firstTokenText = firstTextToken.Text; string trimmed = firstTokenText.TrimStart(); if (trimmed != firstTokenText) { SyntaxToken newFirstToken = SyntaxFactory.Token( firstTextToken.LeadingTrivia, firstTextToken.Kind(), trimmed, firstTextToken.ValueText.TrimStart(), firstTextToken.TrailingTrivia); summaryContent = summaryContent.Replace(firstTextSyntax, firstTextSyntax.ReplaceToken(firstTextToken, newFirstToken)); } } } return(summaryContent); }
Document PerformAction(Document document, SemanticModel model, SyntaxNode root, PropertyDeclarationSyntax propertyDeclaration, bool needsSetter) { AccessorDeclarationSyntax accessor = null; PropertyDeclarationSyntax newProp = null; if (needsSetter) { accessor = SyntaxFactory.AccessorDeclaration(SyntaxKind.SetAccessorDeclaration); var getter = propertyDeclaration.AccessorList.Accessors.FirstOrDefault(m => m.IsKind(SyntaxKind.GetAccessorDeclaration)); if (getter == null) { //get; accessor = accessor.WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.SemicolonToken)); } else { var getField = ReplacePropertyWithBackingFieldWithAutoPropertyCodeRefactoringProvider.ScanGetter(model, getter); if (getField == null && getter.Body == null) { //get; accessor = accessor.WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.SemicolonToken)).WithTrailingTrivia(getter.GetTrailingTrivia()); } else if (getField == null || getField.IsReadOnly) { //readonly or no field can be found accessor = accessor.WithBody(GetNotImplementedBlock()); } else { //now we add a 'field = value'. accessor = accessor.WithBody(SyntaxFactory.Block( SyntaxFactory.ExpressionStatement( SyntaxFactory.AssignmentExpression(SyntaxKind.SimpleAssignmentExpression, SyntaxFactory.IdentifierName(getField.Name), SyntaxFactory.IdentifierName("value"))))); } } newProp = propertyDeclaration.WithAccessorList(propertyDeclaration.AccessorList.AddAccessors(accessor)); } else { accessor = SyntaxFactory.AccessorDeclaration(SyntaxKind.GetAccessorDeclaration); var setter = propertyDeclaration.AccessorList.Accessors.FirstOrDefault(m => m.IsKind(SyntaxKind.SetAccessorDeclaration)); var accessorDeclList = new SyntaxList <AccessorDeclarationSyntax>(); if (setter == null) { //set; accessor = accessor.WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.SemicolonToken)); } else { var setField = ReplacePropertyWithBackingFieldWithAutoPropertyCodeRefactoringProvider.ScanSetter(model, setter); if (setField == null && setter.Body == null) { //set; accessor = accessor.WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.SemicolonToken)).WithTrailingTrivia(setter.GetTrailingTrivia()); } else if (setField == null) { //no field can be found accessor = accessor.WithBody(GetNotImplementedBlock()); } else { //now we add a 'return field;'. accessor = accessor.WithBody(SyntaxFactory.Block( SyntaxFactory.ReturnStatement(SyntaxFactory.IdentifierName(setField.Name)))); } accessorDeclList = accessorDeclList.Add(propertyDeclaration.AccessorList.Accessors.First(m => m.IsKind(SyntaxKind.SetAccessorDeclaration))); } accessorDeclList = accessorDeclList.Insert(0, accessor); var accessorList = SyntaxFactory.AccessorList(accessorDeclList); newProp = propertyDeclaration.WithAccessorList(accessorList); } var newRoot = root.ReplaceNode((SyntaxNode)propertyDeclaration, newProp).WithAdditionalAnnotations(Formatter.Annotation); return(document.WithSyntaxRoot(newRoot)); }