private void CreateDelegateDeclaration(Document document, FuncOrAction funcOrAction, IParameterSymbol parameterSymbol, out string newDelegateName, out DelegateDeclarationSyntax delegateDeclaration) { var syntaxGenerator = SyntaxGenerator.GetGenerator(document); var parameters = funcOrAction switch { FuncOrAction.Action action => action.Parameters, FuncOrAction.Func func => func.Parameters, _ => throw new System.NotImplementedException() }; newDelegateName = MakeFirstLetterUpperCase(parameterSymbol.Name); delegateDeclaration = (DelegateDeclarationSyntax)syntaxGenerator.DelegateDeclaration( newDelegateName, parameters .Select(p => syntaxGenerator.ParameterDeclaration( p.Name, syntaxGenerator.TypeExpression(p.Type))), accessibility: Accessibility.Public); if (funcOrAction is FuncOrAction.Func func1) { delegateDeclaration = delegateDeclaration .WithReturnType((TypeSyntax)syntaxGenerator.TypeExpression(func1.ReturnType)); } }
private async Task <Document> UpdateDocumentToAddAndUseANewDelegate( Document document, FuncOrAction funcOrAction, ParameterSyntax parameterSyntax, IParameterSymbol parameterSymbol, SemanticModel semanticModel) { var syntaxGenerator = SyntaxGenerator.GetGenerator(document); var parameters = funcOrAction switch { FuncOrAction.Action action => action.Parameters, FuncOrAction.Func func => func.Parameters, _ => throw new System.NotImplementedException() }; var newDelegateName = MakeFirstLetterUpperCase(parameterSymbol.Name); var delegateDeclaration = (DelegateDeclarationSyntax)syntaxGenerator.DelegateDeclaration( newDelegateName, parameters .Select(p => syntaxGenerator.ParameterDeclaration( p.Name, syntaxGenerator.TypeExpression(p.Type))), accessibility: Accessibility.Public); if (funcOrAction is FuncOrAction.Func func1) { delegateDeclaration = delegateDeclaration .WithReturnType((TypeSyntax)syntaxGenerator.TypeExpression(func1.ReturnType)); } var method = (MethodDeclarationSyntax)parameterSyntax.Parent.Parent; var updatedMethod = method.ReplaceNode(parameterSyntax.Type, SyntaxFactory.IdentifierName(newDelegateName)); var root = await document.GetSyntaxRootAsync(); var containingType = (TypeDeclarationSyntax)method.Parent; var indexOfMethodWithinSiblingMembers = containingType.Members.IndexOf(method); var updatedRoot = root.ReplaceNodes(new SyntaxNode[] { method, containingType }, (originalNode, possiblyChangedNode) => { if (originalNode == method) { return(updatedMethod); } else if (originalNode == containingType) { var possibleChangedContainingType = (TypeDeclarationSyntax)possiblyChangedNode; var newMembers = possibleChangedContainingType.Members.Insert( indexOfMethodWithinSiblingMembers, delegateDeclaration); return(possibleChangedContainingType.WithMembers(SyntaxFactory.List(newMembers))); } throw new System.Exception("Unexpected: originalNode is not any of the nodes passed to ReplaceNodes"); }); return(document.WithSyntaxRoot(updatedRoot)); }