using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.Formatting;
using Microsoft.CodeAnalysis.Simplification;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
///
/// The Code under this class is generated by Visual Studio
///
namespace CustomRoslynAnalyzers.Test.TestHelper
{
///
/// Diagnostic Producer class with extra methods dealing with applying codefixes
/// All methods are static
///
public abstract partial class CodeFixVerifier : DiagnosticVerifier
{
///
/// Apply the inputted CodeAction to the inputted document.
/// Meant to be used to apply codefixes.
///
/// The Document to apply the fix on
/// A CodeAction that will be applied to the Document.
/// A Document with the changes from the CodeAction
private static Document ApplyFix(Document document, CodeAction codeAction)
{
var operations = codeAction.GetOperationsAsync(CancellationToken.None).Result;
var solution = operations.OfType().Single().ChangedSolution;
return solution.GetDocument(document.Id);
}
///
/// Compare two collections of Diagnostics,and return a list of any new diagnostics that appear only in the second collection.
/// Note: Considers Diagnostics to be the same if they have the same Ids. In the case of multiple diagnostics with the same Id in a row,
/// this method may not necessarily return the new one.
///
/// The Diagnostics that existed in the code before the CodeFix was applied
/// The Diagnostics that exist in the code after the CodeFix was applied
/// A list of Diagnostics that only surfaced in the code after the CodeFix was applied
private static IEnumerable GetNewDiagnostics(IEnumerable diagnostics, IEnumerable newDiagnostics)
{
var oldArray = diagnostics.OrderBy(d => d.Location.SourceSpan.Start).ToArray();
var newArray = newDiagnostics.OrderBy(d => d.Location.SourceSpan.Start).ToArray();
int oldIndex = 0;
int newIndex = 0;
while (newIndex < newArray.Length)
{
if (oldIndex < oldArray.Length && oldArray[oldIndex].Id == newArray[newIndex].Id)
{
++oldIndex;
++newIndex;
}
else
{
yield return newArray[newIndex++];
}
}
}
///
/// Get the existing compiler diagnostics on the inputted document.
///
/// The Document to run the compiler diagnostic analyzers on
/// The compiler diagnostics that were found in the code
private static IEnumerable GetCompilerDiagnostics(Document document)
{
return document.GetSemanticModelAsync().Result.GetDiagnostics();
}
///
/// Given a document, turn it into a string based on the syntax root
///
/// The Document to be converted to a string
/// A string containing the syntax of the Document after formatting
private static string GetStringFromDocument(Document document)
{
var simplifiedDoc = Simplifier.ReduceAsync(document, Simplifier.Annotation).Result;
var root = simplifiedDoc.GetSyntaxRootAsync().Result;
root = Formatter.Format(root, Formatter.Annotation, simplifiedDoc.Project.Solution.Workspace);
return root.GetText().ToString();
}
}
}