You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

DiagnosticVerifier.Helper.cs 9.8 kB

7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Collections.Immutable;
  4. using System.Linq;
  5. using System.Reflection;
  6. using Discord.Commands;
  7. using Microsoft.CodeAnalysis;
  8. using Microsoft.CodeAnalysis.CSharp;
  9. using Microsoft.CodeAnalysis.Diagnostics;
  10. using Microsoft.CodeAnalysis.Text;
  11. namespace TestHelper
  12. {
  13. /// <summary>
  14. /// Class for turning strings into documents and getting the diagnostics on them
  15. /// All methods are static
  16. /// </summary>
  17. public abstract partial class DiagnosticVerifier
  18. {
  19. private static readonly MetadataReference CorlibReference =
  20. MetadataReference.CreateFromFile(typeof(object).GetTypeInfo().Assembly.Location);
  21. private static readonly MetadataReference SystemCoreReference =
  22. MetadataReference.CreateFromFile(typeof(Enumerable).GetTypeInfo().Assembly.Location);
  23. private static readonly MetadataReference CSharpSymbolsReference =
  24. MetadataReference.CreateFromFile(typeof(CSharpCompilation).GetTypeInfo().Assembly.Location);
  25. private static readonly MetadataReference CodeAnalysisReference =
  26. MetadataReference.CreateFromFile(typeof(Compilation).GetTypeInfo().Assembly.Location);
  27. //private static readonly MetadataReference DiscordNetReference = MetadataReference.CreateFromFile(typeof(IDiscordClient).GetTypeInfo().Assembly.Location);
  28. //private static readonly MetadataReference DiscordCommandsReference = MetadataReference.CreateFromFile(typeof(CommandAttribute).GetTypeInfo().Assembly.Location);
  29. private static readonly Assembly DiscordCommandsAssembly = typeof(CommandAttribute).GetTypeInfo().Assembly;
  30. internal static string DefaultFilePathPrefix = "Test";
  31. internal static string CSharpDefaultFileExt = "cs";
  32. internal static string VisualBasicDefaultExt = "vb";
  33. internal static string TestProjectName = "TestProject";
  34. /// <summary>
  35. /// Get the <see cref="MetadataReference" /> for <paramref name="assembly" /> and all assemblies referenced by
  36. /// <paramref name="assembly" />
  37. /// </summary>
  38. /// <param name="assembly">The assembly.</param>
  39. /// <returns><see cref="MetadataReference" />s.</returns>
  40. private static IEnumerable<MetadataReference> Transitive(Assembly assembly)
  41. {
  42. foreach (var a in RecursiveReferencedAssemblies(assembly))
  43. yield return MetadataReference.CreateFromFile(a.Location);
  44. }
  45. private static HashSet<Assembly> RecursiveReferencedAssemblies(Assembly a, HashSet<Assembly> assemblies = null)
  46. {
  47. assemblies = assemblies ?? new HashSet<Assembly>();
  48. if (!assemblies.Add(a)) return assemblies;
  49. foreach (var referencedAssemblyName in a.GetReferencedAssemblies())
  50. {
  51. var referencedAssembly = AppDomain.CurrentDomain.GetAssemblies()
  52. .SingleOrDefault(x => x.GetName() == referencedAssemblyName) ??
  53. Assembly.Load(referencedAssemblyName);
  54. RecursiveReferencedAssemblies(referencedAssembly, assemblies);
  55. }
  56. return assemblies;
  57. }
  58. #region Get Diagnostics
  59. /// <summary>
  60. /// Given classes in the form of strings, their language, and an IDiagnosticAnlayzer to apply to it, return the
  61. /// diagnostics found in the string after converting it to a document.
  62. /// </summary>
  63. /// <param name="sources">Classes in the form of strings</param>
  64. /// <param name="language">The language the source classes are in</param>
  65. /// <param name="analyzer">The analyzer to be run on the sources</param>
  66. /// <returns>An IEnumerable of Diagnostics that surfaced in the source code, sorted by Location</returns>
  67. private static Diagnostic[]
  68. GetSortedDiagnostics(string[] sources, string language, DiagnosticAnalyzer analyzer) =>
  69. GetSortedDiagnosticsFromDocuments(analyzer, GetDocuments(sources, language));
  70. /// <summary>
  71. /// Given an analyzer and a document to apply it to, run the analyzer and gather an array of diagnostics found in it.
  72. /// The returned diagnostics are then ordered by location in the source document.
  73. /// </summary>
  74. /// <param name="analyzer">The analyzer to run on the documents</param>
  75. /// <param name="documents">The Documents that the analyzer will be run on</param>
  76. /// <returns>An IEnumerable of Diagnostics that surfaced in the source code, sorted by Location</returns>
  77. protected static Diagnostic[] GetSortedDiagnosticsFromDocuments(DiagnosticAnalyzer analyzer,
  78. Document[] documents)
  79. {
  80. var projects = new HashSet<Project>();
  81. foreach (var document in documents) projects.Add(document.Project);
  82. var diagnostics = new List<Diagnostic>();
  83. foreach (var project in projects)
  84. {
  85. var compilationWithAnalyzers =
  86. project.GetCompilationAsync().Result.WithAnalyzers(ImmutableArray.Create(analyzer));
  87. var diags = compilationWithAnalyzers.GetAnalyzerDiagnosticsAsync().Result;
  88. foreach (var diag in diags)
  89. if (diag.Location == Location.None || diag.Location.IsInMetadata)
  90. diagnostics.Add(diag);
  91. else
  92. for (var i = 0; i < documents.Length; i++)
  93. {
  94. var document = documents[i];
  95. var tree = document.GetSyntaxTreeAsync().Result;
  96. if (tree == diag.Location.SourceTree) diagnostics.Add(diag);
  97. }
  98. }
  99. var results = SortDiagnostics(diagnostics);
  100. diagnostics.Clear();
  101. return results;
  102. }
  103. /// <summary>
  104. /// Sort diagnostics by location in source document
  105. /// </summary>
  106. /// <param name="diagnostics">The list of Diagnostics to be sorted</param>
  107. /// <returns>An IEnumerable containing the Diagnostics in order of Location</returns>
  108. private static Diagnostic[] SortDiagnostics(IEnumerable<Diagnostic> diagnostics) =>
  109. diagnostics.OrderBy(d => d.Location.SourceSpan.Start).ToArray();
  110. #endregion
  111. #region Set up compilation and documents
  112. /// <summary>
  113. /// Given an array of strings as sources and a language, turn them into a project and return the documents and spans of
  114. /// it.
  115. /// </summary>
  116. /// <param name="sources">Classes in the form of strings</param>
  117. /// <param name="language">The language the source code is in</param>
  118. /// <returns>A Tuple containing the Documents produced from the sources and their TextSpans if relevant</returns>
  119. private static Document[] GetDocuments(string[] sources, string language)
  120. {
  121. if (language != LanguageNames.CSharp && language != LanguageNames.VisualBasic)
  122. throw new ArgumentException("Unsupported Language");
  123. var project = CreateProject(sources, language);
  124. var documents = project.Documents.ToArray();
  125. if (sources.Length != documents.Length)
  126. throw new Exception("Amount of sources did not match amount of Documents created");
  127. return documents;
  128. }
  129. /// <summary>
  130. /// Create a Document from a string through creating a project that contains it.
  131. /// </summary>
  132. /// <param name="source">Classes in the form of a string</param>
  133. /// <param name="language">The language the source code is in</param>
  134. /// <returns>A Document created from the source string</returns>
  135. protected static Document CreateDocument(string source, string language = LanguageNames.CSharp) =>
  136. CreateProject(new[] {source}, language).Documents.First();
  137. /// <summary>
  138. /// Create a project using the inputted strings as sources.
  139. /// </summary>
  140. /// <param name="sources">Classes in the form of strings</param>
  141. /// <param name="language">The language the source code is in</param>
  142. /// <returns>A Project created out of the Documents created from the source strings</returns>
  143. private static Project CreateProject(string[] sources, string language = LanguageNames.CSharp)
  144. {
  145. var fileNamePrefix = DefaultFilePathPrefix;
  146. var fileExt = language == LanguageNames.CSharp ? CSharpDefaultFileExt : VisualBasicDefaultExt;
  147. var projectId = ProjectId.CreateNewId(TestProjectName);
  148. var solution = new AdhocWorkspace()
  149. .CurrentSolution
  150. .AddProject(projectId, TestProjectName, TestProjectName, language)
  151. .AddMetadataReference(projectId, CorlibReference)
  152. .AddMetadataReference(projectId, SystemCoreReference)
  153. .AddMetadataReference(projectId, CSharpSymbolsReference)
  154. .AddMetadataReference(projectId, CodeAnalysisReference)
  155. .AddMetadataReferences(projectId, Transitive(DiscordCommandsAssembly));
  156. var count = 0;
  157. foreach (var source in sources)
  158. {
  159. var newFileName = fileNamePrefix + count + "." + fileExt;
  160. var documentId = DocumentId.CreateNewId(projectId, newFileName);
  161. solution = solution.AddDocument(documentId, newFileName, SourceText.From(source));
  162. count++;
  163. }
  164. return solution.GetProject(projectId);
  165. }
  166. #endregion
  167. }
  168. }