\n \n MSB3883: Unexpected exception: \n MSB3883: Eccezione imprevista: \n {StrBegin=\"MSB3883: \"}\n \n \n MSB3053: The assembly alias \"{1}\" on reference \"{0}\" contains illegal characters.\n MSB3053: l'alias dell'assembly \"{1}\" nel riferimento \"{0}\" contiene caratteri non ammessi.\n {StrBegin=\"MSB3053: \"}\n \n \n MSB3051: The parameter to the compiler is invalid. {0}\n MSB3051: parametro del compilatore non valido. {0}\n {StrBegin=\"MSB3051: \"}\n \n \n MSB3052: The parameter to the compiler is invalid, '{0}{1}' will be ignored.\n MSB3052: il parametro per il compilatore non è valido. '{0}{1}' verrà ignorato.\n {StrBegin=\"MSB3052: \"}\n \n \n The string \"{0}\" cannot be converted to a boolean (true/false) value.\n Non è possibile convertire la stringa \"{0}\" in un valore booleano (true/false).\n \n \n \n MSB3081: A problem occurred while trying to set the \"{0}\" parameter for the IDE's in-process compiler. {1}\n MSB3081: si è verificato un problema durante il tentativo di impostare il parametro \"{0}\" per il compilatore in-process dell'IDE. {1}\n {StrBegin=\"MSB3081: \"}\n \n \n MSB3105: The item \"{0}\" was specified more than once in the \"{1}\" parameter. Duplicate items are not supported by the \"{1}\" parameter.\n MSB3105: l'elemento \"{0}\" è stato specificato più di una volta nel parametro \"{1}\", ma il parametro \"{1}\" non supporta gli elementi duplicati.\n {StrBegin=\"MSB3105: \"}\n \n \n MSB3083: The item \"{0}\" was specified more than once in the \"{1}\" parameter and both items had the same value \"{2}\" for the \"{3}\" metadata. Duplicate items are not supported by the \"{1}\" parameter unless they have different values for the \"{3}\" metadata.\n MSB3083: l'elemento \"{0}\" è stato specificato più di una volta nel parametro \"{1}\" ed entrambi gli elementi hanno lo stesso valore \"{2}\" per i metadati di \"{3}\". Il parametro \"{1}\" non supporta gli elementi duplicati a meno che non includano valori diversi per i metadati di \"{3}\".\n {StrBegin=\"MSB3083: \"}\n \n \n Expected file \"{0}\" does not exist.\n Il file previsto \"{0}\" non esiste.\n \n \n \n Reference assembly \"{0}\" already has latest information. Leaving it untouched.\n Le informazioni nell'assembly di riferimento \"{0}\" sono già le più recenti. Non verranno modificate.\n \n \n \n Could not extract the MVID from \"{0}\". Are you sure it is a reference assembly?\n Non è stato possibile estrarre il MVID da \"{0}\". Si è sicuri che si tratti di un assembly di riferimento?\n \n \n \n Failed to check the content hash of the source ref assembly '{0}': {1}\n{2}\n Non è stato possibile verificare l'hash del contenuto dell'assembly di riferimento di origine '{0}': {1}\n{2}\n \n \n \n Failed to check the content hash of the destination ref assembly '{0}'. It will be overwritten.\n Non è stato possibile verificare l'hash del contenuto dell'assembly di riferimento di destinazione '{0}'. Verrà sovrascritto.\n \n \n \n MSB3082: Task failed because \"{0}\" was not found.\n MSB3082: l'attività non è riuscita perché \"{0}\" non è stato trovato.\n {StrBegin=\"MSB3082: \"}\n \n \n MSB3087: An incompatible host object was passed into the \"{0}\" task. The host object for this task must implement the \"{1}\" interface.\n MSB3087: all'attività \"{0}\" è stato passato un oggetto host incompatibile. L'oggetto host di questa attività deve implementare l'interfaccia \"{1}\".\n {StrBegin=\"MSB3087: \"}\n \n \n Item \"{0}\" has attribute \"{1}\" with value \"{2}\" that could not be converted to \"{3}\".\n L'elemento \"{0}\" contiene l'attributo \"{1}\" con valore \"{2}\" che non è stato possibile convertire in \"{3}\".\n \n \n \n The IDE's in-process compiler does not support the specified values for the \"{0}\" parameter. Therefore, this task will fallback to using the command-line compiler.\n Il compilatore in-process dell'IDE non supporta i valori specificati per il parametro \"{0}\", di conseguenza per questa attività verrà usato in sostituzione il compilatore da riga di comando.\n \n \n \n MSB3104: The referenced assembly \"{0}\" was not found. If this assembly is produced by another one of your projects, please make sure to build that project before building this one.\n MSB3104: il modello \"{0}\" a cui si fa riferimento non è stato trovato. Se l'assembly è prodotto da un altro progetto, assicurarsi di compilare tale progetto prima di compilare quello corrente.\n {StrBegin=\"MSB3104: \"}\n \n \n File \"{0}\" could not be read: {1}\n Non è stato possibile leggere il file \"{0}\": {1}\n \n \n \n Skipping analyzers to speed up the build. You can execute 'Build' or 'Rebuild' command to run analyzers.\n Skipping analyzers to speed up the build. You can execute 'Build' or 'Rebuild' command to run analyzers.\n \n \n \n Shared compilation failed; falling back to tool: {0}\n La compilazione condivisa non è riuscita. Verrà eseguito il fallback allo strumento: {0}\n \n \n \n Using shared compilation with compiler from directory: {0}\n Verrà usata la compilazione condivisa con il compilatore della directory: {0}\n \n \n \n MSB3401: \"{1}\" is an invalid value for the \"{0}\" parameter. The valid values are: {2}\n MSB3401: \"{1}\" è un valore non valido per il parametro \"{0}\". I valori validi sono: {2}\n {StrBegin=\"MSB3401: \"}\n \n \n \"{1}\" is an invalid value for the \"{0}\" parameter.\n \"{1}\" non è un valore valido per il parametro \"{0}\".\n \n \n \n MSB3402: There was an error creating the pdb file \"{0}\". {1}\n MSB3402: si è verificato un errore durante la creazione del file PDB \"{0}\". {1}\n {StrBegin=\"MSB3402: \"}\n \n \n {0} contains duplicate items '{1}' with conflicting metadata '{2}': '{3}' and '{4}'\n {0} contiene elementi duplicati '{1}' con metadati in conflitto '{2}': '{3}' e '{4}'\n \n \n \n {0} paths are required to end with a slash or backslash: '{1}'\n {0} percorsi devono terminare con una barra o una barra rovesciata: '{1}'\n \n \n \n {0} items must include at least one top-level (not nested) item when {1} is true\n {0} elementi devono includere almeno un elemento di primo livello (non annidato) quando {1} è true\n \n \n \n The value of {0} not found in {1} items, or the corresponding item is not a top-level source root: '{2}'\n Il valore di {0} non è stato trovato negli elementi {1} oppure l'elemento corrispondente non è una radice di origine di primo livello: '{2}'\n \n \n
\n \n"},"label":{"kind":"number","value":-1,"string":"-1"}}},{"rowIdx":627,"cells":{"repo_name":{"kind":"string","value":"dotnet/roslyn"},"pr_number":{"kind":"number","value":56433,"string":"56,433"},"pr_title":{"kind":"string","value":"Only allow Contract.ThrowIfNull() to be called on nullable types"},"pr_description":{"kind":"string","value":"We had some places we were calling it on bools."},"author":{"kind":"string","value":"jasonmalinowski"},"date_created":{"kind":"timestamp","value":"2021-09-16T01:20:43Z","string":"2021-09-16T01:20:43Z"},"date_merged":{"kind":"timestamp","value":"2021-09-16T18:44:11Z","string":"2021-09-16T18:44:11Z"},"previous_commit":{"kind":"string","value":"736fc1b5e6e2847689c0154b3e5f23ea99dd56af"},"pr_commit":{"kind":"string","value":"6d0f4e3f972ceb561b04574e7f957a4ff458e272"},"query":{"kind":"string","value":"Only allow Contract.ThrowIfNull() to be called on nullable types. We had some places we were calling it on bools."},"filepath":{"kind":"string","value":"./src/Compilers/Core/MSBuildTask/GenerateMSBuildEditorConfig.cs"},"before_content":{"kind":"string","value":"// Licensed to the .NET Foundation under one or more agreements.\n// The .NET Foundation licenses this file to you under the MIT license.\n// See the LICENSE file in the project root for more information.\n\nusing System;\nusing System.IO;\nusing System.Linq;\nusing System.Text;\nusing Microsoft.Build.Framework;\nusing Microsoft.Build.Utilities;\nusing Roslyn.Utilities;\n\nnamespace Microsoft.CodeAnalysis.BuildTasks\n{\n /// \n /// Transforms a set of MSBuild Properties and Metadata into a global analyzer config.\n /// \n /// \n /// This task takes a set of items passed in via and and transforms\n /// them into a global analyzer config. \n /// \n /// is expected to be a list of items whose is the property name\n /// and have a metadata value called Value that contains the evaluated value of the property. Each of the ]\n /// will be transformed into an build_property.ItemSpec = Value entry in the\n /// global section of the generated config file.\n /// \n /// is expected to be a list of items whose represents a file in the \n /// compilation source tree. It should have two metadata values: ItemType is the name of the MSBuild item that originally \n /// included the file (e.g. Compile, AdditionalFile etc.); MetadataName is expected to contain the name of\n /// another piece of metadata that should be retrieved and used as the output value in the file. It is expected that a given \n /// file can have multiple entries in the differing by its ItemType.\n /// \n /// Each of the will be transformed into a new section in the generated config file. The section\n /// header will be the full path of the item (generated via its), and each section will have a \n /// set of build_metadata.ItemType.MetadataName = RetrievedMetadataValue, one per ItemType\n /// \n /// The Microsoft.Managed.Core.targets calls this task with the collected results of the AnalyzerProperty and \n /// AnalyzerItemMetadata item groups. \n /// \n public sealed class GenerateMSBuildEditorConfig : Task\n {\n /// \n /// Although this task does its own writing to disk, this\n /// output parameter is here for testing purposes.\n /// \n [Output]\n public string ConfigFileContents { get; set; }\n\n [Required]\n public ITaskItem[] MetadataItems { get; set; }\n\n [Required]\n public ITaskItem[] PropertyItems { get; set; }\n\n public ITaskItem FileName { get; set; }\n\n public GenerateMSBuildEditorConfig()\n {\n ConfigFileContents = string.Empty;\n MetadataItems = Array.Empty();\n PropertyItems = Array.Empty();\n FileName = new TaskItem();\n }\n\n public override bool Execute()\n {\n StringBuilder builder = new StringBuilder();\n\n // we always generate global configs\n builder.AppendLine(\"is_global = true\");\n\n // collect the properties into a global section\n foreach (var prop in PropertyItems)\n {\n builder.Append(\"build_property.\")\n .Append(prop.ItemSpec)\n .Append(\" = \")\n .AppendLine(prop.GetMetadata(\"Value\"));\n }\n\n // group the metadata items by their full path\n var groupedItems = MetadataItems.GroupBy(i => NormalizeWithForwardSlash(i.GetMetadata(\"FullPath\")));\n\n foreach (var group in groupedItems)\n {\n // write the section for this item\n builder.AppendLine()\n .Append(\"[\");\n EncodeString(builder, group.Key);\n builder.AppendLine(\"]\");\n\n foreach (var item in group)\n {\n string itemType = item.GetMetadata(\"ItemType\");\n string metadataName = item.GetMetadata(\"MetadataName\");\n if (!string.IsNullOrWhiteSpace(itemType) && !string.IsNullOrWhiteSpace(metadataName))\n {\n builder.Append(\"build_metadata.\")\n .Append(itemType)\n .Append(\".\")\n .Append(metadataName)\n .Append(\" = \")\n .AppendLine(item.GetMetadata(metadataName));\n }\n }\n }\n\n ConfigFileContents = builder.ToString();\n return string.IsNullOrEmpty(FileName.ItemSpec) ? true : WriteMSBuildEditorConfig();\n }\n\n internal bool WriteMSBuildEditorConfig()\n {\n try\n {\n var targetFileName = FileName.ItemSpec;\n if (File.Exists(targetFileName))\n {\n string existingContents = File.ReadAllText(targetFileName);\n if (existingContents.Equals(ConfigFileContents))\n {\n return true;\n }\n }\n var encoding = new UTF8Encoding(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: true);\n File.WriteAllText(targetFileName, ConfigFileContents, encoding);\n return true;\n }\n catch (IOException ex)\n {\n Log.LogErrorFromException(ex);\n return false;\n }\n }\n\n /// \n /// Filenames with special characters like '#' and'{' get written\n /// into the section names in the resulting .editorconfig file. Later,\n /// when the file is parsed in configuration options these special\n /// characters are interpretted as invalid values and ignored by the\n /// processor. We encode the special characters in these strings\n /// before writing them here.\n /// \n\n private static void EncodeString(StringBuilder builder, string value)\n {\n foreach (var c in value)\n {\n if (c is '*' or '?' or '{' or ',' or ';' or '}' or '[' or ']' or '#' or '!')\n {\n builder.Append(\"\\\\\");\n }\n builder.Append(c);\n }\n }\n\n /// \n /// Equivalent to Roslyn.Utilities.PathUtilities.NormalizeWithForwardSlash\n /// Both methods should be kept in sync.\n /// \n private static string NormalizeWithForwardSlash(string p)\n => PlatformInformation.IsUnix ? p : p.Replace('\\\\', '/');\n }\n}\n"},"after_content":{"kind":"string","value":"// Licensed to the .NET Foundation under one or more agreements.\n// The .NET Foundation licenses this file to you under the MIT license.\n// See the LICENSE file in the project root for more information.\n\nusing System;\nusing System.IO;\nusing System.Linq;\nusing System.Text;\nusing Microsoft.Build.Framework;\nusing Microsoft.Build.Utilities;\nusing Roslyn.Utilities;\n\nnamespace Microsoft.CodeAnalysis.BuildTasks\n{\n /// \n /// Transforms a set of MSBuild Properties and Metadata into a global analyzer config.\n /// \n /// \n /// This task takes a set of items passed in via and and transforms\n /// them into a global analyzer config. \n /// \n /// is expected to be a list of items whose is the property name\n /// and have a metadata value called Value that contains the evaluated value of the property. Each of the ]\n /// will be transformed into an build_property.ItemSpec = Value entry in the\n /// global section of the generated config file.\n /// \n /// is expected to be a list of items whose represents a file in the \n /// compilation source tree. It should have two metadata values: ItemType is the name of the MSBuild item that originally \n /// included the file (e.g. Compile, AdditionalFile etc.); MetadataName is expected to contain the name of\n /// another piece of metadata that should be retrieved and used as the output value in the file. It is expected that a given \n /// file can have multiple entries in the differing by its ItemType.\n /// \n /// Each of the will be transformed into a new section in the generated config file. The section\n /// header will be the full path of the item (generated via its), and each section will have a \n /// set of build_metadata.ItemType.MetadataName = RetrievedMetadataValue, one per ItemType\n /// \n /// The Microsoft.Managed.Core.targets calls this task with the collected results of the AnalyzerProperty and \n /// AnalyzerItemMetadata item groups. \n /// \n public sealed class GenerateMSBuildEditorConfig : Task\n {\n /// \n /// Although this task does its own writing to disk, this\n /// output parameter is here for testing purposes.\n /// \n [Output]\n public string ConfigFileContents { get; set; }\n\n [Required]\n public ITaskItem[] MetadataItems { get; set; }\n\n [Required]\n public ITaskItem[] PropertyItems { get; set; }\n\n public ITaskItem FileName { get; set; }\n\n public GenerateMSBuildEditorConfig()\n {\n ConfigFileContents = string.Empty;\n MetadataItems = Array.Empty();\n PropertyItems = Array.Empty();\n FileName = new TaskItem();\n }\n\n public override bool Execute()\n {\n StringBuilder builder = new StringBuilder();\n\n // we always generate global configs\n builder.AppendLine(\"is_global = true\");\n\n // collect the properties into a global section\n foreach (var prop in PropertyItems)\n {\n builder.Append(\"build_property.\")\n .Append(prop.ItemSpec)\n .Append(\" = \")\n .AppendLine(prop.GetMetadata(\"Value\"));\n }\n\n // group the metadata items by their full path\n var groupedItems = MetadataItems.GroupBy(i => NormalizeWithForwardSlash(i.GetMetadata(\"FullPath\")));\n\n foreach (var group in groupedItems)\n {\n // write the section for this item\n builder.AppendLine()\n .Append(\"[\");\n EncodeString(builder, group.Key);\n builder.AppendLine(\"]\");\n\n foreach (var item in group)\n {\n string itemType = item.GetMetadata(\"ItemType\");\n string metadataName = item.GetMetadata(\"MetadataName\");\n if (!string.IsNullOrWhiteSpace(itemType) && !string.IsNullOrWhiteSpace(metadataName))\n {\n builder.Append(\"build_metadata.\")\n .Append(itemType)\n .Append(\".\")\n .Append(metadataName)\n .Append(\" = \")\n .AppendLine(item.GetMetadata(metadataName));\n }\n }\n }\n\n ConfigFileContents = builder.ToString();\n return string.IsNullOrEmpty(FileName.ItemSpec) ? true : WriteMSBuildEditorConfig();\n }\n\n internal bool WriteMSBuildEditorConfig()\n {\n try\n {\n var targetFileName = FileName.ItemSpec;\n if (File.Exists(targetFileName))\n {\n string existingContents = File.ReadAllText(targetFileName);\n if (existingContents.Equals(ConfigFileContents))\n {\n return true;\n }\n }\n var encoding = new UTF8Encoding(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: true);\n File.WriteAllText(targetFileName, ConfigFileContents, encoding);\n return true;\n }\n catch (IOException ex)\n {\n Log.LogErrorFromException(ex);\n return false;\n }\n }\n\n /// \n /// Filenames with special characters like '#' and'{' get written\n /// into the section names in the resulting .editorconfig file. Later,\n /// when the file is parsed in configuration options these special\n /// characters are interpretted as invalid values and ignored by the\n /// processor. We encode the special characters in these strings\n /// before writing them here.\n /// \n\n private static void EncodeString(StringBuilder builder, string value)\n {\n foreach (var c in value)\n {\n if (c is '*' or '?' or '{' or ',' or ';' or '}' or '[' or ']' or '#' or '!')\n {\n builder.Append(\"\\\\\");\n }\n builder.Append(c);\n }\n }\n\n /// \n /// Equivalent to Roslyn.Utilities.PathUtilities.NormalizeWithForwardSlash\n /// Both methods should be kept in sync.\n /// \n private static string NormalizeWithForwardSlash(string p)\n => PlatformInformation.IsUnix ? p : p.Replace('\\\\', '/');\n }\n}\n"},"label":{"kind":"number","value":-1,"string":"-1"}}},{"rowIdx":628,"cells":{"repo_name":{"kind":"string","value":"dotnet/roslyn"},"pr_number":{"kind":"number","value":56433,"string":"56,433"},"pr_title":{"kind":"string","value":"Only allow Contract.ThrowIfNull() to be called on nullable types"},"pr_description":{"kind":"string","value":"We had some places we were calling it on bools."},"author":{"kind":"string","value":"jasonmalinowski"},"date_created":{"kind":"timestamp","value":"2021-09-16T01:20:43Z","string":"2021-09-16T01:20:43Z"},"date_merged":{"kind":"timestamp","value":"2021-09-16T18:44:11Z","string":"2021-09-16T18:44:11Z"},"previous_commit":{"kind":"string","value":"736fc1b5e6e2847689c0154b3e5f23ea99dd56af"},"pr_commit":{"kind":"string","value":"6d0f4e3f972ceb561b04574e7f957a4ff458e272"},"query":{"kind":"string","value":"Only allow Contract.ThrowIfNull() to be called on nullable types. We had some places we were calling it on bools."},"filepath":{"kind":"string","value":"./src/Features/Core/Portable/ConvertAnonymousType/AbstractConvertAnonymousTypeToClassCodeRefactoringProvider.cs"},"before_content":{"kind":"string","value":"// Licensed to the .NET Foundation under one or more agreements.\n// The .NET Foundation licenses this file to you under the MIT license.\n// See the LICENSE file in the project root for more information.\n\nusing System;\nusing System.Collections.Generic;\nusing System.Collections.Immutable;\nusing System.Diagnostics;\nusing System.Linq;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing Microsoft.CodeAnalysis.CodeActions;\nusing Microsoft.CodeAnalysis.CodeGeneration;\nusing Microsoft.CodeAnalysis.CodeRefactorings;\nusing Microsoft.CodeAnalysis.Editing;\nusing Microsoft.CodeAnalysis.Formatting;\nusing Microsoft.CodeAnalysis.GenerateEqualsAndGetHashCodeFromMembers;\nusing Microsoft.CodeAnalysis.LanguageServices;\nusing Microsoft.CodeAnalysis.PooledObjects;\nusing Microsoft.CodeAnalysis.Shared.Extensions;\nusing Microsoft.CodeAnalysis.Shared.Utilities;\nusing Microsoft.CodeAnalysis.Text;\nusing Roslyn.Utilities;\n\nnamespace Microsoft.CodeAnalysis.ConvertAnonymousType\n{\n internal abstract class AbstractConvertAnonymousTypeToClassCodeRefactoringProvider<\n TExpressionSyntax,\n TNameSyntax,\n TIdentifierNameSyntax,\n TObjectCreationExpressionSyntax,\n TAnonymousObjectCreationExpressionSyntax,\n TNamespaceDeclarationSyntax>\n : AbstractConvertAnonymousTypeCodeRefactoringProvider\n where TExpressionSyntax : SyntaxNode\n where TNameSyntax : TExpressionSyntax\n where TIdentifierNameSyntax : TNameSyntax\n where TObjectCreationExpressionSyntax : TExpressionSyntax\n where TAnonymousObjectCreationExpressionSyntax : TExpressionSyntax\n where TNamespaceDeclarationSyntax : SyntaxNode\n {\n protected abstract TObjectCreationExpressionSyntax CreateObjectCreationExpression(TNameSyntax nameNode, TAnonymousObjectCreationExpressionSyntax currentAnonymousObject);\n\n public override async Task ComputeRefactoringsAsync(CodeRefactoringContext context)\n {\n var (document, textSpan, cancellationToken) = context;\n var (anonymousObject, anonymousType) = await TryGetAnonymousObjectAsync(document, textSpan, cancellationToken).ConfigureAwait(false);\n\n if (anonymousObject == null || anonymousType == null)\n return;\n\n // Check if the anonymous type actually references another anonymous type inside of it.\n // If it does, we can't convert this. There is no way to describe this anonymous type\n // in the concrete type we create.\n var containsAnonymousType = anonymousType.GetMembers()\n .OfType()\n .Any(p => p.Type.ContainsAnonymousType());\n if (containsAnonymousType)\n return;\n\n var syntaxFacts = document.GetRequiredLanguageService();\n if (syntaxFacts.SupportsRecord(anonymousObject.SyntaxTree.Options))\n {\n context.RegisterRefactoring(new MyCodeAction(\n FeaturesResources.Convert_to_record,\n c => ConvertAsync(document, textSpan, isRecord: true, c)),\n anonymousObject.Span);\n }\n\n context.RegisterRefactoring(new MyCodeAction(\n FeaturesResources.Convert_to_class,\n c => ConvertAsync(document, textSpan, isRecord: false, c)),\n anonymousObject.Span);\n }\n\n private async Task ConvertAsync(Document document, TextSpan span, bool isRecord, CancellationToken cancellationToken)\n {\n var (anonymousObject, anonymousType) = await TryGetAnonymousObjectAsync(document, span, cancellationToken).ConfigureAwait(false);\n\n Debug.Assert(anonymousObject != null);\n Debug.Assert(anonymousType != null);\n\n var position = span.Start;\n var options = await document.GetOptionsAsync(cancellationToken).ConfigureAwait(false);\n var root = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false);\n var semanticModel = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false);\n\n // Generate a unique name for the class we're creating. We'll also add a rename\n // annotation so the user can pick the right name for the type afterwards.\n var className = NameGenerator.GenerateUniqueName(\n isRecord ? \"NewRecord\" : \"NewClass\",\n n => semanticModel.LookupSymbols(position, name: n).IsEmpty);\n\n // First, create the set of properties this class will have based on the properties the\n // anonymous type has itself. Also, get a mapping of the original anonymous type's\n // properties to the new name we generated for it (if we converted camelCase to\n // PascalCase).\n var (properties, propertyMap) = GenerateProperties(document, anonymousType);\n\n // Next, generate the full class that will be used to replace all instances of this\n // anonymous type.\n var namedTypeSymbol = await GenerateFinalNamedTypeAsync(\n document, className, isRecord, properties, cancellationToken).ConfigureAwait(false);\n\n var generator = SyntaxGenerator.GetGenerator(document);\n var editor = new SyntaxEditor(root, generator);\n\n var syntaxFacts = document.GetRequiredLanguageService();\n var containingMember = anonymousObject.FirstAncestorOrSelf((node, syntaxFacts) => syntaxFacts.IsMethodLevelMember(node), syntaxFacts) ?? anonymousObject;\n\n // Next, go and update any references to these anonymous type properties to match\n // the new PascalCased name we've picked for the new properties that will go in\n // the named type.\n await ReplacePropertyReferencesAsync(\n document, editor, containingMember,\n propertyMap, cancellationToken).ConfigureAwait(false);\n\n // Next, go through and replace all matching anonymous types in this method with a call\n // to construct the new named type we've generated. \n await ReplaceMatchingAnonymousTypesAsync(\n document, editor, namedTypeSymbol,\n containingMember, anonymousObject,\n anonymousType, cancellationToken).ConfigureAwait(false);\n\n // Then, actually insert the new class in the appropriate container.\n var container = anonymousObject.GetAncestor() ?? root;\n editor.ReplaceNode(container, (currentContainer, _) =>\n {\n var codeGenService = document.GetRequiredLanguageService();\n var codeGenOptions = new CodeGenerationOptions(\n generateMembers: true,\n sortMembers: false,\n autoInsertionLocation: false,\n options: options,\n parseOptions: root.SyntaxTree.Options);\n\n return codeGenService.AddNamedType(\n currentContainer, namedTypeSymbol, codeGenOptions, cancellationToken);\n });\n\n var updatedDocument = document.WithSyntaxRoot(editor.GetChangedRoot());\n\n // Finally, format using the equals+getHashCode service so that our generated methods\n // follow any special formatting rules specific to them.\n var equalsAndGetHashCodeService = document.GetRequiredLanguageService();\n return await equalsAndGetHashCodeService.FormatDocumentAsync(\n updatedDocument, cancellationToken).ConfigureAwait(false);\n }\n\n private static async Task ReplacePropertyReferencesAsync(\n Document document, SyntaxEditor editor, SyntaxNode containingMember,\n ImmutableDictionary propertyMap, CancellationToken cancellationToken)\n {\n var syntaxFacts = document.GetRequiredLanguageService();\n var semanticModel = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false);\n var identifiers = containingMember.DescendantNodes().OfType();\n\n foreach (var identifier in identifiers)\n {\n if (!syntaxFacts.IsNameOfSimpleMemberAccessExpression(identifier) &&\n !syntaxFacts.IsNameOfMemberBindingExpression(identifier))\n {\n continue;\n }\n\n if (semanticModel.GetSymbolInfo(identifier, cancellationToken).GetAnySymbol() is not IPropertySymbol symbol)\n continue;\n\n if (propertyMap.TryGetValue(symbol, out var newName))\n {\n editor.ReplaceNode(\n identifier,\n (currentId, g) => g.IdentifierName(newName).WithTriviaFrom(currentId));\n }\n }\n }\n\n private async Task ReplaceMatchingAnonymousTypesAsync(\n Document document, SyntaxEditor editor, INamedTypeSymbol classSymbol,\n SyntaxNode containingMember, TAnonymousObjectCreationExpressionSyntax creationNode,\n INamedTypeSymbol anonymousType, CancellationToken cancellationToken)\n {\n // When invoked we want to fixup all creations of the \"same\" anonymous type within the\n // containing method. We define same-ness as meaning \"they have the type symbol\". this\n // means both have the same member names, in the same order, with the same member types.\n // We fix all these up in the method because the user may be creating several instances\n // of this anonymous type in that method and then combining them in interesting ways\n // (i.e. checking them for equality, using them in collections, etc.). The language\n // guarantees within a method boundary that these will be the same type and can be used\n // together in this fashion.\n //\n // Note: we could consider expanding this in the future (potentially with another\n // lightbulb action). Specifically, we could look in the containing type and replace\n // any matches in any methods.\n var semanticModel = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false);\n\n var childCreationNodes = containingMember.DescendantNodesAndSelf()\n .OfType();\n\n foreach (var childCreation in childCreationNodes)\n {\n var childType = semanticModel.GetTypeInfo(childCreation, cancellationToken).Type;\n if (childType == null)\n {\n Debug.Fail(\"We should always be able to get an anonymous type for any anonymous creation node.\");\n continue;\n }\n\n if (anonymousType.Equals(childType))\n ReplaceWithObjectCreation(editor, classSymbol, creationNode, childCreation);\n }\n }\n\n private void ReplaceWithObjectCreation(\n SyntaxEditor editor, INamedTypeSymbol classSymbol,\n TAnonymousObjectCreationExpressionSyntax startingCreationNode,\n TAnonymousObjectCreationExpressionSyntax childCreation)\n {\n // Use the callback form as anonymous types may be nested, and we want to\n // properly replace them even in that case.\n editor.ReplaceNode(\n childCreation,\n (currentNode, g) =>\n {\n var currentAnonymousObject = (TAnonymousObjectCreationExpressionSyntax)currentNode;\n\n // If we hit the node the user started on, then add the rename annotation here.\n var className = classSymbol.Name;\n var classNameToken = startingCreationNode == childCreation\n ? g.Identifier(className).WithAdditionalAnnotations(RenameAnnotation.Create())\n : g.Identifier(className);\n\n var classNameNode = classSymbol.TypeParameters.Length == 0\n ? (TNameSyntax)g.IdentifierName(classNameToken)\n : (TNameSyntax)g.GenericName(classNameToken,\n classSymbol.TypeParameters.Select(tp => g.IdentifierName(tp.Name)));\n\n return CreateObjectCreationExpression(classNameNode, currentAnonymousObject)\n .WithAdditionalAnnotations(Formatter.Annotation);\n });\n }\n\n private static async Task GenerateFinalNamedTypeAsync(\n Document document, string typeName, bool isRecord,\n ImmutableArray properties,\n CancellationToken cancellationToken)\n {\n var generator = SyntaxGenerator.GetGenerator(document);\n var semanticModel = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false);\n\n // Next, see if any of the properties ended up using any type parameters from the\n // containing method/named-type. If so, we'll need to generate a generic type so we can\n // properly pass these along.\n var capturedTypeParameters =\n properties.Select(p => p.Type)\n .SelectMany(t => t.GetReferencedTypeParameters())\n .Distinct()\n .ToImmutableArray();\n\n using var _ = ArrayBuilder.GetInstance(out var members);\n\n if (isRecord)\n {\n // Create a record with a single primary constructor, containing a parameter for all the properties\n // we're generating.\n var constructor = CodeGenerationSymbolFactory.CreateConstructorSymbol(\n attributes: default,\n Accessibility.Public,\n modifiers: default,\n typeName,\n properties.SelectAsArray(prop => CodeGenerationSymbolFactory.CreateParameterSymbol(prop.Type, prop.Name)),\n isPrimaryConstructor: true);\n\n members.Add(constructor);\n }\n else\n {\n // Now try to generate all the members that will go in the new class. This is a bit\n // circular. In order to generate some of the members, we need to know about the type.\n // But in order to create the type, we need the members. To address this we do two\n // passes. First, we create an empty version of the class. This can then be used to\n // help create members like Equals/GetHashCode. Then, once we have all the members we\n // create the final type.\n var namedTypeWithoutMembers = CreateNamedType(typeName, isRecord: false, capturedTypeParameters, members: default);\n\n var constructor = CreateClassConstructor(semanticModel, typeName, properties, generator);\n\n // Generate Equals/GetHashCode. Only readonly properties are suitable for these\n // methods. We can defer to our existing language service for this so that we\n // generate the same Equals/GetHashCode that our other IDE features generate.\n var readonlyProperties = ImmutableArray.CastUp(\n properties.WhereAsArray(p => p.SetMethod == null));\n\n var equalsAndGetHashCodeService = document.GetRequiredLanguageService();\n\n var equalsMethod = await equalsAndGetHashCodeService.GenerateEqualsMethodAsync(\n document, namedTypeWithoutMembers, readonlyProperties,\n localNameOpt: SyntaxGeneratorExtensions.OtherName, cancellationToken).ConfigureAwait(false);\n var getHashCodeMethod = await equalsAndGetHashCodeService.GenerateGetHashCodeMethodAsync(\n document, namedTypeWithoutMembers,\n readonlyProperties, cancellationToken).ConfigureAwait(false);\n\n members.AddRange(properties);\n members.Add(constructor);\n members.Add(equalsMethod);\n members.Add(getHashCodeMethod);\n\n }\n\n return CreateNamedType(typeName, isRecord, capturedTypeParameters, members.ToImmutable());\n }\n\n private static INamedTypeSymbol CreateNamedType(\n string className, bool isRecord, ImmutableArray capturedTypeParameters, ImmutableArray members)\n {\n return CodeGenerationSymbolFactory.CreateNamedTypeSymbol(\n attributes: default, Accessibility.Internal, modifiers: default,\n isRecord, TypeKind.Class, className, capturedTypeParameters, members: members);\n }\n\n private static (ImmutableArray properties, ImmutableDictionary propertyMap) GenerateProperties(\n Document document, INamedTypeSymbol anonymousType)\n {\n var originalProperties = anonymousType.GetMembers().OfType().ToImmutableArray();\n var newProperties = originalProperties.SelectAsArray(p => GenerateProperty(document, p));\n\n // If we changed the names of any properties, record that name mapping. We'll\n // use this to update reference to the old anonymous-type properties to the new\n // names.\n var builder = ImmutableDictionary.CreateBuilder();\n for (var i = 0; i < originalProperties.Length; i++)\n {\n var originalProperty = originalProperties[i];\n var newProperty = newProperties[i];\n\n if (originalProperty.Name != newProperty.Name)\n builder[originalProperty] = newProperty.Name;\n }\n\n return (newProperties, builder.ToImmutable());\n }\n\n private static IPropertySymbol GenerateProperty(Document document, IPropertySymbol prop)\n {\n // The actual properties generated by C#/VB are not what we want. For example, they\n // think of themselves as having real accessors that will read/write into a real field\n // in the type. Instead, we just want to generate auto-props. So we effectively clone\n // the property, just throwing aways anything we don't need for that purpose.\n // \n // We also want to follow general .NET naming. So that means converting to pascal\n // case from camel-case.\n\n var getMethod = prop.GetMethod != null ? CreateAccessorSymbol(prop, MethodKind.PropertyGet) : null;\n var setMethod = prop.SetMethod != null ? CreateAccessorSymbol(prop, MethodKind.PropertySet) : null;\n\n return CodeGenerationSymbolFactory.CreatePropertySymbol(\n attributes: default, Accessibility.Public, modifiers: default,\n prop.Type, refKind: default, explicitInterfaceImplementations: default,\n GetLegalName(prop.Name.ToPascalCase(trimLeadingTypePrefix: false), document),\n parameters: default, getMethod: getMethod, setMethod: setMethod);\n }\n\n private static string GetLegalName(string name, Document document)\n {\n var syntaxFacts = document.GetRequiredLanguageService();\n return syntaxFacts.IsLegalIdentifier(name)\n ? name\n : \"Item\"; // Just a dummy name for the property. Does not need to be localized.\n }\n\n private static IMethodSymbol CreateAccessorSymbol(IPropertySymbol prop, MethodKind kind)\n => CodeGenerationSymbolFactory.CreateMethodSymbol(\n attributes: default, Accessibility.Public, DeclarationModifiers.Abstract,\n prop.Type, refKind: default, explicitInterfaceImplementations: default,\n name: \"\", typeParameters: default, parameters: default, methodKind: kind);\n\n private static IMethodSymbol CreateClassConstructor(\n SemanticModel semanticModel, string className,\n ImmutableArray properties, SyntaxGenerator generator)\n {\n // For every property, create a corresponding parameter, as well as an assignment\n // statement from that parameter to the property.\n var parameterToPropMap = new Dictionary();\n var parameters = properties.SelectAsArray(prop =>\n {\n var parameter = CodeGenerationSymbolFactory.CreateParameterSymbol(\n prop.Type, prop.Name.ToCamelCase(trimLeadingTypePrefix: false));\n\n parameterToPropMap[parameter.Name] = prop;\n\n return parameter;\n });\n\n var assignmentStatements = generator.CreateAssignmentStatements(\n semanticModel, parameters, parameterToPropMap, ImmutableDictionary.Empty,\n addNullChecks: false, preferThrowExpression: false);\n\n var constructor = CodeGenerationSymbolFactory.CreateConstructorSymbol(\n attributes: default, Accessibility.Public, modifiers: default,\n className, parameters, assignmentStatements);\n\n return constructor;\n }\n\n private class MyCodeAction : CodeAction.DocumentChangeAction\n {\n public MyCodeAction(string title, Func> createChangedDocument)\n : base(title, createChangedDocument, title)\n {\n }\n }\n }\n}\n"},"after_content":{"kind":"string","value":"// Licensed to the .NET Foundation under one or more agreements.\n// The .NET Foundation licenses this file to you under the MIT license.\n// See the LICENSE file in the project root for more information.\n\nusing System;\nusing System.Collections.Generic;\nusing System.Collections.Immutable;\nusing System.Diagnostics;\nusing System.Linq;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing Microsoft.CodeAnalysis.CodeActions;\nusing Microsoft.CodeAnalysis.CodeGeneration;\nusing Microsoft.CodeAnalysis.CodeRefactorings;\nusing Microsoft.CodeAnalysis.Editing;\nusing Microsoft.CodeAnalysis.Formatting;\nusing Microsoft.CodeAnalysis.GenerateEqualsAndGetHashCodeFromMembers;\nusing Microsoft.CodeAnalysis.LanguageServices;\nusing Microsoft.CodeAnalysis.PooledObjects;\nusing Microsoft.CodeAnalysis.Shared.Extensions;\nusing Microsoft.CodeAnalysis.Shared.Utilities;\nusing Microsoft.CodeAnalysis.Text;\nusing Roslyn.Utilities;\n\nnamespace Microsoft.CodeAnalysis.ConvertAnonymousType\n{\n internal abstract class AbstractConvertAnonymousTypeToClassCodeRefactoringProvider<\n TExpressionSyntax,\n TNameSyntax,\n TIdentifierNameSyntax,\n TObjectCreationExpressionSyntax,\n TAnonymousObjectCreationExpressionSyntax,\n TNamespaceDeclarationSyntax>\n : AbstractConvertAnonymousTypeCodeRefactoringProvider\n where TExpressionSyntax : SyntaxNode\n where TNameSyntax : TExpressionSyntax\n where TIdentifierNameSyntax : TNameSyntax\n where TObjectCreationExpressionSyntax : TExpressionSyntax\n where TAnonymousObjectCreationExpressionSyntax : TExpressionSyntax\n where TNamespaceDeclarationSyntax : SyntaxNode\n {\n protected abstract TObjectCreationExpressionSyntax CreateObjectCreationExpression(TNameSyntax nameNode, TAnonymousObjectCreationExpressionSyntax currentAnonymousObject);\n\n public override async Task ComputeRefactoringsAsync(CodeRefactoringContext context)\n {\n var (document, textSpan, cancellationToken) = context;\n var (anonymousObject, anonymousType) = await TryGetAnonymousObjectAsync(document, textSpan, cancellationToken).ConfigureAwait(false);\n\n if (anonymousObject == null || anonymousType == null)\n return;\n\n // Check if the anonymous type actually references another anonymous type inside of it.\n // If it does, we can't convert this. There is no way to describe this anonymous type\n // in the concrete type we create.\n var containsAnonymousType = anonymousType.GetMembers()\n .OfType()\n .Any(p => p.Type.ContainsAnonymousType());\n if (containsAnonymousType)\n return;\n\n var syntaxFacts = document.GetRequiredLanguageService();\n if (syntaxFacts.SupportsRecord(anonymousObject.SyntaxTree.Options))\n {\n context.RegisterRefactoring(new MyCodeAction(\n FeaturesResources.Convert_to_record,\n c => ConvertAsync(document, textSpan, isRecord: true, c)),\n anonymousObject.Span);\n }\n\n context.RegisterRefactoring(new MyCodeAction(\n FeaturesResources.Convert_to_class,\n c => ConvertAsync(document, textSpan, isRecord: false, c)),\n anonymousObject.Span);\n }\n\n private async Task ConvertAsync(Document document, TextSpan span, bool isRecord, CancellationToken cancellationToken)\n {\n var (anonymousObject, anonymousType) = await TryGetAnonymousObjectAsync(document, span, cancellationToken).ConfigureAwait(false);\n\n Debug.Assert(anonymousObject != null);\n Debug.Assert(anonymousType != null);\n\n var position = span.Start;\n var options = await document.GetOptionsAsync(cancellationToken).ConfigureAwait(false);\n var root = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false);\n var semanticModel = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false);\n\n // Generate a unique name for the class we're creating. We'll also add a rename\n // annotation so the user can pick the right name for the type afterwards.\n var className = NameGenerator.GenerateUniqueName(\n isRecord ? \"NewRecord\" : \"NewClass\",\n n => semanticModel.LookupSymbols(position, name: n).IsEmpty);\n\n // First, create the set of properties this class will have based on the properties the\n // anonymous type has itself. Also, get a mapping of the original anonymous type's\n // properties to the new name we generated for it (if we converted camelCase to\n // PascalCase).\n var (properties, propertyMap) = GenerateProperties(document, anonymousType);\n\n // Next, generate the full class that will be used to replace all instances of this\n // anonymous type.\n var namedTypeSymbol = await GenerateFinalNamedTypeAsync(\n document, className, isRecord, properties, cancellationToken).ConfigureAwait(false);\n\n var generator = SyntaxGenerator.GetGenerator(document);\n var editor = new SyntaxEditor(root, generator);\n\n var syntaxFacts = document.GetRequiredLanguageService();\n var containingMember = anonymousObject.FirstAncestorOrSelf((node, syntaxFacts) => syntaxFacts.IsMethodLevelMember(node), syntaxFacts) ?? anonymousObject;\n\n // Next, go and update any references to these anonymous type properties to match\n // the new PascalCased name we've picked for the new properties that will go in\n // the named type.\n await ReplacePropertyReferencesAsync(\n document, editor, containingMember,\n propertyMap, cancellationToken).ConfigureAwait(false);\n\n // Next, go through and replace all matching anonymous types in this method with a call\n // to construct the new named type we've generated. \n await ReplaceMatchingAnonymousTypesAsync(\n document, editor, namedTypeSymbol,\n containingMember, anonymousObject,\n anonymousType, cancellationToken).ConfigureAwait(false);\n\n // Then, actually insert the new class in the appropriate container.\n var container = anonymousObject.GetAncestor() ?? root;\n editor.ReplaceNode(container, (currentContainer, _) =>\n {\n var codeGenService = document.GetRequiredLanguageService();\n var codeGenOptions = new CodeGenerationOptions(\n generateMembers: true,\n sortMembers: false,\n autoInsertionLocation: false,\n options: options,\n parseOptions: root.SyntaxTree.Options);\n\n return codeGenService.AddNamedType(\n currentContainer, namedTypeSymbol, codeGenOptions, cancellationToken);\n });\n\n var updatedDocument = document.WithSyntaxRoot(editor.GetChangedRoot());\n\n // Finally, format using the equals+getHashCode service so that our generated methods\n // follow any special formatting rules specific to them.\n var equalsAndGetHashCodeService = document.GetRequiredLanguageService();\n return await equalsAndGetHashCodeService.FormatDocumentAsync(\n updatedDocument, cancellationToken).ConfigureAwait(false);\n }\n\n private static async Task ReplacePropertyReferencesAsync(\n Document document, SyntaxEditor editor, SyntaxNode containingMember,\n ImmutableDictionary propertyMap, CancellationToken cancellationToken)\n {\n var syntaxFacts = document.GetRequiredLanguageService();\n var semanticModel = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false);\n var identifiers = containingMember.DescendantNodes().OfType();\n\n foreach (var identifier in identifiers)\n {\n if (!syntaxFacts.IsNameOfSimpleMemberAccessExpression(identifier) &&\n !syntaxFacts.IsNameOfMemberBindingExpression(identifier))\n {\n continue;\n }\n\n if (semanticModel.GetSymbolInfo(identifier, cancellationToken).GetAnySymbol() is not IPropertySymbol symbol)\n continue;\n\n if (propertyMap.TryGetValue(symbol, out var newName))\n {\n editor.ReplaceNode(\n identifier,\n (currentId, g) => g.IdentifierName(newName).WithTriviaFrom(currentId));\n }\n }\n }\n\n private async Task ReplaceMatchingAnonymousTypesAsync(\n Document document, SyntaxEditor editor, INamedTypeSymbol classSymbol,\n SyntaxNode containingMember, TAnonymousObjectCreationExpressionSyntax creationNode,\n INamedTypeSymbol anonymousType, CancellationToken cancellationToken)\n {\n // When invoked we want to fixup all creations of the \"same\" anonymous type within the\n // containing method. We define same-ness as meaning \"they have the type symbol\". this\n // means both have the same member names, in the same order, with the same member types.\n // We fix all these up in the method because the user may be creating several instances\n // of this anonymous type in that method and then combining them in interesting ways\n // (i.e. checking them for equality, using them in collections, etc.). The language\n // guarantees within a method boundary that these will be the same type and can be used\n // together in this fashion.\n //\n // Note: we could consider expanding this in the future (potentially with another\n // lightbulb action). Specifically, we could look in the containing type and replace\n // any matches in any methods.\n var semanticModel = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false);\n\n var childCreationNodes = containingMember.DescendantNodesAndSelf()\n .OfType();\n\n foreach (var childCreation in childCreationNodes)\n {\n var childType = semanticModel.GetTypeInfo(childCreation, cancellationToken).Type;\n if (childType == null)\n {\n Debug.Fail(\"We should always be able to get an anonymous type for any anonymous creation node.\");\n continue;\n }\n\n if (anonymousType.Equals(childType))\n ReplaceWithObjectCreation(editor, classSymbol, creationNode, childCreation);\n }\n }\n\n private void ReplaceWithObjectCreation(\n SyntaxEditor editor, INamedTypeSymbol classSymbol,\n TAnonymousObjectCreationExpressionSyntax startingCreationNode,\n TAnonymousObjectCreationExpressionSyntax childCreation)\n {\n // Use the callback form as anonymous types may be nested, and we want to\n // properly replace them even in that case.\n editor.ReplaceNode(\n childCreation,\n (currentNode, g) =>\n {\n var currentAnonymousObject = (TAnonymousObjectCreationExpressionSyntax)currentNode;\n\n // If we hit the node the user started on, then add the rename annotation here.\n var className = classSymbol.Name;\n var classNameToken = startingCreationNode == childCreation\n ? g.Identifier(className).WithAdditionalAnnotations(RenameAnnotation.Create())\n : g.Identifier(className);\n\n var classNameNode = classSymbol.TypeParameters.Length == 0\n ? (TNameSyntax)g.IdentifierName(classNameToken)\n : (TNameSyntax)g.GenericName(classNameToken,\n classSymbol.TypeParameters.Select(tp => g.IdentifierName(tp.Name)));\n\n return CreateObjectCreationExpression(classNameNode, currentAnonymousObject)\n .WithAdditionalAnnotations(Formatter.Annotation);\n });\n }\n\n private static async Task GenerateFinalNamedTypeAsync(\n Document document, string typeName, bool isRecord,\n ImmutableArray properties,\n CancellationToken cancellationToken)\n {\n var generator = SyntaxGenerator.GetGenerator(document);\n var semanticModel = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false);\n\n // Next, see if any of the properties ended up using any type parameters from the\n // containing method/named-type. If so, we'll need to generate a generic type so we can\n // properly pass these along.\n var capturedTypeParameters =\n properties.Select(p => p.Type)\n .SelectMany(t => t.GetReferencedTypeParameters())\n .Distinct()\n .ToImmutableArray();\n\n using var _ = ArrayBuilder.GetInstance(out var members);\n\n if (isRecord)\n {\n // Create a record with a single primary constructor, containing a parameter for all the properties\n // we're generating.\n var constructor = CodeGenerationSymbolFactory.CreateConstructorSymbol(\n attributes: default,\n Accessibility.Public,\n modifiers: default,\n typeName,\n properties.SelectAsArray(prop => CodeGenerationSymbolFactory.CreateParameterSymbol(prop.Type, prop.Name)),\n isPrimaryConstructor: true);\n\n members.Add(constructor);\n }\n else\n {\n // Now try to generate all the members that will go in the new class. This is a bit\n // circular. In order to generate some of the members, we need to know about the type.\n // But in order to create the type, we need the members. To address this we do two\n // passes. First, we create an empty version of the class. This can then be used to\n // help create members like Equals/GetHashCode. Then, once we have all the members we\n // create the final type.\n var namedTypeWithoutMembers = CreateNamedType(typeName, isRecord: false, capturedTypeParameters, members: default);\n\n var constructor = CreateClassConstructor(semanticModel, typeName, properties, generator);\n\n // Generate Equals/GetHashCode. Only readonly properties are suitable for these\n // methods. We can defer to our existing language service for this so that we\n // generate the same Equals/GetHashCode that our other IDE features generate.\n var readonlyProperties = ImmutableArray.CastUp(\n properties.WhereAsArray(p => p.SetMethod == null));\n\n var equalsAndGetHashCodeService = document.GetRequiredLanguageService();\n\n var equalsMethod = await equalsAndGetHashCodeService.GenerateEqualsMethodAsync(\n document, namedTypeWithoutMembers, readonlyProperties,\n localNameOpt: SyntaxGeneratorExtensions.OtherName, cancellationToken).ConfigureAwait(false);\n var getHashCodeMethod = await equalsAndGetHashCodeService.GenerateGetHashCodeMethodAsync(\n document, namedTypeWithoutMembers,\n readonlyProperties, cancellationToken).ConfigureAwait(false);\n\n members.AddRange(properties);\n members.Add(constructor);\n members.Add(equalsMethod);\n members.Add(getHashCodeMethod);\n\n }\n\n return CreateNamedType(typeName, isRecord, capturedTypeParameters, members.ToImmutable());\n }\n\n private static INamedTypeSymbol CreateNamedType(\n string className, bool isRecord, ImmutableArray capturedTypeParameters, ImmutableArray members)\n {\n return CodeGenerationSymbolFactory.CreateNamedTypeSymbol(\n attributes: default, Accessibility.Internal, modifiers: default,\n isRecord, TypeKind.Class, className, capturedTypeParameters, members: members);\n }\n\n private static (ImmutableArray properties, ImmutableDictionary propertyMap) GenerateProperties(\n Document document, INamedTypeSymbol anonymousType)\n {\n var originalProperties = anonymousType.GetMembers().OfType().ToImmutableArray();\n var newProperties = originalProperties.SelectAsArray(p => GenerateProperty(document, p));\n\n // If we changed the names of any properties, record that name mapping. We'll\n // use this to update reference to the old anonymous-type properties to the new\n // names.\n var builder = ImmutableDictionary.CreateBuilder();\n for (var i = 0; i < originalProperties.Length; i++)\n {\n var originalProperty = originalProperties[i];\n var newProperty = newProperties[i];\n\n if (originalProperty.Name != newProperty.Name)\n builder[originalProperty] = newProperty.Name;\n }\n\n return (newProperties, builder.ToImmutable());\n }\n\n private static IPropertySymbol GenerateProperty(Document document, IPropertySymbol prop)\n {\n // The actual properties generated by C#/VB are not what we want. For example, they\n // think of themselves as having real accessors that will read/write into a real field\n // in the type. Instead, we just want to generate auto-props. So we effectively clone\n // the property, just throwing aways anything we don't need for that purpose.\n // \n // We also want to follow general .NET naming. So that means converting to pascal\n // case from camel-case.\n\n var getMethod = prop.GetMethod != null ? CreateAccessorSymbol(prop, MethodKind.PropertyGet) : null;\n var setMethod = prop.SetMethod != null ? CreateAccessorSymbol(prop, MethodKind.PropertySet) : null;\n\n return CodeGenerationSymbolFactory.CreatePropertySymbol(\n attributes: default, Accessibility.Public, modifiers: default,\n prop.Type, refKind: default, explicitInterfaceImplementations: default,\n GetLegalName(prop.Name.ToPascalCase(trimLeadingTypePrefix: false), document),\n parameters: default, getMethod: getMethod, setMethod: setMethod);\n }\n\n private static string GetLegalName(string name, Document document)\n {\n var syntaxFacts = document.GetRequiredLanguageService();\n return syntaxFacts.IsLegalIdentifier(name)\n ? name\n : \"Item\"; // Just a dummy name for the property. Does not need to be localized.\n }\n\n private static IMethodSymbol CreateAccessorSymbol(IPropertySymbol prop, MethodKind kind)\n => CodeGenerationSymbolFactory.CreateMethodSymbol(\n attributes: default, Accessibility.Public, DeclarationModifiers.Abstract,\n prop.Type, refKind: default, explicitInterfaceImplementations: default,\n name: \"\", typeParameters: default, parameters: default, methodKind: kind);\n\n private static IMethodSymbol CreateClassConstructor(\n SemanticModel semanticModel, string className,\n ImmutableArray properties, SyntaxGenerator generator)\n {\n // For every property, create a corresponding parameter, as well as an assignment\n // statement from that parameter to the property.\n var parameterToPropMap = new Dictionary();\n var parameters = properties.SelectAsArray(prop =>\n {\n var parameter = CodeGenerationSymbolFactory.CreateParameterSymbol(\n prop.Type, prop.Name.ToCamelCase(trimLeadingTypePrefix: false));\n\n parameterToPropMap[parameter.Name] = prop;\n\n return parameter;\n });\n\n var assignmentStatements = generator.CreateAssignmentStatements(\n semanticModel, parameters, parameterToPropMap, ImmutableDictionary.Empty,\n addNullChecks: false, preferThrowExpression: false);\n\n var constructor = CodeGenerationSymbolFactory.CreateConstructorSymbol(\n attributes: default, Accessibility.Public, modifiers: default,\n className, parameters, assignmentStatements);\n\n return constructor;\n }\n\n private class MyCodeAction : CodeAction.DocumentChangeAction\n {\n public MyCodeAction(string title, Func> createChangedDocument)\n : base(title, createChangedDocument, title)\n {\n }\n }\n }\n}\n"},"label":{"kind":"number","value":-1,"string":"-1"}}},{"rowIdx":629,"cells":{"repo_name":{"kind":"string","value":"dotnet/roslyn"},"pr_number":{"kind":"number","value":56433,"string":"56,433"},"pr_title":{"kind":"string","value":"Only allow Contract.ThrowIfNull() to be called on nullable types"},"pr_description":{"kind":"string","value":"We had some places we were calling it on bools."},"author":{"kind":"string","value":"jasonmalinowski"},"date_created":{"kind":"timestamp","value":"2021-09-16T01:20:43Z","string":"2021-09-16T01:20:43Z"},"date_merged":{"kind":"timestamp","value":"2021-09-16T18:44:11Z","string":"2021-09-16T18:44:11Z"},"previous_commit":{"kind":"string","value":"736fc1b5e6e2847689c0154b3e5f23ea99dd56af"},"pr_commit":{"kind":"string","value":"6d0f4e3f972ceb561b04574e7f957a4ff458e272"},"query":{"kind":"string","value":"Only allow Contract.ThrowIfNull() to be called on nullable types. We had some places we were calling it on bools."},"filepath":{"kind":"string","value":"./src/VisualStudio/Core/Def/Implementation/Preview/ReferenceChange.AnalyzerReferenceChange.cs"},"before_content":{"kind":"string","value":"// Licensed to the .NET Foundation under one or more agreements.\n// The .NET Foundation licenses this file to you under the MIT license.\n// See the LICENSE file in the project root for more information.\n\n#nullable disable\n\nusing Microsoft.CodeAnalysis;\nusing Microsoft.CodeAnalysis.Diagnostics;\n\nnamespace Microsoft.VisualStudio.LanguageServices.Implementation.Preview\n{\n internal abstract partial class ReferenceChange : AbstractChange\n {\n private sealed class AnalyzerReferenceChange : ReferenceChange\n {\n private readonly AnalyzerReference _reference;\n\n public AnalyzerReferenceChange(AnalyzerReference reference, ProjectId projectId, string projectName, bool isAdded, PreviewEngine engine)\n : base(projectId, projectName, isAdded, engine)\n {\n _reference = reference;\n }\n\n internal override Solution AddToSolution(Solution solution)\n => solution.AddAnalyzerReference(this.ProjectId, _reference);\n\n internal override Solution RemoveFromSolution(Solution solution)\n => solution.RemoveAnalyzerReference(this.ProjectId, _reference);\n\n protected override string GetDisplayText()\n {\n var display = _reference.Display ?? ServicesVSResources.Unknown1;\n return string.Format(ServicesVSResources.Analyzer_reference_to_0_in_project_1, display, this.ProjectName);\n }\n }\n }\n}\n"},"after_content":{"kind":"string","value":"// Licensed to the .NET Foundation under one or more agreements.\n// The .NET Foundation licenses this file to you under the MIT license.\n// See the LICENSE file in the project root for more information.\n\n#nullable disable\n\nusing Microsoft.CodeAnalysis;\nusing Microsoft.CodeAnalysis.Diagnostics;\n\nnamespace Microsoft.VisualStudio.LanguageServices.Implementation.Preview\n{\n internal abstract partial class ReferenceChange : AbstractChange\n {\n private sealed class AnalyzerReferenceChange : ReferenceChange\n {\n private readonly AnalyzerReference _reference;\n\n public AnalyzerReferenceChange(AnalyzerReference reference, ProjectId projectId, string projectName, bool isAdded, PreviewEngine engine)\n : base(projectId, projectName, isAdded, engine)\n {\n _reference = reference;\n }\n\n internal override Solution AddToSolution(Solution solution)\n => solution.AddAnalyzerReference(this.ProjectId, _reference);\n\n internal override Solution RemoveFromSolution(Solution solution)\n => solution.RemoveAnalyzerReference(this.ProjectId, _reference);\n\n protected override string GetDisplayText()\n {\n var display = _reference.Display ?? ServicesVSResources.Unknown1;\n return string.Format(ServicesVSResources.Analyzer_reference_to_0_in_project_1, display, this.ProjectName);\n }\n }\n }\n}\n"},"label":{"kind":"number","value":-1,"string":"-1"}}},{"rowIdx":630,"cells":{"repo_name":{"kind":"string","value":"dotnet/roslyn"},"pr_number":{"kind":"number","value":56433,"string":"56,433"},"pr_title":{"kind":"string","value":"Only allow Contract.ThrowIfNull() to be called on nullable types"},"pr_description":{"kind":"string","value":"We had some places we were calling it on bools."},"author":{"kind":"string","value":"jasonmalinowski"},"date_created":{"kind":"timestamp","value":"2021-09-16T01:20:43Z","string":"2021-09-16T01:20:43Z"},"date_merged":{"kind":"timestamp","value":"2021-09-16T18:44:11Z","string":"2021-09-16T18:44:11Z"},"previous_commit":{"kind":"string","value":"736fc1b5e6e2847689c0154b3e5f23ea99dd56af"},"pr_commit":{"kind":"string","value":"6d0f4e3f972ceb561b04574e7f957a4ff458e272"},"query":{"kind":"string","value":"Only allow Contract.ThrowIfNull() to be called on nullable types. We had some places we were calling it on bools."},"filepath":{"kind":"string","value":"./src/Workspaces/Core/Portable/CodeCleanup/Providers/ICodeCleanupProvider.cs"},"before_content":{"kind":"string","value":"// Licensed to the .NET Foundation under one or more agreements.\n// The .NET Foundation licenses this file to you under the MIT license.\n// See the LICENSE file in the project root for more information.\n\nusing System.Collections.Immutable;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing Microsoft.CodeAnalysis.Text;\n\nnamespace Microsoft.CodeAnalysis.CodeCleanup.Providers\n{\n /// \n /// A code cleaner that requires semantic information to do its job.\n /// \n internal interface ICodeCleanupProvider\n {\n /// \n /// Returns the name of this provider.\n /// \n string Name { get; }\n\n /// \n /// This should apply its code clean up logic to the spans of the document.\n /// \n Task CleanupAsync(Document document, ImmutableArray spans, CancellationToken cancellationToken = default);\n\n /// \n /// This will run all provided code cleaners in an order that is given to the method.\n /// \n /// This will do cleanups that don't require any semantic information\n /// \n Task CleanupAsync(SyntaxNode root, ImmutableArray spans, Workspace workspace, CancellationToken cancellationToken = default);\n }\n}\n"},"after_content":{"kind":"string","value":"// Licensed to the .NET Foundation under one or more agreements.\n// The .NET Foundation licenses this file to you under the MIT license.\n// See the LICENSE file in the project root for more information.\n\nusing System.Collections.Immutable;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing Microsoft.CodeAnalysis.Text;\n\nnamespace Microsoft.CodeAnalysis.CodeCleanup.Providers\n{\n /// \n /// A code cleaner that requires semantic information to do its job.\n /// \n internal interface ICodeCleanupProvider\n {\n /// \n /// Returns the name of this provider.\n /// \n string Name { get; }\n\n /// \n /// This should apply its code clean up logic to the spans of the document.\n /// \n Task CleanupAsync(Document document, ImmutableArray spans, CancellationToken cancellationToken = default);\n\n /// \n /// This will run all provided code cleaners in an order that is given to the method.\n /// \n /// This will do cleanups that don't require any semantic information\n /// \n Task CleanupAsync(SyntaxNode root, ImmutableArray spans, Workspace workspace, CancellationToken cancellationToken = default);\n }\n}\n"},"label":{"kind":"number","value":-1,"string":"-1"}}},{"rowIdx":631,"cells":{"repo_name":{"kind":"string","value":"dotnet/roslyn"},"pr_number":{"kind":"number","value":56433,"string":"56,433"},"pr_title":{"kind":"string","value":"Only allow Contract.ThrowIfNull() to be called on nullable types"},"pr_description":{"kind":"string","value":"We had some places we were calling it on bools."},"author":{"kind":"string","value":"jasonmalinowski"},"date_created":{"kind":"timestamp","value":"2021-09-16T01:20:43Z","string":"2021-09-16T01:20:43Z"},"date_merged":{"kind":"timestamp","value":"2021-09-16T18:44:11Z","string":"2021-09-16T18:44:11Z"},"previous_commit":{"kind":"string","value":"736fc1b5e6e2847689c0154b3e5f23ea99dd56af"},"pr_commit":{"kind":"string","value":"6d0f4e3f972ceb561b04574e7f957a4ff458e272"},"query":{"kind":"string","value":"Only allow Contract.ThrowIfNull() to be called on nullable types. We had some places we were calling it on bools."},"filepath":{"kind":"string","value":"./src/Compilers/Test/Resources/Core/SymbolsTests/netModule/CrossRefModule2.netmodule"},"before_content":{"kind":"string","value":"MZ\u0000\u0003\u0000\u0000\u0000\u0004\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000@\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u000e\u001f\u000e\u0000\t!\u0001L!This program cannot be run in DOS mode.\n\n$\u0000\u0000\u0000\u0000\u0000\u0000\u0000PE\u0000\u0000L\u0001\u0002\u00007P\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0002\u0001\u000b\u0001\u000b\u0000\u0000\u0004\u0000\u0000\u0000\u0002\u0000\u0000\u0000\u0000\u0000\u0000\u001e\"\u0000\u0000\u0000 \u0000\u0000\u0000@\u0000\u0000\u0000\u0000@\u0000\u0000 \u0000\u0000\u0000\u0002\u0000\u0000\u0004\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0004\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000`\u0000\u0000\u0000\u0002\u0000\u0000\u0000\u0000\u0000\u0000\u0002\u0000@\u0000\u0000\u0010\u0000\u0000\u0010\u0000\u0000\u0000\u0000\u0010\u0000\u0000\u0010\u0000\u0000\u0000\u0000\u0000\u0000\u0010\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000!\u0000\u0000O\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000@\u0000\u0000\f\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000 \u0000\u0000\b\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\b \u0000\u0000H\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000.text\u0000\u0000\u0000$\u0002\u0000\u0000\u0000 \u0000\u0000\u0000\u0004\u0000\u0000\u0000\u0002\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000 \u0000\u0000`.reloc\u0000\u0000\f\u0000\u0000\u0000\u0000@\u0000\u0000\u0000\u0002\u0000\u0000\u0000\u0006\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000@\u0000\u0000B\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\"\u0000\u0000\u0000\u0000\u0000\u0000H\u0000\u0000\u0000\u0002\u0000\u0005\u0000X \u0000\u0000t\u0001\u0000\u0000\u0001\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u001e\u0002(\u0001\u0000\u0000\n*BSJB\u0001\u0000\u0001\u0000\u0000\u0000\u0000\u0000\f\u0000\u0000\u0000v4.0.30319\u0000\u0000\u0000\u0000\u0005\u0000l\u0000\u0000\u0000\u0000\u0000\u0000#~\u0000\u0000\u0000\u0000\u0000T\u0000\u0000\u0000#Strings\u0000\u0000\u0000\u0000L\u0001\u0000\u0000\b\u0000\u0000\u0000#US\u0000T\u0001\u0000\u0000\u0010\u0000\u0000\u0000#GUID\u0000\u0000\u0000d\u0001\u0000\u0000\u0010\u0000\u0000\u0000#Blob\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0002\u0000\u0000\u0001G\u0004\u0000\u0004\b\u0000\u0000\u0000\u0000%3\u0000\u0016\u0000\u0000\u0001\u0000\u0000\u0000\u0001\u0000\u0000\u0000\u0002\u0000\u0000\u0000\u0001\u0000\u0000\u0000\u0001\u0000\u0000\u0000\u0001\u0000\u0000\u0000\u0001\u0000\u0000\u0000\u0000\u00009\u0000\u0001\u0000\u0000\u0000\u0000\u0000\u0005\u00000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0001\u0000\u0000\u0000\u0000\u0000\u0001\u0000\u0001\u0000\u0001\u0000\u0000\u0000\u0013\u0000\u0000\u0000\u0005\u0000\u0001\u0000\u0001\u0000P \u0000\u0000\u0000\u0000\u0006\u00183\u0000\n\u0000\u0001\u0000\t\u00003\u0000\n\u0000\u0016\u0000\u0004\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0001\u0000\n\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000mscorlib\u0000M2\u0000CrossRefModule1.netmodule\u0000M1\u0000.ctor\u0000CrossRefModule2.netmodule\u0000\u0000\u0000\u0003 \u0000\u0000\u0000\u0000\u0000\u0017\u000bG@LQ>\u001e)\u0000\bz\\V\u00194\u0003 \u0000\u0001\u0000\u0000!\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u000e\"\u0000\u0000\u0000 \u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\"\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000_CorExeMain\u0000mscoree.dll\u0000\u0000\u0000\u0000\u0000%\u0000 @\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000 \u0000\u0000\f\u0000\u0000\u0000 2\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000"},"after_content":{"kind":"string","value":"MZ\u0000\u0003\u0000\u0000\u0000\u0004\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000@\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u000e\u001f\u000e\u0000\t!\u0001L!This program cannot be run in DOS mode.\n\n$\u0000\u0000\u0000\u0000\u0000\u0000\u0000PE\u0000\u0000L\u0001\u0002\u00007P\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0002\u0001\u000b\u0001\u000b\u0000\u0000\u0004\u0000\u0000\u0000\u0002\u0000\u0000\u0000\u0000\u0000\u0000\u001e\"\u0000\u0000\u0000 \u0000\u0000\u0000@\u0000\u0000\u0000\u0000@\u0000\u0000 \u0000\u0000\u0000\u0002\u0000\u0000\u0004\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0004\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000`\u0000\u0000\u0000\u0002\u0000\u0000\u0000\u0000\u0000\u0000\u0002\u0000@\u0000\u0000\u0010\u0000\u0000\u0010\u0000\u0000\u0000\u0000\u0010\u0000\u0000\u0010\u0000\u0000\u0000\u0000\u0000\u0000\u0010\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000!\u0000\u0000O\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000@\u0000\u0000\f\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000 \u0000\u0000\b\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\b \u0000\u0000H\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000.text\u0000\u0000\u0000$\u0002\u0000\u0000\u0000 \u0000\u0000\u0000\u0004\u0000\u0000\u0000\u0002\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000 \u0000\u0000`.reloc\u0000\u0000\f\u0000\u0000\u0000\u0000@\u0000\u0000\u0000\u0002\u0000\u0000\u0000\u0006\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000@\u0000\u0000B\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\"\u0000\u0000\u0000\u0000\u0000\u0000H\u0000\u0000\u0000\u0002\u0000\u0005\u0000X \u0000\u0000t\u0001\u0000\u0000\u0001\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u001e\u0002(\u0001\u0000\u0000\n*BSJB\u0001\u0000\u0001\u0000\u0000\u0000\u0000\u0000\f\u0000\u0000\u0000v4.0.30319\u0000\u0000\u0000\u0000\u0005\u0000l\u0000\u0000\u0000\u0000\u0000\u0000#~\u0000\u0000\u0000\u0000\u0000T\u0000\u0000\u0000#Strings\u0000\u0000\u0000\u0000L\u0001\u0000\u0000\b\u0000\u0000\u0000#US\u0000T\u0001\u0000\u0000\u0010\u0000\u0000\u0000#GUID\u0000\u0000\u0000d\u0001\u0000\u0000\u0010\u0000\u0000\u0000#Blob\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0002\u0000\u0000\u0001G\u0004\u0000\u0004\b\u0000\u0000\u0000\u0000%3\u0000\u0016\u0000\u0000\u0001\u0000\u0000\u0000\u0001\u0000\u0000\u0000\u0002\u0000\u0000\u0000\u0001\u0000\u0000\u0000\u0001\u0000\u0000\u0000\u0001\u0000\u0000\u0000\u0001\u0000\u0000\u0000\u0000\u00009\u0000\u0001\u0000\u0000\u0000\u0000\u0000\u0005\u00000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0001\u0000\u0000\u0000\u0000\u0000\u0001\u0000\u0001\u0000\u0001\u0000\u0000\u0000\u0013\u0000\u0000\u0000\u0005\u0000\u0001\u0000\u0001\u0000P \u0000\u0000\u0000\u0000\u0006\u00183\u0000\n\u0000\u0001\u0000\t\u00003\u0000\n\u0000\u0016\u0000\u0004\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0001\u0000\n\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000mscorlib\u0000M2\u0000CrossRefModule1.netmodule\u0000M1\u0000.ctor\u0000CrossRefModule2.netmodule\u0000\u0000\u0000\u0003 \u0000\u0000\u0000\u0000\u0000\u0017\u000bG@LQ>\u001e)\u0000\bz\\V\u00194\u0003 \u0000\u0001\u0000\u0000!\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u000e\"\u0000\u0000\u0000 \u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\"\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000_CorExeMain\u0000mscoree.dll\u0000\u0000\u0000\u0000\u0000%\u0000 @\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000 \u0000\u0000\f\u0000\u0000\u0000 2\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000"},"label":{"kind":"number","value":-1,"string":"-1"}}},{"rowIdx":632,"cells":{"repo_name":{"kind":"string","value":"dotnet/roslyn"},"pr_number":{"kind":"number","value":56433,"string":"56,433"},"pr_title":{"kind":"string","value":"Only allow Contract.ThrowIfNull() to be called on nullable types"},"pr_description":{"kind":"string","value":"We had some places we were calling it on bools."},"author":{"kind":"string","value":"jasonmalinowski"},"date_created":{"kind":"timestamp","value":"2021-09-16T01:20:43Z","string":"2021-09-16T01:20:43Z"},"date_merged":{"kind":"timestamp","value":"2021-09-16T18:44:11Z","string":"2021-09-16T18:44:11Z"},"previous_commit":{"kind":"string","value":"736fc1b5e6e2847689c0154b3e5f23ea99dd56af"},"pr_commit":{"kind":"string","value":"6d0f4e3f972ceb561b04574e7f957a4ff458e272"},"query":{"kind":"string","value":"Only allow Contract.ThrowIfNull() to be called on nullable types. We had some places we were calling it on bools."},"filepath":{"kind":"string","value":"./src/Compilers/Core/Portable/DiagnosticAnalyzer/DefaultAnalyzerAssemblyLoader.Desktop.cs"},"before_content":{"kind":"string","value":"// Licensed to the .NET Foundation under one or more agreements.\n// The .NET Foundation licenses this file to you under the MIT license.\n// See the LICENSE file in the project root for more information.\n\n#nullable disable\n\n#if !NETCOREAPP\n\nusing System;\nusing System.Reflection;\nusing System.Threading;\n\nnamespace Microsoft.CodeAnalysis\n{\n /// \n /// Loads analyzer assemblies from their original locations in the file system.\n /// Assemblies will only be loaded from the locations specified when the loader\n /// is instantiated.\n /// \n /// \n /// This type is meant to be used in scenarios where it is OK for the analyzer\n /// assemblies to be locked on disk for the lifetime of the host; for example,\n /// csc.exe and vbc.exe. In scenarios where support for updating or deleting\n /// the analyzer on disk is required a different loader should be used.\n /// \n internal class DefaultAnalyzerAssemblyLoader : AnalyzerAssemblyLoader\n {\n private int _hookedAssemblyResolve;\n\n protected override Assembly LoadFromPathImpl(string fullPath)\n {\n if (Interlocked.CompareExchange(ref _hookedAssemblyResolve, 0, 1) == 0)\n {\n AppDomain.CurrentDomain.AssemblyResolve += CurrentDomain_AssemblyResolve;\n }\n\n var pathToLoad = GetPathToLoad(fullPath);\n return Assembly.LoadFrom(pathToLoad);\n }\n\n private Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args)\n {\n try\n {\n return Load(AppDomain.CurrentDomain.ApplyPolicy(args.Name));\n }\n catch\n {\n return null;\n }\n }\n }\n}\n\n#endif\n"},"after_content":{"kind":"string","value":"// Licensed to the .NET Foundation under one or more agreements.\n// The .NET Foundation licenses this file to you under the MIT license.\n// See the LICENSE file in the project root for more information.\n\n#nullable disable\n\n#if !NETCOREAPP\n\nusing System;\nusing System.Reflection;\nusing System.Threading;\n\nnamespace Microsoft.CodeAnalysis\n{\n /// \n /// Loads analyzer assemblies from their original locations in the file system.\n /// Assemblies will only be loaded from the locations specified when the loader\n /// is instantiated.\n /// \n /// \n /// This type is meant to be used in scenarios where it is OK for the analyzer\n /// assemblies to be locked on disk for the lifetime of the host; for example,\n /// csc.exe and vbc.exe. In scenarios where support for updating or deleting\n /// the analyzer on disk is required a different loader should be used.\n /// \n internal class DefaultAnalyzerAssemblyLoader : AnalyzerAssemblyLoader\n {\n private int _hookedAssemblyResolve;\n\n protected override Assembly LoadFromPathImpl(string fullPath)\n {\n if (Interlocked.CompareExchange(ref _hookedAssemblyResolve, 0, 1) == 0)\n {\n AppDomain.CurrentDomain.AssemblyResolve += CurrentDomain_AssemblyResolve;\n }\n\n var pathToLoad = GetPathToLoad(fullPath);\n return Assembly.LoadFrom(pathToLoad);\n }\n\n private Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args)\n {\n try\n {\n return Load(AppDomain.CurrentDomain.ApplyPolicy(args.Name));\n }\n catch\n {\n return null;\n }\n }\n }\n}\n\n#endif\n"},"label":{"kind":"number","value":-1,"string":"-1"}}},{"rowIdx":633,"cells":{"repo_name":{"kind":"string","value":"dotnet/roslyn"},"pr_number":{"kind":"number","value":56433,"string":"56,433"},"pr_title":{"kind":"string","value":"Only allow Contract.ThrowIfNull() to be called on nullable types"},"pr_description":{"kind":"string","value":"We had some places we were calling it on bools."},"author":{"kind":"string","value":"jasonmalinowski"},"date_created":{"kind":"timestamp","value":"2021-09-16T01:20:43Z","string":"2021-09-16T01:20:43Z"},"date_merged":{"kind":"timestamp","value":"2021-09-16T18:44:11Z","string":"2021-09-16T18:44:11Z"},"previous_commit":{"kind":"string","value":"736fc1b5e6e2847689c0154b3e5f23ea99dd56af"},"pr_commit":{"kind":"string","value":"6d0f4e3f972ceb561b04574e7f957a4ff458e272"},"query":{"kind":"string","value":"Only allow Contract.ThrowIfNull() to be called on nullable types. We had some places we were calling it on bools."},"filepath":{"kind":"string","value":"./src/Compilers/VisualBasic/Test/Semantic/Semantics/PrintResultTestSource.vb"},"before_content":{"kind":"string","value":"' Licensed to the .NET Foundation under one or more agreements.\n' The .NET Foundation licenses this file to you under the MIT license.\n' See the LICENSE file in the project root for more information.\n\nImports System\nImports System.Globalization\n\nModule PrintHelper\n\n Function GetCultureInvariantString(val As Object) As String\n If val Is Nothing Then\n Return Nothing\n End If\n\n Dim vType = val.GetType()\n Dim valStr = val.ToString()\n If vType Is GetType(DateTime) Then\n valStr = DirectCast(val, DateTime).ToString(\"M/d/yyyy h:mm:ss tt\", CultureInfo.InvariantCulture)\n ElseIf vType Is GetType(Single) Then\n valStr = DirectCast(val, Single).ToString(CultureInfo.InvariantCulture)\n ElseIf vType Is GetType(Double) Then\n valStr = DirectCast(val, Double).ToString(CultureInfo.InvariantCulture)\n ElseIf vType Is GetType(Decimal) Then\n valStr = DirectCast(val, Decimal).ToString(CultureInfo.InvariantCulture)\n End If\n\n Return valStr\n End Function\n\n Sub PrintResult(val As Boolean)\n Console.WriteLine(\"Boolean: {0}\", val)\n End Sub\n Sub PrintResult(val As SByte)\n Console.WriteLine(\"SByte: {0}\", val)\n End Sub\n Sub PrintResult(val As Byte)\n Console.WriteLine(\"Byte: {0}\", val)\n End Sub\n Sub PrintResult(val As Short)\n Console.WriteLine(\"Short: {0}\", val)\n End Sub\n Sub PrintResult(val As UShort)\n Console.WriteLine(\"UShort: {0}\", val)\n End Sub\n Sub PrintResult(val As Integer)\n Console.WriteLine(\"Integer: {0}\", val)\n End Sub\n Sub PrintResult(val As UInteger)\n Console.WriteLine(\"UInteger: {0}\", val)\n End Sub\n Sub PrintResult(val As Long)\n Console.WriteLine(\"Long: {0}\", val)\n End Sub\n Sub PrintResult(val As ULong)\n Console.WriteLine(\"ULong: {0}\", val)\n End Sub\n Sub PrintResult(val As Decimal)\n Console.WriteLine(\"Decimal: {0}\", GetCultureInvariantString(val))\n End Sub\n Sub PrintResult(val As Single)\n Console.WriteLine(\"Single: {0}\", GetCultureInvariantString(val))\n End Sub\n Sub PrintResult(val As Double)\n Console.WriteLine(\"Double: {0}\", GetCultureInvariantString(val))\n End Sub\n Sub PrintResult(val As Date)\n Console.WriteLine(\"Date: {0}\", GetCultureInvariantString(val))\n End Sub\n Sub PrintResult(val As Char)\n Console.WriteLine(\"Char: [{0}]\", val)\n End Sub\n Sub PrintResult(val As Char())\n Console.WriteLine(\"Char(): {0}\", New String(val))\n End Sub\n Sub PrintResult(val As String)\n Console.WriteLine(\"String: [{0}]\", val)\n End Sub\n Sub PrintResult(val As Object)\n Console.WriteLine(\"Object: [{0}]\", val)\n End Sub\n Sub PrintResult(val As Guid)\n Console.WriteLine(\"Guid: {0}\", val)\n End Sub\n Sub PrintResult(val As ValueType)\n Dim pval = GetCultureInvariantString(val)\n Console.WriteLine(\"ValueType: [{0}]\", pval)\n End Sub\n Sub PrintResult(val As IComparable)\n Console.WriteLine(\"IComparable: [{0}]\", val)\n End Sub\n\n ' =================================================================\n\n Sub PrintResult(expr As String, val As Boolean)\n System.Console.WriteLine(\"[{1}] Boolean: {0}\", val, expr)\n End Sub\n Sub PrintResult(expr As String, val As SByte)\n System.Console.WriteLine(\"[{1}] SByte: {0}\", val, expr)\n End Sub\n Sub PrintResult(expr As String, val As Byte)\n System.Console.WriteLine(\"[{1}] Byte: {0}\", val, expr)\n End Sub\n Sub PrintResult(expr As String, val As Short)\n System.Console.WriteLine(\"[{1}] Short: {0}\", val, expr)\n End Sub\n Sub PrintResult(expr As String, val As UShort)\n System.Console.WriteLine(\"[{1}] UShort: {0}\", val, expr)\n End Sub\n Sub PrintResult(expr As String, val As Integer)\n System.Console.WriteLine(\"[{1}] Integer: {0}\", val, expr)\n End Sub\n Sub PrintResult(expr As String, val As UInteger)\n System.Console.WriteLine(\"[{1}] UInteger: {0}\", val, expr)\n End Sub\n Sub PrintResult(expr As String, val As Long)\n System.Console.WriteLine(\"[{1}] Long: {0}\", val, expr)\n End Sub\n Sub PrintResult(expr As String, val As ULong)\n System.Console.WriteLine(\"[{1}] ULong: {0}\", val, expr)\n End Sub\n Sub PrintResult(expr As String, val As Decimal)\n System.Console.WriteLine(\"[{1}] Decimal: {0}\", GetCultureInvariantString(val), expr)\n End Sub\n Sub PrintResult(expr As String, val As Single)\n System.Console.WriteLine(\"[{1}] Single: {0}\", GetCultureInvariantString(val), expr)\n End Sub\n Sub PrintResult(expr As String, val As Double)\n System.Console.WriteLine(\"[{1}] Double: {0}\", GetCultureInvariantString(val), expr)\n End Sub\n Sub PrintResult(expr As String, val As Date)\n System.Console.WriteLine(\"[{1}] Date: {0}\", GetCultureInvariantString(val), expr)\n End Sub\n Sub PrintResult(expr As String, val As Char)\n System.Console.WriteLine(\"[{1}] Char: {0}\", val, expr)\n End Sub\n Sub PrintResult(expr As String, val As String)\n System.Console.WriteLine(\"[{0}] String: [{1}]\", expr, val)\n End Sub\n Sub PrintResult(expr As String, val As Object)\n System.Console.WriteLine(\"[{1}] Object: {0}\", GetCultureInvariantString(val), expr)\n End Sub\n Sub PrintResult(expr As String, val As System.TypeCode)\n System.Console.WriteLine(\"[{1}] TypeCode: {0}\", val, expr)\n End Sub\n\nEnd Module\n"},"after_content":{"kind":"string","value":"' Licensed to the .NET Foundation under one or more agreements.\n' The .NET Foundation licenses this file to you under the MIT license.\n' See the LICENSE file in the project root for more information.\n\nImports System\nImports System.Globalization\n\nModule PrintHelper\n\n Function GetCultureInvariantString(val As Object) As String\n If val Is Nothing Then\n Return Nothing\n End If\n\n Dim vType = val.GetType()\n Dim valStr = val.ToString()\n If vType Is GetType(DateTime) Then\n valStr = DirectCast(val, DateTime).ToString(\"M/d/yyyy h:mm:ss tt\", CultureInfo.InvariantCulture)\n ElseIf vType Is GetType(Single) Then\n valStr = DirectCast(val, Single).ToString(CultureInfo.InvariantCulture)\n ElseIf vType Is GetType(Double) Then\n valStr = DirectCast(val, Double).ToString(CultureInfo.InvariantCulture)\n ElseIf vType Is GetType(Decimal) Then\n valStr = DirectCast(val, Decimal).ToString(CultureInfo.InvariantCulture)\n End If\n\n Return valStr\n End Function\n\n Sub PrintResult(val As Boolean)\n Console.WriteLine(\"Boolean: {0}\", val)\n End Sub\n Sub PrintResult(val As SByte)\n Console.WriteLine(\"SByte: {0}\", val)\n End Sub\n Sub PrintResult(val As Byte)\n Console.WriteLine(\"Byte: {0}\", val)\n End Sub\n Sub PrintResult(val As Short)\n Console.WriteLine(\"Short: {0}\", val)\n End Sub\n Sub PrintResult(val As UShort)\n Console.WriteLine(\"UShort: {0}\", val)\n End Sub\n Sub PrintResult(val As Integer)\n Console.WriteLine(\"Integer: {0}\", val)\n End Sub\n Sub PrintResult(val As UInteger)\n Console.WriteLine(\"UInteger: {0}\", val)\n End Sub\n Sub PrintResult(val As Long)\n Console.WriteLine(\"Long: {0}\", val)\n End Sub\n Sub PrintResult(val As ULong)\n Console.WriteLine(\"ULong: {0}\", val)\n End Sub\n Sub PrintResult(val As Decimal)\n Console.WriteLine(\"Decimal: {0}\", GetCultureInvariantString(val))\n End Sub\n Sub PrintResult(val As Single)\n Console.WriteLine(\"Single: {0}\", GetCultureInvariantString(val))\n End Sub\n Sub PrintResult(val As Double)\n Console.WriteLine(\"Double: {0}\", GetCultureInvariantString(val))\n End Sub\n Sub PrintResult(val As Date)\n Console.WriteLine(\"Date: {0}\", GetCultureInvariantString(val))\n End Sub\n Sub PrintResult(val As Char)\n Console.WriteLine(\"Char: [{0}]\", val)\n End Sub\n Sub PrintResult(val As Char())\n Console.WriteLine(\"Char(): {0}\", New String(val))\n End Sub\n Sub PrintResult(val As String)\n Console.WriteLine(\"String: [{0}]\", val)\n End Sub\n Sub PrintResult(val As Object)\n Console.WriteLine(\"Object: [{0}]\", val)\n End Sub\n Sub PrintResult(val As Guid)\n Console.WriteLine(\"Guid: {0}\", val)\n End Sub\n Sub PrintResult(val As ValueType)\n Dim pval = GetCultureInvariantString(val)\n Console.WriteLine(\"ValueType: [{0}]\", pval)\n End Sub\n Sub PrintResult(val As IComparable)\n Console.WriteLine(\"IComparable: [{0}]\", val)\n End Sub\n\n ' =================================================================\n\n Sub PrintResult(expr As String, val As Boolean)\n System.Console.WriteLine(\"[{1}] Boolean: {0}\", val, expr)\n End Sub\n Sub PrintResult(expr As String, val As SByte)\n System.Console.WriteLine(\"[{1}] SByte: {0}\", val, expr)\n End Sub\n Sub PrintResult(expr As String, val As Byte)\n System.Console.WriteLine(\"[{1}] Byte: {0}\", val, expr)\n End Sub\n Sub PrintResult(expr As String, val As Short)\n System.Console.WriteLine(\"[{1}] Short: {0}\", val, expr)\n End Sub\n Sub PrintResult(expr As String, val As UShort)\n System.Console.WriteLine(\"[{1}] UShort: {0}\", val, expr)\n End Sub\n Sub PrintResult(expr As String, val As Integer)\n System.Console.WriteLine(\"[{1}] Integer: {0}\", val, expr)\n End Sub\n Sub PrintResult(expr As String, val As UInteger)\n System.Console.WriteLine(\"[{1}] UInteger: {0}\", val, expr)\n End Sub\n Sub PrintResult(expr As String, val As Long)\n System.Console.WriteLine(\"[{1}] Long: {0}\", val, expr)\n End Sub\n Sub PrintResult(expr As String, val As ULong)\n System.Console.WriteLine(\"[{1}] ULong: {0}\", val, expr)\n End Sub\n Sub PrintResult(expr As String, val As Decimal)\n System.Console.WriteLine(\"[{1}] Decimal: {0}\", GetCultureInvariantString(val), expr)\n End Sub\n Sub PrintResult(expr As String, val As Single)\n System.Console.WriteLine(\"[{1}] Single: {0}\", GetCultureInvariantString(val), expr)\n End Sub\n Sub PrintResult(expr As String, val As Double)\n System.Console.WriteLine(\"[{1}] Double: {0}\", GetCultureInvariantString(val), expr)\n End Sub\n Sub PrintResult(expr As String, val As Date)\n System.Console.WriteLine(\"[{1}] Date: {0}\", GetCultureInvariantString(val), expr)\n End Sub\n Sub PrintResult(expr As String, val As Char)\n System.Console.WriteLine(\"[{1}] Char: {0}\", val, expr)\n End Sub\n Sub PrintResult(expr As String, val As String)\n System.Console.WriteLine(\"[{0}] String: [{1}]\", expr, val)\n End Sub\n Sub PrintResult(expr As String, val As Object)\n System.Console.WriteLine(\"[{1}] Object: {0}\", GetCultureInvariantString(val), expr)\n End Sub\n Sub PrintResult(expr As String, val As System.TypeCode)\n System.Console.WriteLine(\"[{1}] TypeCode: {0}\", val, expr)\n End Sub\n\nEnd Module\n"},"label":{"kind":"number","value":-1,"string":"-1"}}},{"rowIdx":634,"cells":{"repo_name":{"kind":"string","value":"dotnet/roslyn"},"pr_number":{"kind":"number","value":56433,"string":"56,433"},"pr_title":{"kind":"string","value":"Only allow Contract.ThrowIfNull() to be called on nullable types"},"pr_description":{"kind":"string","value":"We had some places we were calling it on bools."},"author":{"kind":"string","value":"jasonmalinowski"},"date_created":{"kind":"timestamp","value":"2021-09-16T01:20:43Z","string":"2021-09-16T01:20:43Z"},"date_merged":{"kind":"timestamp","value":"2021-09-16T18:44:11Z","string":"2021-09-16T18:44:11Z"},"previous_commit":{"kind":"string","value":"736fc1b5e6e2847689c0154b3e5f23ea99dd56af"},"pr_commit":{"kind":"string","value":"6d0f4e3f972ceb561b04574e7f957a4ff458e272"},"query":{"kind":"string","value":"Only allow Contract.ThrowIfNull() to be called on nullable types. We had some places we were calling it on bools."},"filepath":{"kind":"string","value":"./src/Workspaces/MSBuildTest/Resources/ProjectFiles/VisualBasic/VisualBasicProject.vbproj"},"before_content":{"kind":"string","value":"\n\n\n \n Debug\n AnyCPU\n AnyCPU\n \n \n {AC25ECDA-DE94-4FCF-A688-EB3A2BE3670C}\n Library\n VisualBasicProject\n VisualBasicProject\n 512\n Windows\n v4.6\n \n \n true\n full\n true\n true\n bin\\Debug\\\n VisualBasicProject.xml\n $(NoWarn);42016,41999,42017,42018,42019,42032,42036,42020,42021,42022\n true\n snKey.snk\n FURBY\n \n \n pdbonly\n false\n true\n true\n bin\\Release\\\n VisualBasicProject.xml\n $(NoWarn);42016,41999,42017,42018,42019,42032,42036,42020,42021,42022\n \n \n On\n 15\n \n \n Binary\n \n \n Off\n \n \n On\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n True\n Application.myapp\n \n \n \n True\n True\n Resources.resx\n \n \n True\n Settings.settings\n True\n \n \n \n \n \n VbMyResourcesResXFileCodeGenerator\n Resources.Designer.vb\n My.Resources\n Designer\n \n \n \n \n MyApplicationCodeGenerator\n Application.Designer.vb\n \n \n SettingsSingleFileGenerator\n My\n Settings.Designer.vb\n \n \n \n \n {686DD036-86AA-443E-8A10-DDB43266A8C4}\n CSharpProject\n \n \n \n \n"},"after_content":{"kind":"string","value":"\n\n\n \n Debug\n AnyCPU\n AnyCPU\n \n \n {AC25ECDA-DE94-4FCF-A688-EB3A2BE3670C}\n Library\n VisualBasicProject\n VisualBasicProject\n 512\n Windows\n v4.6\n \n \n true\n full\n true\n true\n bin\\Debug\\\n VisualBasicProject.xml\n $(NoWarn);42016,41999,42017,42018,42019,42032,42036,42020,42021,42022\n true\n snKey.snk\n FURBY\n \n \n pdbonly\n false\n true\n true\n bin\\Release\\\n VisualBasicProject.xml\n $(NoWarn);42016,41999,42017,42018,42019,42032,42036,42020,42021,42022\n \n \n On\n 15\n \n \n Binary\n \n \n Off\n \n \n On\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n True\n Application.myapp\n \n \n \n True\n True\n Resources.resx\n \n \n True\n Settings.settings\n True\n \n \n \n \n \n VbMyResourcesResXFileCodeGenerator\n Resources.Designer.vb\n My.Resources\n Designer\n \n \n \n \n MyApplicationCodeGenerator\n Application.Designer.vb\n \n \n SettingsSingleFileGenerator\n My\n Settings.Designer.vb\n \n \n \n \n {686DD036-86AA-443E-8A10-DDB43266A8C4}\n CSharpProject\n \n \n \n \n"},"label":{"kind":"number","value":-1,"string":"-1"}}},{"rowIdx":635,"cells":{"repo_name":{"kind":"string","value":"dotnet/roslyn"},"pr_number":{"kind":"number","value":56433,"string":"56,433"},"pr_title":{"kind":"string","value":"Only allow Contract.ThrowIfNull() to be called on nullable types"},"pr_description":{"kind":"string","value":"We had some places we were calling it on bools."},"author":{"kind":"string","value":"jasonmalinowski"},"date_created":{"kind":"timestamp","value":"2021-09-16T01:20:43Z","string":"2021-09-16T01:20:43Z"},"date_merged":{"kind":"timestamp","value":"2021-09-16T18:44:11Z","string":"2021-09-16T18:44:11Z"},"previous_commit":{"kind":"string","value":"736fc1b5e6e2847689c0154b3e5f23ea99dd56af"},"pr_commit":{"kind":"string","value":"6d0f4e3f972ceb561b04574e7f957a4ff458e272"},"query":{"kind":"string","value":"Only allow Contract.ThrowIfNull() to be called on nullable types. We had some places we were calling it on bools."},"filepath":{"kind":"string","value":"./src/Compilers/Core/Portable/InternalUtilities/RoslynParallel.cs"},"before_content":{"kind":"string","value":"// Licensed to the .NET Foundation under one or more agreements.\n// The .NET Foundation licenses this file to you under the MIT license.\n// See the LICENSE file in the project root for more information.\n\nusing System;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing Microsoft.CodeAnalysis;\n\nnamespace Roslyn.Utilities\n{\n internal static class RoslynParallel\n {\n internal static readonly ParallelOptions DefaultParallelOptions = new ParallelOptions();\n\n /// \n public static ParallelLoopResult For(int fromInclusive, int toExclusive, Action body, CancellationToken cancellationToken)\n {\n var parallelOptions = cancellationToken.CanBeCanceled\n ? new ParallelOptions { CancellationToken = cancellationToken }\n : DefaultParallelOptions;\n\n return Parallel.For(fromInclusive, toExclusive, parallelOptions, errorHandlingBody);\n\n // Local function\n void errorHandlingBody(int i)\n {\n try\n {\n body(i);\n }\n catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken))\n {\n throw ExceptionUtilities.Unreachable;\n }\n catch (OperationCanceledException e) when (cancellationToken.IsCancellationRequested && e.CancellationToken != cancellationToken)\n {\n // Parallel.For checks for a specific cancellation token, so make sure we throw with the\n // correct one.\n cancellationToken.ThrowIfCancellationRequested();\n throw ExceptionUtilities.Unreachable;\n }\n }\n }\n }\n}\n"},"after_content":{"kind":"string","value":"// Licensed to the .NET Foundation under one or more agreements.\n// The .NET Foundation licenses this file to you under the MIT license.\n// See the LICENSE file in the project root for more information.\n\nusing System;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing Microsoft.CodeAnalysis;\n\nnamespace Roslyn.Utilities\n{\n internal static class RoslynParallel\n {\n internal static readonly ParallelOptions DefaultParallelOptions = new ParallelOptions();\n\n /// \n public static ParallelLoopResult For(int fromInclusive, int toExclusive, Action body, CancellationToken cancellationToken)\n {\n var parallelOptions = cancellationToken.CanBeCanceled\n ? new ParallelOptions { CancellationToken = cancellationToken }\n : DefaultParallelOptions;\n\n return Parallel.For(fromInclusive, toExclusive, parallelOptions, errorHandlingBody);\n\n // Local function\n void errorHandlingBody(int i)\n {\n try\n {\n body(i);\n }\n catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken))\n {\n throw ExceptionUtilities.Unreachable;\n }\n catch (OperationCanceledException e) when (cancellationToken.IsCancellationRequested && e.CancellationToken != cancellationToken)\n {\n // Parallel.For checks for a specific cancellation token, so make sure we throw with the\n // correct one.\n cancellationToken.ThrowIfCancellationRequested();\n throw ExceptionUtilities.Unreachable;\n }\n }\n }\n }\n}\n"},"label":{"kind":"number","value":-1,"string":"-1"}}},{"rowIdx":636,"cells":{"repo_name":{"kind":"string","value":"dotnet/roslyn"},"pr_number":{"kind":"number","value":56432,"string":"56,432"},"pr_title":{"kind":"string","value":"When we're loading dependencies, don't require exact versions"},"pr_description":{"kind":"string","value":"When we're loading analyzer dependencies, our current logic was to require the exact version that was requested from the loading assembly. This is problematic in a lot of cases where you would normally have a binding redirect to ensure assemblies load cleanly; by requiring exact versions we'd end up in diamond dependency cases where you couldn't practically produce an analyzer package that would cleanly load.\r\n\r\nWhile doing this change, @RikkiGibson and I noticed several other problems:\r\n\r\n1. There was an errant cache that was left in the .NET Core implementation, which meant that we'd sometimes reuse assemblies even when we were able to load them correctly. This has also been fixed as a prerequisite to the main fix, since otherwise it was difficult to prove that the behavior changes here weren't also going to impact the .NET Core implementation.\r\n2. There were some race conditions in the implementation.\r\n\r\n**REVIEWING COMMIT-AT-A-TIME IS HIGHLY RECOMMENDED**, since those changes are broken out to separate commits.\r\n\r\nFixes #53672\r\nFixes #56216"},"author":{"kind":"string","value":"jasonmalinowski"},"date_created":{"kind":"timestamp","value":"2021-09-16T01:19:09Z","string":"2021-09-16T01:19:09Z"},"date_merged":{"kind":"timestamp","value":"2021-11-30T03:29:47Z","string":"2021-11-30T03:29:47Z"},"previous_commit":{"kind":"string","value":"e302aa0555624495ca1644c8488ddf33c6a65686"},"pr_commit":{"kind":"string","value":"0bdc85394f139a23d8363a47635efa878112a95b"},"query":{"kind":"string","value":"When we're loading dependencies, don't require exact versions. When we're loading analyzer dependencies, our current logic was to require the exact version that was requested from the loading assembly. This is problematic in a lot of cases where you would normally have a binding redirect to ensure assemblies load cleanly; by requiring exact versions we'd end up in diamond dependency cases where you couldn't practically produce an analyzer package that would cleanly load.\r\n\r\nWhile doing this change, @RikkiGibson and I noticed several other problems:\r\n\r\n1. There was an errant cache that was left in the .NET Core implementation, which meant that we'd sometimes reuse assemblies even when we were able to load them correctly. This has also been fixed as a prerequisite to the main fix, since otherwise it was difficult to prove that the behavior changes here weren't also going to impact the .NET Core implementation.\r\n2. There were some race conditions in the implementation.\r\n\r\n**REVIEWING COMMIT-AT-A-TIME IS HIGHLY RECOMMENDED**, since those changes are broken out to separate commits.\r\n\r\nFixes #53672\r\nFixes #56216"},"filepath":{"kind":"string","value":"./src/Compilers/Core/CodeAnalysisTest/DefaultAnalyzerAssemblyLoaderTests.cs"},"before_content":{"kind":"string","value":"// Licensed to the .NET Foundation under one or more agreements.\n// The .NET Foundation licenses this file to you under the MIT license.\n// See the LICENSE file in the project root for more information.\n\nusing System;\nusing System.Collections.Generic;\nusing System.Collections.Immutable;\nusing System.IO;\nusing System.Linq;\nusing System.Reflection;\nusing System.Runtime.InteropServices;\nusing System.Text;\nusing Microsoft.CodeAnalysis.CSharp;\nusing Microsoft.CodeAnalysis.Diagnostics;\nusing Microsoft.CodeAnalysis.PooledObjects;\nusing Microsoft.CodeAnalysis.Test.Utilities;\nusing Roslyn.Test.Utilities;\nusing Roslyn.Utilities;\nusing Xunit;\nusing Xunit.Abstractions;\n\nnamespace Microsoft.CodeAnalysis.UnitTests\n{\n [CollectionDefinition(Name)]\n public class AssemblyLoadTestFixtureCollection : ICollectionFixture\n {\n public const string Name = nameof(AssemblyLoadTestFixtureCollection);\n private AssemblyLoadTestFixtureCollection() { }\n }\n\n [Collection(AssemblyLoadTestFixtureCollection.Name)]\n public sealed class DefaultAnalyzerAssemblyLoaderTests : TestBase\n {\n private static readonly CSharpCompilationOptions s_dllWithMaxWarningLevel = new(OutputKind.DynamicallyLinkedLibrary, warningLevel: CodeAnalysis.Diagnostic.MaxWarningLevel);\n private readonly ITestOutputHelper _output;\n private readonly AssemblyLoadTestFixture _testFixture;\n public DefaultAnalyzerAssemblyLoaderTests(ITestOutputHelper output, AssemblyLoadTestFixture testFixture)\n {\n _output = output;\n _testFixture = testFixture;\n }\n\n [Fact, WorkItem(32226, \"https://github.com/dotnet/roslyn/issues/32226\")]\n public void LoadWithDependency()\n {\n var analyzerDependencyFile = _testFixture.AnalyzerDependency;\n var analyzerMainFile = _testFixture.AnalyzerWithDependency;\n var loader = new DefaultAnalyzerAssemblyLoader();\n loader.AddDependencyLocation(analyzerDependencyFile.Path);\n\n var analyzerMainReference = new AnalyzerFileReference(analyzerMainFile.Path, loader);\n analyzerMainReference.AnalyzerLoadFailed += (_, e) => AssertEx.Fail(e.Exception!.Message);\n var analyzerDependencyReference = new AnalyzerFileReference(analyzerDependencyFile.Path, loader);\n analyzerDependencyReference.AnalyzerLoadFailed += (_, e) => AssertEx.Fail(e.Exception!.Message);\n\n var analyzers = analyzerMainReference.GetAnalyzersForAllLanguages();\n Assert.Equal(1, analyzers.Length);\n Assert.Equal(\"TestAnalyzer\", analyzers[0].ToString());\n\n Assert.Equal(0, analyzerDependencyReference.GetAnalyzersForAllLanguages().Length);\n\n Assert.NotNull(analyzerDependencyReference.GetAssembly());\n }\n\n [Fact]\n public void AddDependencyLocationThrowsOnNull()\n {\n var loader = new DefaultAnalyzerAssemblyLoader();\n\n Assert.Throws(\"fullPath\", () => loader.AddDependencyLocation(null));\n Assert.Throws(\"fullPath\", () => loader.AddDependencyLocation(\"a\"));\n }\n\n [Fact]\n public void ThrowsForMissingFile()\n {\n var path = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName() + \".dll\");\n\n var loader = new DefaultAnalyzerAssemblyLoader();\n\n Assert.ThrowsAny(() => loader.LoadFromPath(path));\n }\n\n [Fact]\n public void BasicLoad()\n {\n var loader = new DefaultAnalyzerAssemblyLoader();\n loader.AddDependencyLocation(_testFixture.Alpha.Path);\n Assembly alpha = loader.LoadFromPath(_testFixture.Alpha.Path);\n\n Assert.NotNull(alpha);\n }\n\n [Fact]\n public void AssemblyLoading()\n {\n StringBuilder sb = new StringBuilder();\n\n var loader = new DefaultAnalyzerAssemblyLoader();\n loader.AddDependencyLocation(_testFixture.Alpha.Path);\n loader.AddDependencyLocation(_testFixture.Beta.Path);\n loader.AddDependencyLocation(_testFixture.Gamma.Path);\n loader.AddDependencyLocation(_testFixture.Delta1.Path);\n\n Assembly alpha = loader.LoadFromPath(_testFixture.Alpha.Path);\n\n var a = alpha.CreateInstance(\"Alpha.A\")!;\n a.GetType().GetMethod(\"Write\")!.Invoke(a, new object[] { sb, \"Test A\" });\n\n Assembly beta = loader.LoadFromPath(_testFixture.Beta.Path);\n\n var b = beta.CreateInstance(\"Beta.B\")!;\n b.GetType().GetMethod(\"Write\")!.Invoke(b, new object[] { sb, \"Test B\" });\n\n var expected = @\"Delta: Gamma: Alpha: Test A\nDelta: Gamma: Beta: Test B\n\";\n\n var actual = sb.ToString();\n\n Assert.Equal(expected, actual);\n }\n\n [ConditionalFact(typeof(CoreClrOnly))]\n public void AssemblyLoading_AssemblyLocationNotAdded()\n {\n var loader = new DefaultAnalyzerAssemblyLoader();\n loader.AddDependencyLocation(_testFixture.Gamma.Path);\n loader.AddDependencyLocation(_testFixture.Delta1.Path);\n Assert.Throws(() => loader.LoadFromPath(_testFixture.Beta.Path));\n }\n\n [ConditionalFact(typeof(CoreClrOnly))]\n public void AssemblyLoading_DependencyLocationNotAdded()\n {\n StringBuilder sb = new StringBuilder();\n var loader = new DefaultAnalyzerAssemblyLoader();\n // We don't pass Alpha's path to AddDependencyLocation here, and therefore expect\n // calling Beta.B.Write to fail.\n loader.AddDependencyLocation(_testFixture.Gamma.Path);\n loader.AddDependencyLocation(_testFixture.Beta.Path);\n Assembly beta = loader.LoadFromPath(_testFixture.Beta.Path);\n\n var b = beta.CreateInstance(\"Beta.B\")!;\n var writeMethod = b.GetType().GetMethod(\"Write\")!;\n var exception = Assert.Throws(\n () => writeMethod.Invoke(b, new object[] { sb, \"Test B\" }));\n Assert.IsAssignableFrom(exception.InnerException);\n\n var actual = sb.ToString();\n Assert.Equal(@\"\", actual);\n }\n\n private static void VerifyAssemblies(IEnumerable assemblies, params (string simpleName, string version, string path)[] expected)\n {\n Assert.Equal(expected, assemblies.Select(assembly => (assembly.GetName().Name!, assembly.GetName().Version!.ToString(), assembly.Location)).Order());\n }\n\n [ConditionalFact(typeof(CoreClrOnly))]\n public void AssemblyLoading_DependencyInDifferentDirectory()\n {\n StringBuilder sb = new StringBuilder();\n var loader = new DefaultAnalyzerAssemblyLoader();\n\n var tempDir = Temp.CreateDirectory();\n\n var deltaFile = tempDir.CreateFile(\"Delta.dll\").CopyContentFrom(_testFixture.Delta1.Path);\n loader.AddDependencyLocation(deltaFile.Path);\n loader.AddDependencyLocation(_testFixture.Gamma.Path);\n Assembly gamma = loader.LoadFromPath(_testFixture.Gamma.Path);\n\n var b = gamma.CreateInstance(\"Gamma.G\")!;\n var writeMethod = b.GetType().GetMethod(\"Write\")!;\n writeMethod.Invoke(b, new object[] { sb, \"Test G\" });\n\n var actual = sb.ToString();\n Assert.Equal(@\"Delta: Gamma: Test G\n\", actual);\n\n#if NETCOREAPP\n var alcs = DefaultAnalyzerAssemblyLoader.TestAccessor.GetOrderedLoadContexts(loader);\n Assert.Equal(1, alcs.Length);\n\n VerifyAssemblies(\n alcs[0].Assemblies,\n (\"Delta\", \"1.0.0.0\", deltaFile.Path),\n (\"Gamma\", \"0.0.0.0\", _testFixture.Gamma.Path)\n );\n#endif\n }\n\n [Fact]\n public void AssemblyLoading_MultipleVersions()\n {\n StringBuilder sb = new StringBuilder();\n\n var loader = new DefaultAnalyzerAssemblyLoader();\n loader.AddDependencyLocation(_testFixture.Gamma.Path);\n loader.AddDependencyLocation(_testFixture.Delta1.Path);\n loader.AddDependencyLocation(_testFixture.Epsilon.Path);\n loader.AddDependencyLocation(_testFixture.Delta2.Path);\n\n Assembly gamma = loader.LoadFromPath(_testFixture.Gamma.Path);\n var g = gamma.CreateInstance(\"Gamma.G\")!;\n g.GetType().GetMethod(\"Write\")!.Invoke(g, new object[] { sb, \"Test G\" });\n\n Assembly epsilon = loader.LoadFromPath(_testFixture.Epsilon.Path);\n var e = epsilon.CreateInstance(\"Epsilon.E\")!;\n e.GetType().GetMethod(\"Write\")!.Invoke(e, new object[] { sb, \"Test E\" });\n\n#if NETCOREAPP\n var alcs = DefaultAnalyzerAssemblyLoader.TestAccessor.GetOrderedLoadContexts(loader);\n Assert.Equal(2, alcs.Length);\n\n VerifyAssemblies(\n alcs[0].Assemblies,\n (\"Delta\", \"1.0.0.0\", _testFixture.Delta1.Path),\n (\"Gamma\", \"0.0.0.0\", _testFixture.Gamma.Path)\n );\n\n VerifyAssemblies(\n alcs[1].Assemblies,\n (\"Delta\", \"2.0.0.0\", _testFixture.Delta2.Path),\n (\"Epsilon\", \"0.0.0.0\", _testFixture.Epsilon.Path));\n#endif\n\n var actual = sb.ToString();\n if (ExecutionConditionUtil.IsCoreClr)\n {\n Assert.Equal(\n@\"Delta: Gamma: Test G\nDelta.2: Epsilon: Test E\n\",\n actual);\n }\n else\n {\n Assert.Equal(\n@\"Delta: Gamma: Test G\nDelta: Epsilon: Test E\n\",\n actual);\n }\n }\n\n [Fact]\n public void AssemblyLoading_MultipleVersions_NoExactMatch()\n {\n StringBuilder sb = new StringBuilder();\n\n var loader = new DefaultAnalyzerAssemblyLoader();\n loader.AddDependencyLocation(_testFixture.Delta1.Path);\n loader.AddDependencyLocation(_testFixture.Epsilon.Path);\n loader.AddDependencyLocation(_testFixture.Delta3.Path);\n\n Assembly epsilon = loader.LoadFromPath(_testFixture.Epsilon.Path);\n var e = epsilon.CreateInstance(\"Epsilon.E\")!;\n e.GetType().GetMethod(\"Write\")!.Invoke(e, new object[] { sb, \"Test E\" });\n\n#if NETCOREAPP\n var alcs = DefaultAnalyzerAssemblyLoader.TestAccessor.GetOrderedLoadContexts(loader);\n Assert.Equal(1, alcs.Length);\n\n VerifyAssemblies(\n alcs[0].Assemblies,\n (\"Delta\", \"3.0.0.0\", _testFixture.Delta3.Path),\n (\"Epsilon\", \"0.0.0.0\", _testFixture.Epsilon.Path));\n#endif\n\n var actual = sb.ToString();\n if (ExecutionConditionUtil.IsCoreClr)\n {\n Assert.Equal(\n@\"Delta.3: Epsilon: Test E\n\",\n actual);\n }\n else\n {\n Assert.Equal(\n@\"Delta: Epsilon: Test E\n\",\n actual);\n }\n }\n\n [Fact]\n public void AssemblyLoading_MultipleVersions_MultipleEqualMatches()\n {\n StringBuilder sb = new StringBuilder();\n\n // Delta2B and Delta2 have the same version, but we prefer Delta2 because it's in the same directory as Epsilon.\n var loader = new DefaultAnalyzerAssemblyLoader();\n loader.AddDependencyLocation(_testFixture.Delta2B.Path);\n loader.AddDependencyLocation(_testFixture.Delta2.Path);\n loader.AddDependencyLocation(_testFixture.Epsilon.Path);\n\n Assembly epsilon = loader.LoadFromPath(_testFixture.Epsilon.Path);\n var e = epsilon.CreateInstance(\"Epsilon.E\")!;\n e.GetType().GetMethod(\"Write\")!.Invoke(e, new object[] { sb, \"Test E\" });\n\n#if NETCOREAPP\n var alcs = DefaultAnalyzerAssemblyLoader.TestAccessor.GetOrderedLoadContexts(loader);\n Assert.Equal(1, alcs.Length);\n\n VerifyAssemblies(\n alcs[0].Assemblies,\n (\"Delta\", \"2.0.0.0\", _testFixture.Delta2.Path),\n (\"Epsilon\", \"0.0.0.0\", _testFixture.Epsilon.Path));\n#endif\n\n var actual = sb.ToString();\n if (ExecutionConditionUtil.IsCoreClr)\n {\n Assert.Equal(\n@\"Delta.2: Epsilon: Test E\n\",\n actual);\n }\n else\n {\n Assert.Equal(\n@\"Delta: Epsilon: Test E\n\",\n actual);\n }\n }\n\n [Fact]\n public void AssemblyLoading_MultipleVersions_ExactAndGreaterMatch()\n {\n StringBuilder sb = new StringBuilder();\n\n var loader = new DefaultAnalyzerAssemblyLoader();\n loader.AddDependencyLocation(_testFixture.Delta2B.Path);\n loader.AddDependencyLocation(_testFixture.Delta3.Path);\n loader.AddDependencyLocation(_testFixture.Epsilon.Path);\n\n Assembly epsilon = loader.LoadFromPath(_testFixture.Epsilon.Path);\n var e = epsilon.CreateInstance(\"Epsilon.E\")!;\n e.GetType().GetMethod(\"Write\")!.Invoke(e, new object[] { sb, \"Test E\" });\n\n#if NETCOREAPP\n var alcs = DefaultAnalyzerAssemblyLoader.TestAccessor.GetOrderedLoadContexts(loader);\n Assert.Equal(1, alcs.Length);\n\n VerifyAssemblies(\n alcs[0].Assemblies,\n (\"Delta\", \"2.0.0.0\", _testFixture.Delta2B.Path),\n (\"Epsilon\", \"0.0.0.0\", _testFixture.Epsilon.Path));\n#endif\n\n var actual = sb.ToString();\n if (ExecutionConditionUtil.IsCoreClr)\n {\n Assert.Equal(\n@\"Delta.2B: Epsilon: Test E\n\",\n actual);\n }\n else\n {\n Assert.Equal(\n@\"Delta: Epsilon: Test E\n\",\n actual);\n }\n }\n\n [Fact]\n public void AssemblyLoading_MultipleVersions_WorseMatchInSameDirectory()\n {\n StringBuilder sb = new StringBuilder();\n\n var tempDir = Temp.CreateDirectory();\n var epsilonFile = tempDir.CreateFile(\"Epsilon.dll\").CopyContentFrom(_testFixture.Epsilon.Path);\n var delta1File = tempDir.CreateFile(\"Delta.dll\").CopyContentFrom(_testFixture.Delta1.Path);\n\n // Epsilon wants Delta2, but since Delta1 is in the same directory, we prefer Delta1 over Delta2.\n var loader = new DefaultAnalyzerAssemblyLoader();\n loader.AddDependencyLocation(delta1File.Path);\n loader.AddDependencyLocation(_testFixture.Delta2.Path);\n loader.AddDependencyLocation(epsilonFile.Path);\n\n Assembly epsilon = loader.LoadFromPath(epsilonFile.Path);\n var e = epsilon.CreateInstance(\"Epsilon.E\")!;\n e.GetType().GetMethod(\"Write\")!.Invoke(e, new object[] { sb, \"Test E\" });\n\n#if NETCOREAPP\n var alcs = DefaultAnalyzerAssemblyLoader.TestAccessor.GetOrderedLoadContexts(loader);\n Assert.Equal(1, alcs.Length);\n\n VerifyAssemblies(\n alcs[0].Assemblies,\n (\"Delta\", \"1.0.0.0\", delta1File.Path),\n (\"Epsilon\", \"0.0.0.0\", epsilonFile.Path));\n#endif\n\n var actual = sb.ToString();\n Assert.Equal(\n@\"Delta: Epsilon: Test E\n\",\n actual);\n }\n\n [Fact]\n public void AssemblyLoading_MultipleVersions_MultipleLoaders()\n {\n StringBuilder sb = new StringBuilder();\n\n var loader1 = new DefaultAnalyzerAssemblyLoader();\n loader1.AddDependencyLocation(_testFixture.Gamma.Path);\n loader1.AddDependencyLocation(_testFixture.Delta1.Path);\n\n var loader2 = new DefaultAnalyzerAssemblyLoader();\n loader2.AddDependencyLocation(_testFixture.Epsilon.Path);\n loader2.AddDependencyLocation(_testFixture.Delta2.Path);\n\n Assembly gamma = loader1.LoadFromPath(_testFixture.Gamma.Path);\n var g = gamma.CreateInstance(\"Gamma.G\")!;\n g.GetType().GetMethod(\"Write\")!.Invoke(g, new object[] { sb, \"Test G\" });\n\n Assembly epsilon = loader2.LoadFromPath(_testFixture.Epsilon.Path);\n var e = epsilon.CreateInstance(\"Epsilon.E\")!;\n e.GetType().GetMethod(\"Write\")!.Invoke(e, new object[] { sb, \"Test E\" });\n\n#if NETCOREAPP\n var alcs1 = DefaultAnalyzerAssemblyLoader.TestAccessor.GetOrderedLoadContexts(loader1);\n Assert.Equal(1, alcs1.Length);\n\n VerifyAssemblies(\n alcs1[0].Assemblies,\n (\"Delta\", \"1.0.0.0\", _testFixture.Delta1.Path),\n (\"Gamma\", \"0.0.0.0\", _testFixture.Gamma.Path));\n\n var alcs2 = DefaultAnalyzerAssemblyLoader.TestAccessor.GetOrderedLoadContexts(loader2);\n Assert.Equal(1, alcs2.Length);\n\n VerifyAssemblies(\n alcs2[0].Assemblies,\n (\"Delta\", \"2.0.0.0\", _testFixture.Delta2.Path),\n (\"Epsilon\", \"0.0.0.0\", _testFixture.Epsilon.Path));\n#endif\n\n var actual = sb.ToString();\n if (ExecutionConditionUtil.IsCoreClr)\n {\n Assert.Equal(\n@\"Delta: Gamma: Test G\nDelta.2: Epsilon: Test E\n\",\n actual);\n }\n else\n {\n Assert.Equal(\n@\"Delta: Gamma: Test G\nDelta: Epsilon: Test E\n\",\n actual);\n }\n }\n\n [Fact]\n public void AssemblyLoading_MultipleVersions_MissingVersion()\n {\n StringBuilder sb = new StringBuilder();\n\n var loader = new DefaultAnalyzerAssemblyLoader();\n loader.AddDependencyLocation(_testFixture.Gamma.Path);\n loader.AddDependencyLocation(_testFixture.Delta1.Path);\n loader.AddDependencyLocation(_testFixture.Epsilon.Path);\n\n Assembly gamma = loader.LoadFromPath(_testFixture.Gamma.Path);\n var g = gamma.CreateInstance(\"Gamma.G\")!;\n g.GetType().GetMethod(\"Write\")!.Invoke(g, new object[] { sb, \"Test G\" });\n\n Assembly epsilon = loader.LoadFromPath(_testFixture.Epsilon.Path);\n var e = epsilon.CreateInstance(\"Epsilon.E\")!;\n var eWrite = e.GetType().GetMethod(\"Write\")!;\n\n var actual = sb.ToString();\n eWrite.Invoke(e, new object[] { sb, \"Test E\" });\n Assert.Equal(\n@\"Delta: Gamma: Test G\n\",\n actual);\n }\n\n [Fact]\n public void AssemblyLoading_AnalyzerReferencesSystemCollectionsImmutable_01()\n {\n StringBuilder sb = new StringBuilder();\n\n var loader = new DefaultAnalyzerAssemblyLoader();\n loader.AddDependencyLocation(_testFixture.UserSystemCollectionsImmutable.Path);\n loader.AddDependencyLocation(_testFixture.AnalyzerReferencesSystemCollectionsImmutable1.Path);\n\n Assembly analyzerAssembly = loader.LoadFromPath(_testFixture.AnalyzerReferencesSystemCollectionsImmutable1.Path);\n var analyzer = analyzerAssembly.CreateInstance(\"Analyzer\")!;\n\n if (ExecutionConditionUtil.IsCoreClr)\n {\n var ex = Assert.ThrowsAny(() => analyzer.GetType().GetMethod(\"Method\")!.Invoke(analyzer, new object[] { sb }));\n Assert.True(ex is MissingMethodException or TargetInvocationException, $@\"Unexpected exception type: \"\"{ex.GetType()}\"\"\");\n }\n else\n {\n analyzer.GetType().GetMethod(\"Method\")!.Invoke(analyzer, new object[] { sb });\n Assert.Equal(\"42\", sb.ToString());\n }\n }\n\n [Fact]\n public void AssemblyLoading_AnalyzerReferencesSystemCollectionsImmutable_02()\n {\n StringBuilder sb = new StringBuilder();\n\n var loader = new DefaultAnalyzerAssemblyLoader();\n loader.AddDependencyLocation(_testFixture.UserSystemCollectionsImmutable.Path);\n loader.AddDependencyLocation(_testFixture.AnalyzerReferencesSystemCollectionsImmutable2.Path);\n\n Assembly analyzerAssembly = loader.LoadFromPath(_testFixture.AnalyzerReferencesSystemCollectionsImmutable2.Path);\n var analyzer = analyzerAssembly.CreateInstance(\"Analyzer\")!;\n analyzer.GetType().GetMethod(\"Method\")!.Invoke(analyzer, new object[] { sb });\n Assert.Equal(ExecutionConditionUtil.IsCoreClr ? \"1\" : \"42\", sb.ToString());\n }\n\n [ConditionalFact(typeof(WindowsOnly), typeof(CoreClrOnly))]\n public void AssemblyLoading_NativeDependency()\n {\n var loader = new DefaultAnalyzerAssemblyLoader();\n loader.AddDependencyLocation(_testFixture.AnalyzerWithNativeDependency.Path);\n\n Assembly analyzerAssembly = loader.LoadFromPath(_testFixture.AnalyzerWithNativeDependency.Path);\n var analyzer = analyzerAssembly.CreateInstance(\"Class1\")!;\n var result = analyzer.GetType().GetMethod(\"GetFileAttributes\")!.Invoke(analyzer, new[] { _testFixture.AnalyzerWithNativeDependency.Path });\n Assert.Equal(0, Marshal.GetLastWin32Error());\n Assert.Equal(FileAttributes.Archive, (FileAttributes)result!);\n }\n\n [Fact]\n public void AssemblyLoading_Delete()\n {\n StringBuilder sb = new StringBuilder();\n\n var loader = new DefaultAnalyzerAssemblyLoader();\n\n var tempDir = Temp.CreateDirectory();\n var deltaCopy = tempDir.CreateFile(\"Delta.dll\").CopyContentFrom(_testFixture.Delta1.Path);\n loader.AddDependencyLocation(deltaCopy.Path);\n Assembly delta = loader.LoadFromPath(deltaCopy.Path);\n\n try\n {\n File.Delete(deltaCopy.Path);\n }\n catch (UnauthorizedAccessException)\n {\n return;\n }\n\n // The above call may or may not throw depending on the platform configuration.\n // If it doesn't throw, we might as well check that things are still functioning reasonably.\n\n var d = delta.CreateInstance(\"Delta.D\");\n d!.GetType().GetMethod(\"Write\")!.Invoke(d, new object[] { sb, \"Test D\" });\n\n var actual = sb.ToString();\n Assert.Equal(\n@\"Delta: Test D\n\",\n actual);\n }\n\n#if NETCOREAPP\n [Fact]\n public void VerifyCompilerAssemblySimpleNames()\n {\n var caAssembly = typeof(Microsoft.CodeAnalysis.SyntaxNode).Assembly;\n var caReferences = caAssembly.GetReferencedAssemblies();\n var allReferenceSimpleNames = ArrayBuilder.GetInstance();\n allReferenceSimpleNames.Add(caAssembly.GetName().Name ?? throw new InvalidOperationException());\n foreach (var reference in caReferences)\n {\n allReferenceSimpleNames.Add(reference.Name ?? throw new InvalidOperationException());\n }\n\n var csAssembly = typeof(Microsoft.CodeAnalysis.CSharp.CSharpSyntaxNode).Assembly;\n allReferenceSimpleNames.Add(csAssembly.GetName().Name ?? throw new InvalidOperationException());\n var csReferences = csAssembly.GetReferencedAssemblies();\n foreach (var reference in csReferences)\n {\n var name = reference.Name ?? throw new InvalidOperationException();\n if (!allReferenceSimpleNames.Contains(name, StringComparer.OrdinalIgnoreCase))\n {\n allReferenceSimpleNames.Add(name);\n }\n }\n\n var vbAssembly = typeof(Microsoft.CodeAnalysis.VisualBasic.VisualBasicSyntaxNode).Assembly;\n var vbReferences = vbAssembly.GetReferencedAssemblies();\n allReferenceSimpleNames.Add(vbAssembly.GetName().Name ?? throw new InvalidOperationException());\n foreach (var reference in vbReferences)\n {\n var name = reference.Name ?? throw new InvalidOperationException();\n if (!allReferenceSimpleNames.Contains(name, StringComparer.OrdinalIgnoreCase))\n {\n allReferenceSimpleNames.Add(name);\n }\n }\n\n if (!DefaultAnalyzerAssemblyLoader.CompilerAssemblySimpleNames.SetEquals(allReferenceSimpleNames))\n {\n allReferenceSimpleNames.Sort();\n var allNames = string.Join(\",\\r\\n \", allReferenceSimpleNames.Select(name => $@\"\"\"{name}\"\"\"));\n _output.WriteLine(\" internal static readonly ImmutableHashSet CompilerAssemblySimpleNames =\");\n _output.WriteLine(\" ImmutableHashSet.Create(\");\n _output.WriteLine(\" StringComparer.OrdinalIgnoreCase,\");\n _output.WriteLine($\" {allNames});\");\n allReferenceSimpleNames.Free();\n Assert.True(false, $\"{nameof(DefaultAnalyzerAssemblyLoader)}.{nameof(DefaultAnalyzerAssemblyLoader.CompilerAssemblySimpleNames)} is not up to date. Paste in the standard output of this test to update it.\");\n }\n else\n {\n allReferenceSimpleNames.Free();\n }\n }\n\n [Fact]\n public void AssemblyLoadingInNonDefaultContext_AnalyzerReferencesSystemCollectionsImmutable()\n {\n // Create a separate ALC as the compiler context, load the compiler assembly and a modified version of S.C.I into it,\n // then use that to load and run `AssemblyLoadingInNonDefaultContextHelper1` below. We expect the analyzer running in\n // its own `DirectoryLoadContext` would use the bogus S.C.I loaded in the compiler load context instead of the real one\n // in the default context.\n var compilerContext = new System.Runtime.Loader.AssemblyLoadContext(\"compilerContext\");\n _ = compilerContext.LoadFromAssemblyPath(_testFixture.UserSystemCollectionsImmutable.Path);\n _ = compilerContext.LoadFromAssemblyPath(typeof(DefaultAnalyzerAssemblyLoader).GetTypeInfo().Assembly.Location);\n\n var testAssembly = compilerContext.LoadFromAssemblyPath(typeof(DefaultAnalyzerAssemblyLoaderTests).GetTypeInfo().Assembly.Location);\n var testObject = testAssembly.CreateInstance(typeof(DefaultAnalyzerAssemblyLoaderTests).FullName!,\n ignoreCase: false, BindingFlags.Default, binder: null, args: new object[] { _output, _testFixture }, null, null)!;\n\n StringBuilder sb = new StringBuilder();\n testObject.GetType().GetMethod(nameof(AssemblyLoadingInNonDefaultContextHelper1), BindingFlags.Instance | BindingFlags.NonPublic)!.Invoke(testObject, new object[] { sb });\n Assert.Equal(\"42\", sb.ToString());\n }\n\n // This helper does the same thing as in `AssemblyLoading_AnalyzerReferencesSystemCollectionsImmutable_01` test above except the assertions.\n private void AssemblyLoadingInNonDefaultContextHelper1(StringBuilder sb)\n {\n var loader = new DefaultAnalyzerAssemblyLoader();\n loader.AddDependencyLocation(_testFixture.UserSystemCollectionsImmutable.Path);\n loader.AddDependencyLocation(_testFixture.AnalyzerReferencesSystemCollectionsImmutable1.Path);\n\n Assembly analyzerAssembly = loader.LoadFromPath(_testFixture.AnalyzerReferencesSystemCollectionsImmutable1.Path);\n var analyzer = analyzerAssembly.CreateInstance(\"Analyzer\")!;\n analyzer.GetType().GetMethod(\"Method\")!.Invoke(analyzer, new object[] { sb });\n }\n\n [Fact]\n public void AssemblyLoadingInNonDefaultContext_AnalyzerReferencesNonCompilerAssemblyUsedByDefaultContext()\n {\n // Load the V2 of Delta to default ALC, then create a separate ALC for compiler and load compiler assembly.\n // Next use compiler context to load and run `AssemblyLoadingInNonDefaultContextHelper2` below. We expect the analyzer running in\n // its own `DirectoryLoadContext` would load and use Delta V1 located in its directory instead of V2 already loaded in the default context.\n _ = System.Runtime.Loader.AssemblyLoadContext.Default.LoadFromAssemblyPath(_testFixture.Delta2.Path);\n var compilerContext = new System.Runtime.Loader.AssemblyLoadContext(\"compilerContext\");\n _ = compilerContext.LoadFromAssemblyPath(typeof(DefaultAnalyzerAssemblyLoader).GetTypeInfo().Assembly.Location);\n\n var testAssembly = compilerContext.LoadFromAssemblyPath(typeof(DefaultAnalyzerAssemblyLoaderTests).GetTypeInfo().Assembly.Location);\n var testObject = testAssembly.CreateInstance(typeof(DefaultAnalyzerAssemblyLoaderTests).FullName!,\n ignoreCase: false, BindingFlags.Default, binder: null, args: new object[] { _output, _testFixture }, null, null)!;\n\n StringBuilder sb = new StringBuilder();\n testObject.GetType().GetMethod(nameof(AssemblyLoadingInNonDefaultContextHelper2), BindingFlags.Instance | BindingFlags.NonPublic)!.Invoke(testObject, new object[] { sb });\n Assert.Equal(\n@\"Delta: Hello\n\",\n sb.ToString());\n }\n\n private void AssemblyLoadingInNonDefaultContextHelper2(StringBuilder sb)\n {\n var loader = new DefaultAnalyzerAssemblyLoader();\n loader.AddDependencyLocation(_testFixture.AnalyzerReferencesDelta1.Path);\n loader.AddDependencyLocation(_testFixture.Delta1.Path);\n\n Assembly analyzerAssembly = loader.LoadFromPath(_testFixture.AnalyzerReferencesDelta1.Path);\n var analyzer = analyzerAssembly.CreateInstance(\"Analyzer\")!;\n analyzer.GetType().GetMethod(\"Method\")!.Invoke(analyzer, new object[] { sb });\n }\n#endif\n }\n}\n"},"after_content":{"kind":"string","value":"// Licensed to the .NET Foundation under one or more agreements.\n// The .NET Foundation licenses this file to you under the MIT license.\n// See the LICENSE file in the project root for more information.\n\nusing System;\nusing System.Collections.Generic;\nusing System.Collections.Immutable;\nusing System.IO;\nusing System.Linq;\nusing System.Reflection;\nusing System.Runtime.InteropServices;\nusing System.Text;\nusing Microsoft.CodeAnalysis.CSharp;\nusing Microsoft.CodeAnalysis.Diagnostics;\nusing Microsoft.CodeAnalysis.PooledObjects;\nusing Microsoft.CodeAnalysis.Test.Utilities;\nusing Roslyn.Test.Utilities;\nusing Roslyn.Utilities;\nusing Xunit;\nusing Xunit.Abstractions;\n\nnamespace Microsoft.CodeAnalysis.UnitTests\n{\n [CollectionDefinition(Name)]\n public class AssemblyLoadTestFixtureCollection : ICollectionFixture\n {\n public const string Name = nameof(AssemblyLoadTestFixtureCollection);\n private AssemblyLoadTestFixtureCollection() { }\n }\n\n [Collection(AssemblyLoadTestFixtureCollection.Name)]\n public sealed class DefaultAnalyzerAssemblyLoaderTests : TestBase\n {\n private static readonly CSharpCompilationOptions s_dllWithMaxWarningLevel = new(OutputKind.DynamicallyLinkedLibrary, warningLevel: CodeAnalysis.Diagnostic.MaxWarningLevel);\n private readonly ITestOutputHelper _output;\n private readonly AssemblyLoadTestFixture _testFixture;\n public DefaultAnalyzerAssemblyLoaderTests(ITestOutputHelper output, AssemblyLoadTestFixture testFixture)\n {\n _output = output;\n _testFixture = testFixture;\n }\n\n [Fact, WorkItem(32226, \"https://github.com/dotnet/roslyn/issues/32226\")]\n public void LoadWithDependency()\n {\n var analyzerDependencyFile = _testFixture.AnalyzerDependency;\n var analyzerMainFile = _testFixture.AnalyzerWithDependency;\n var loader = new DefaultAnalyzerAssemblyLoader();\n loader.AddDependencyLocation(analyzerDependencyFile.Path);\n\n var analyzerMainReference = new AnalyzerFileReference(analyzerMainFile.Path, loader);\n analyzerMainReference.AnalyzerLoadFailed += (_, e) => AssertEx.Fail(e.Exception!.Message);\n var analyzerDependencyReference = new AnalyzerFileReference(analyzerDependencyFile.Path, loader);\n analyzerDependencyReference.AnalyzerLoadFailed += (_, e) => AssertEx.Fail(e.Exception!.Message);\n\n var analyzers = analyzerMainReference.GetAnalyzersForAllLanguages();\n Assert.Equal(1, analyzers.Length);\n Assert.Equal(\"TestAnalyzer\", analyzers[0].ToString());\n\n Assert.Equal(0, analyzerDependencyReference.GetAnalyzersForAllLanguages().Length);\n\n Assert.NotNull(analyzerDependencyReference.GetAssembly());\n }\n\n [Fact]\n public void AddDependencyLocationThrowsOnNull()\n {\n var loader = new DefaultAnalyzerAssemblyLoader();\n\n Assert.Throws(\"fullPath\", () => loader.AddDependencyLocation(null!));\n Assert.Throws(\"fullPath\", () => loader.AddDependencyLocation(\"a\"));\n }\n\n [Fact]\n public void ThrowsForMissingFile()\n {\n var path = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName() + \".dll\");\n\n var loader = new DefaultAnalyzerAssemblyLoader();\n\n Assert.ThrowsAny(() => loader.LoadFromPath(path));\n }\n\n [Fact]\n public void BasicLoad()\n {\n var loader = new DefaultAnalyzerAssemblyLoader();\n loader.AddDependencyLocation(_testFixture.Alpha.Path);\n Assembly alpha = loader.LoadFromPath(_testFixture.Alpha.Path);\n\n Assert.NotNull(alpha);\n }\n\n [Fact]\n public void AssemblyLoading()\n {\n StringBuilder sb = new StringBuilder();\n\n var loader = new DefaultAnalyzerAssemblyLoader();\n loader.AddDependencyLocation(_testFixture.Alpha.Path);\n loader.AddDependencyLocation(_testFixture.Beta.Path);\n loader.AddDependencyLocation(_testFixture.Gamma.Path);\n loader.AddDependencyLocation(_testFixture.Delta1.Path);\n\n Assembly alpha = loader.LoadFromPath(_testFixture.Alpha.Path);\n\n var a = alpha.CreateInstance(\"Alpha.A\")!;\n a.GetType().GetMethod(\"Write\")!.Invoke(a, new object[] { sb, \"Test A\" });\n\n Assembly beta = loader.LoadFromPath(_testFixture.Beta.Path);\n\n var b = beta.CreateInstance(\"Beta.B\")!;\n b.GetType().GetMethod(\"Write\")!.Invoke(b, new object[] { sb, \"Test B\" });\n\n var expected = @\"Delta: Gamma: Alpha: Test A\nDelta: Gamma: Beta: Test B\n\";\n\n var actual = sb.ToString();\n\n Assert.Equal(expected, actual);\n }\n\n [ConditionalFact(typeof(CoreClrOnly))]\n public void AssemblyLoading_AssemblyLocationNotAdded()\n {\n var loader = new DefaultAnalyzerAssemblyLoader();\n loader.AddDependencyLocation(_testFixture.Gamma.Path);\n loader.AddDependencyLocation(_testFixture.Delta1.Path);\n Assert.Throws(() => loader.LoadFromPath(_testFixture.Beta.Path));\n }\n\n [ConditionalFact(typeof(CoreClrOnly))]\n public void AssemblyLoading_DependencyLocationNotAdded()\n {\n StringBuilder sb = new StringBuilder();\n var loader = new DefaultAnalyzerAssemblyLoader();\n // We don't pass Alpha's path to AddDependencyLocation here, and therefore expect\n // calling Beta.B.Write to fail.\n loader.AddDependencyLocation(_testFixture.Gamma.Path);\n loader.AddDependencyLocation(_testFixture.Beta.Path);\n Assembly beta = loader.LoadFromPath(_testFixture.Beta.Path);\n\n var b = beta.CreateInstance(\"Beta.B\")!;\n var writeMethod = b.GetType().GetMethod(\"Write\")!;\n var exception = Assert.Throws(\n () => writeMethod.Invoke(b, new object[] { sb, \"Test B\" }));\n Assert.IsAssignableFrom(exception.InnerException);\n\n var actual = sb.ToString();\n Assert.Equal(@\"\", actual);\n }\n\n private static void VerifyAssemblies(IEnumerable assemblies, params (string simpleName, string version, string path)[] expected)\n {\n Assert.Equal(expected, assemblies.Select(assembly => (assembly.GetName().Name!, assembly.GetName().Version!.ToString(), assembly.Location)).Order());\n }\n\n [ConditionalFact(typeof(CoreClrOnly))]\n public void AssemblyLoading_DependencyInDifferentDirectory()\n {\n StringBuilder sb = new StringBuilder();\n var loader = new DefaultAnalyzerAssemblyLoader();\n\n var tempDir = Temp.CreateDirectory();\n\n var deltaFile = tempDir.CreateFile(\"Delta.dll\").CopyContentFrom(_testFixture.Delta1.Path);\n loader.AddDependencyLocation(deltaFile.Path);\n loader.AddDependencyLocation(_testFixture.Gamma.Path);\n Assembly gamma = loader.LoadFromPath(_testFixture.Gamma.Path);\n\n var b = gamma.CreateInstance(\"Gamma.G\")!;\n var writeMethod = b.GetType().GetMethod(\"Write\")!;\n writeMethod.Invoke(b, new object[] { sb, \"Test G\" });\n\n var actual = sb.ToString();\n Assert.Equal(@\"Delta: Gamma: Test G\n\", actual);\n\n#if NETCOREAPP\n var alcs = DefaultAnalyzerAssemblyLoader.TestAccessor.GetOrderedLoadContexts(loader);\n Assert.Equal(1, alcs.Length);\n\n VerifyAssemblies(\n alcs[0].Assemblies,\n (\"Delta\", \"1.0.0.0\", deltaFile.Path),\n (\"Gamma\", \"0.0.0.0\", _testFixture.Gamma.Path)\n );\n#endif\n }\n\n [Fact]\n public void AssemblyLoading_MultipleVersions()\n {\n StringBuilder sb = new StringBuilder();\n\n var loader = new DefaultAnalyzerAssemblyLoader();\n loader.AddDependencyLocation(_testFixture.Gamma.Path);\n loader.AddDependencyLocation(_testFixture.Delta1.Path);\n loader.AddDependencyLocation(_testFixture.Epsilon.Path);\n loader.AddDependencyLocation(_testFixture.Delta2.Path);\n\n Assembly gamma = loader.LoadFromPath(_testFixture.Gamma.Path);\n var g = gamma.CreateInstance(\"Gamma.G\")!;\n g.GetType().GetMethod(\"Write\")!.Invoke(g, new object[] { sb, \"Test G\" });\n\n Assembly epsilon = loader.LoadFromPath(_testFixture.Epsilon.Path);\n var e = epsilon.CreateInstance(\"Epsilon.E\")!;\n e.GetType().GetMethod(\"Write\")!.Invoke(e, new object[] { sb, \"Test E\" });\n\n#if NETCOREAPP\n var alcs = DefaultAnalyzerAssemblyLoader.TestAccessor.GetOrderedLoadContexts(loader);\n Assert.Equal(2, alcs.Length);\n\n VerifyAssemblies(\n alcs[0].Assemblies,\n (\"Delta\", \"1.0.0.0\", _testFixture.Delta1.Path),\n (\"Gamma\", \"0.0.0.0\", _testFixture.Gamma.Path)\n );\n\n VerifyAssemblies(\n alcs[1].Assemblies,\n (\"Delta\", \"2.0.0.0\", _testFixture.Delta2.Path),\n (\"Epsilon\", \"0.0.0.0\", _testFixture.Epsilon.Path));\n#endif\n\n var actual = sb.ToString();\n if (ExecutionConditionUtil.IsCoreClr)\n {\n Assert.Equal(\n@\"Delta: Gamma: Test G\nDelta.2: Epsilon: Test E\n\",\n actual);\n }\n else\n {\n Assert.Equal(\n@\"Delta: Gamma: Test G\nDelta: Epsilon: Test E\n\",\n actual);\n }\n }\n\n [Fact]\n public void AssemblyLoading_MultipleVersions_NoExactMatch()\n {\n StringBuilder sb = new StringBuilder();\n\n var loader = new DefaultAnalyzerAssemblyLoader();\n loader.AddDependencyLocation(_testFixture.Delta1.Path);\n loader.AddDependencyLocation(_testFixture.Epsilon.Path);\n loader.AddDependencyLocation(_testFixture.Delta3.Path);\n\n Assembly epsilon = loader.LoadFromPath(_testFixture.Epsilon.Path);\n var e = epsilon.CreateInstance(\"Epsilon.E\")!;\n e.GetType().GetMethod(\"Write\")!.Invoke(e, new object[] { sb, \"Test E\" });\n\n#if NETCOREAPP\n var alcs = DefaultAnalyzerAssemblyLoader.TestAccessor.GetOrderedLoadContexts(loader);\n Assert.Equal(1, alcs.Length);\n\n VerifyAssemblies(\n alcs[0].Assemblies,\n (\"Delta\", \"3.0.0.0\", _testFixture.Delta3.Path),\n (\"Epsilon\", \"0.0.0.0\", _testFixture.Epsilon.Path));\n#endif\n\n var actual = sb.ToString();\n if (ExecutionConditionUtil.IsCoreClr)\n {\n Assert.Equal(\n@\"Delta.3: Epsilon: Test E\n\",\n actual);\n }\n else\n {\n Assert.Equal(\n@\"Delta: Epsilon: Test E\n\",\n actual);\n }\n }\n\n [Fact]\n public void AssemblyLoading_MultipleVersions_MultipleEqualMatches()\n {\n StringBuilder sb = new StringBuilder();\n\n // Delta2B and Delta2 have the same version, but we prefer Delta2 because it's in the same directory as Epsilon.\n var loader = new DefaultAnalyzerAssemblyLoader();\n loader.AddDependencyLocation(_testFixture.Delta2B.Path);\n loader.AddDependencyLocation(_testFixture.Delta2.Path);\n loader.AddDependencyLocation(_testFixture.Epsilon.Path);\n\n Assembly epsilon = loader.LoadFromPath(_testFixture.Epsilon.Path);\n var e = epsilon.CreateInstance(\"Epsilon.E\")!;\n e.GetType().GetMethod(\"Write\")!.Invoke(e, new object[] { sb, \"Test E\" });\n\n#if NETCOREAPP\n var alcs = DefaultAnalyzerAssemblyLoader.TestAccessor.GetOrderedLoadContexts(loader);\n Assert.Equal(1, alcs.Length);\n\n VerifyAssemblies(\n alcs[0].Assemblies,\n (\"Delta\", \"2.0.0.0\", _testFixture.Delta2.Path),\n (\"Epsilon\", \"0.0.0.0\", _testFixture.Epsilon.Path));\n#endif\n\n var actual = sb.ToString();\n if (ExecutionConditionUtil.IsCoreClr)\n {\n Assert.Equal(\n@\"Delta.2: Epsilon: Test E\n\",\n actual);\n }\n else\n {\n Assert.Equal(\n@\"Delta: Epsilon: Test E\n\",\n actual);\n }\n }\n\n\n [Fact]\n public void AssemblyLoading_MultipleVersions_MultipleVersionsOfSameAnalyzerItself()\n {\n StringBuilder sb = new StringBuilder();\n\n var loader = new DefaultAnalyzerAssemblyLoader();\n loader.AddDependencyLocation(_testFixture.Delta2.Path);\n loader.AddDependencyLocation(_testFixture.Delta2B.Path);\n\n Assembly delta2 = loader.LoadFromPath(_testFixture.Delta2.Path);\n Assembly delta2B = loader.LoadFromPath(_testFixture.Delta2B.Path);\n\n // 2B or not 2B? That is the question...that depends on whether we're on .NET Core or not.\n\n#if NETCOREAPP\n\n // On Core, we're able to load both of these into separate AssemblyLoadContexts.\n Assert.NotEqual(delta2B.Location, delta2.Location);\n Assert.Equal(_testFixture.Delta2.Path, delta2.Location);\n Assert.Equal(_testFixture.Delta2B.Path, delta2B.Location);\n\n#else\n\n // In non-core, we cache by assembly identity; since we don't use multiple AppDomains we have no\n // way to load different assemblies with the same identity, no matter what. Thus, we'll get the\n // same assembly for both of these.\n Assert.Same(delta2B, delta2);\n#endif\n }\n\n [Fact]\n public void AssemblyLoading_MultipleVersions_ExactAndGreaterMatch()\n {\n StringBuilder sb = new StringBuilder();\n\n var loader = new DefaultAnalyzerAssemblyLoader();\n loader.AddDependencyLocation(_testFixture.Delta2B.Path);\n loader.AddDependencyLocation(_testFixture.Delta3.Path);\n loader.AddDependencyLocation(_testFixture.Epsilon.Path);\n\n Assembly epsilon = loader.LoadFromPath(_testFixture.Epsilon.Path);\n var e = epsilon.CreateInstance(\"Epsilon.E\")!;\n e.GetType().GetMethod(\"Write\")!.Invoke(e, new object[] { sb, \"Test E\" });\n\n#if NETCOREAPP\n var alcs = DefaultAnalyzerAssemblyLoader.TestAccessor.GetOrderedLoadContexts(loader);\n Assert.Equal(1, alcs.Length);\n\n VerifyAssemblies(\n alcs[0].Assemblies,\n (\"Delta\", \"2.0.0.0\", _testFixture.Delta2B.Path),\n (\"Epsilon\", \"0.0.0.0\", _testFixture.Epsilon.Path));\n#endif\n\n var actual = sb.ToString();\n if (ExecutionConditionUtil.IsCoreClr)\n {\n Assert.Equal(\n@\"Delta.2B: Epsilon: Test E\n\",\n actual);\n }\n else\n {\n Assert.Equal(\n@\"Delta: Epsilon: Test E\n\",\n actual);\n }\n }\n\n [Fact]\n public void AssemblyLoading_MultipleVersions_WorseMatchInSameDirectory()\n {\n StringBuilder sb = new StringBuilder();\n\n var tempDir = Temp.CreateDirectory();\n var epsilonFile = tempDir.CreateFile(\"Epsilon.dll\").CopyContentFrom(_testFixture.Epsilon.Path);\n var delta1File = tempDir.CreateFile(\"Delta.dll\").CopyContentFrom(_testFixture.Delta1.Path);\n\n // Epsilon wants Delta2, but since Delta1 is in the same directory, we prefer Delta1 over Delta2.\n // This is because the CLR will see it first and load it, without giving us any chance to redirect\n // in the AssemblyResolve hook.\n var loader = new DefaultAnalyzerAssemblyLoader();\n loader.AddDependencyLocation(delta1File.Path);\n loader.AddDependencyLocation(_testFixture.Delta2.Path);\n loader.AddDependencyLocation(epsilonFile.Path);\n\n Assembly epsilon = loader.LoadFromPath(epsilonFile.Path);\n var e = epsilon.CreateInstance(\"Epsilon.E\")!;\n e.GetType().GetMethod(\"Write\")!.Invoke(e, new object[] { sb, \"Test E\" });\n\n#if NETCOREAPP\n var alcs = DefaultAnalyzerAssemblyLoader.TestAccessor.GetOrderedLoadContexts(loader);\n Assert.Equal(1, alcs.Length);\n\n VerifyAssemblies(\n alcs[0].Assemblies,\n (\"Delta\", \"1.0.0.0\", delta1File.Path),\n (\"Epsilon\", \"0.0.0.0\", epsilonFile.Path));\n#endif\n\n var actual = sb.ToString();\n Assert.Equal(\n@\"Delta: Epsilon: Test E\n\",\n actual);\n }\n\n [Fact]\n public void AssemblyLoading_MultipleVersions_MultipleLoaders()\n {\n StringBuilder sb = new StringBuilder();\n\n var loader1 = new DefaultAnalyzerAssemblyLoader();\n loader1.AddDependencyLocation(_testFixture.Gamma.Path);\n loader1.AddDependencyLocation(_testFixture.Delta1.Path);\n\n var loader2 = new DefaultAnalyzerAssemblyLoader();\n loader2.AddDependencyLocation(_testFixture.Epsilon.Path);\n loader2.AddDependencyLocation(_testFixture.Delta2.Path);\n\n Assembly gamma = loader1.LoadFromPath(_testFixture.Gamma.Path);\n var g = gamma.CreateInstance(\"Gamma.G\")!;\n g.GetType().GetMethod(\"Write\")!.Invoke(g, new object[] { sb, \"Test G\" });\n\n Assembly epsilon = loader2.LoadFromPath(_testFixture.Epsilon.Path);\n var e = epsilon.CreateInstance(\"Epsilon.E\")!;\n e.GetType().GetMethod(\"Write\")!.Invoke(e, new object[] { sb, \"Test E\" });\n\n#if NETCOREAPP\n var alcs1 = DefaultAnalyzerAssemblyLoader.TestAccessor.GetOrderedLoadContexts(loader1);\n Assert.Equal(1, alcs1.Length);\n\n VerifyAssemblies(\n alcs1[0].Assemblies,\n (\"Delta\", \"1.0.0.0\", _testFixture.Delta1.Path),\n (\"Gamma\", \"0.0.0.0\", _testFixture.Gamma.Path));\n\n var alcs2 = DefaultAnalyzerAssemblyLoader.TestAccessor.GetOrderedLoadContexts(loader2);\n Assert.Equal(1, alcs2.Length);\n\n VerifyAssemblies(\n alcs2[0].Assemblies,\n (\"Delta\", \"2.0.0.0\", _testFixture.Delta2.Path),\n (\"Epsilon\", \"0.0.0.0\", _testFixture.Epsilon.Path));\n#endif\n\n var actual = sb.ToString();\n if (ExecutionConditionUtil.IsCoreClr)\n {\n Assert.Equal(\n@\"Delta: Gamma: Test G\nDelta.2: Epsilon: Test E\n\",\n actual);\n }\n else\n {\n Assert.Equal(\n@\"Delta: Gamma: Test G\nDelta: Epsilon: Test E\n\",\n actual);\n }\n }\n\n [Fact]\n public void AssemblyLoading_MultipleVersions_MissingVersion()\n {\n StringBuilder sb = new StringBuilder();\n\n var loader = new DefaultAnalyzerAssemblyLoader();\n loader.AddDependencyLocation(_testFixture.Gamma.Path);\n loader.AddDependencyLocation(_testFixture.Delta1.Path);\n loader.AddDependencyLocation(_testFixture.Epsilon.Path);\n\n Assembly gamma = loader.LoadFromPath(_testFixture.Gamma.Path);\n var g = gamma.CreateInstance(\"Gamma.G\")!;\n g.GetType().GetMethod(\"Write\")!.Invoke(g, new object[] { sb, \"Test G\" });\n\n Assembly epsilon = loader.LoadFromPath(_testFixture.Epsilon.Path);\n var e = epsilon.CreateInstance(\"Epsilon.E\")!;\n var eWrite = e.GetType().GetMethod(\"Write\")!;\n\n var actual = sb.ToString();\n eWrite.Invoke(e, new object[] { sb, \"Test E\" });\n Assert.Equal(\n@\"Delta: Gamma: Test G\n\",\n actual);\n }\n\n [Fact]\n public void AssemblyLoading_UnifyToHighest()\n {\n var sb = new StringBuilder();\n\n var loader = new DefaultAnalyzerAssemblyLoader();\n\n // Gamma depends on Delta v1, and Epsilon depends on Delta v2. But both should load\n // and both use Delta v2. We intentionally here are not adding a reference to Delta1, since\n // this test is testing what happens if it's not present. A simple example for this scenario\n // is an analyzer that depends on both Gamma and Epsilon; an analyzer package can't reasonably\n // package both Delta v1 and Delta v2, so it'll only package the highest and things should work.\n loader.AddDependencyLocation(_testFixture.GammaReferencingPublicSigned.Path);\n loader.AddDependencyLocation(_testFixture.EpsilonReferencingPublicSigned.Path);\n loader.AddDependencyLocation(_testFixture.DeltaPublicSigned2.Path);\n\n var gamma = loader.LoadFromPath(_testFixture.GammaReferencingPublicSigned.Path);\n var g = gamma.CreateInstance(\"Gamma.G\")!;\n g.GetType().GetMethod(\"Write\")!.Invoke(g, new object[] { sb, \"Test G\" });\n\n var epsilon = loader.LoadFromPath(_testFixture.EpsilonReferencingPublicSigned.Path);\n var e = epsilon.CreateInstance(\"Epsilon.E\")!;\n e.GetType().GetMethod(\"Write\")!.Invoke(e, new object[] { sb, \"Test E\" });\n\n var actual = sb.ToString();\n\n Assert.Equal(\n@\"Delta.2: Gamma: Test G\nDelta.2: Epsilon: Test E\n\",\n actual);\n }\n\n [Fact]\n public void AssemblyLoading_CanLoadDifferentVersionsDirectly()\n {\n var sb = new StringBuilder();\n\n var loader = new DefaultAnalyzerAssemblyLoader();\n\n // Ensure that no matter what, if we have two analyzers of different versions, we never unify them.\n loader.AddDependencyLocation(_testFixture.DeltaPublicSigned1.Path);\n loader.AddDependencyLocation(_testFixture.DeltaPublicSigned2.Path);\n\n var delta1Assembly = loader.LoadFromPath(_testFixture.DeltaPublicSigned1.Path);\n var delta1Instance = delta1Assembly.CreateInstance(\"Delta.D\")!;\n delta1Instance.GetType().GetMethod(\"Write\")!.Invoke(delta1Instance, new object[] { sb, \"Test D1\" });\n\n var delta2Assembly = loader.LoadFromPath(_testFixture.DeltaPublicSigned2.Path);\n var delta2Instance = delta2Assembly.CreateInstance(\"Delta.D\")!;\n delta2Instance.GetType().GetMethod(\"Write\")!.Invoke(delta2Instance, new object[] { sb, \"Test D2\" });\n\n var actual = sb.ToString();\n\n Assert.Equal(\n@\"Delta: Test D1\nDelta.2: Test D2\n\",\n actual);\n }\n\n [Fact]\n public void AssemblyLoading_AnalyzerReferencesSystemCollectionsImmutable_01()\n {\n StringBuilder sb = new StringBuilder();\n\n var loader = new DefaultAnalyzerAssemblyLoader();\n loader.AddDependencyLocation(_testFixture.UserSystemCollectionsImmutable.Path);\n loader.AddDependencyLocation(_testFixture.AnalyzerReferencesSystemCollectionsImmutable1.Path);\n\n Assembly analyzerAssembly = loader.LoadFromPath(_testFixture.AnalyzerReferencesSystemCollectionsImmutable1.Path);\n var analyzer = analyzerAssembly.CreateInstance(\"Analyzer\")!;\n\n if (ExecutionConditionUtil.IsCoreClr)\n {\n var ex = Assert.ThrowsAny(() => analyzer.GetType().GetMethod(\"Method\")!.Invoke(analyzer, new object[] { sb }));\n Assert.True(ex is MissingMethodException or TargetInvocationException, $@\"Unexpected exception type: \"\"{ex.GetType()}\"\"\");\n }\n else\n {\n analyzer.GetType().GetMethod(\"Method\")!.Invoke(analyzer, new object[] { sb });\n Assert.Equal(\"42\", sb.ToString());\n }\n }\n\n [Fact]\n public void AssemblyLoading_AnalyzerReferencesSystemCollectionsImmutable_02()\n {\n StringBuilder sb = new StringBuilder();\n\n var loader = new DefaultAnalyzerAssemblyLoader();\n loader.AddDependencyLocation(_testFixture.UserSystemCollectionsImmutable.Path);\n loader.AddDependencyLocation(_testFixture.AnalyzerReferencesSystemCollectionsImmutable2.Path);\n\n Assembly analyzerAssembly = loader.LoadFromPath(_testFixture.AnalyzerReferencesSystemCollectionsImmutable2.Path);\n var analyzer = analyzerAssembly.CreateInstance(\"Analyzer\")!;\n analyzer.GetType().GetMethod(\"Method\")!.Invoke(analyzer, new object[] { sb });\n Assert.Equal(ExecutionConditionUtil.IsCoreClr ? \"1\" : \"42\", sb.ToString());\n }\n\n [ConditionalFact(typeof(WindowsOnly), typeof(CoreClrOnly))]\n public void AssemblyLoading_NativeDependency()\n {\n var loader = new DefaultAnalyzerAssemblyLoader();\n loader.AddDependencyLocation(_testFixture.AnalyzerWithNativeDependency.Path);\n\n Assembly analyzerAssembly = loader.LoadFromPath(_testFixture.AnalyzerWithNativeDependency.Path);\n var analyzer = analyzerAssembly.CreateInstance(\"Class1\")!;\n var result = analyzer.GetType().GetMethod(\"GetFileAttributes\")!.Invoke(analyzer, new[] { _testFixture.AnalyzerWithNativeDependency.Path });\n Assert.Equal(0, Marshal.GetLastWin32Error());\n Assert.Equal(FileAttributes.Archive, (FileAttributes)result!);\n }\n\n [Fact]\n public void AssemblyLoading_Delete()\n {\n StringBuilder sb = new StringBuilder();\n\n var loader = new DefaultAnalyzerAssemblyLoader();\n\n var tempDir = Temp.CreateDirectory();\n var deltaCopy = tempDir.CreateFile(\"Delta.dll\").CopyContentFrom(_testFixture.Delta1.Path);\n loader.AddDependencyLocation(deltaCopy.Path);\n Assembly delta = loader.LoadFromPath(deltaCopy.Path);\n\n try\n {\n File.Delete(deltaCopy.Path);\n }\n catch (UnauthorizedAccessException)\n {\n return;\n }\n\n // The above call may or may not throw depending on the platform configuration.\n // If it doesn't throw, we might as well check that things are still functioning reasonably.\n\n var d = delta.CreateInstance(\"Delta.D\");\n d!.GetType().GetMethod(\"Write\")!.Invoke(d, new object[] { sb, \"Test D\" });\n\n var actual = sb.ToString();\n Assert.Equal(\n@\"Delta: Test D\n\",\n actual);\n }\n\n#if NETCOREAPP\n [Fact]\n public void VerifyCompilerAssemblySimpleNames()\n {\n var caAssembly = typeof(Microsoft.CodeAnalysis.SyntaxNode).Assembly;\n var caReferences = caAssembly.GetReferencedAssemblies();\n var allReferenceSimpleNames = ArrayBuilder.GetInstance();\n allReferenceSimpleNames.Add(caAssembly.GetName().Name ?? throw new InvalidOperationException());\n foreach (var reference in caReferences)\n {\n allReferenceSimpleNames.Add(reference.Name ?? throw new InvalidOperationException());\n }\n\n var csAssembly = typeof(Microsoft.CodeAnalysis.CSharp.CSharpSyntaxNode).Assembly;\n allReferenceSimpleNames.Add(csAssembly.GetName().Name ?? throw new InvalidOperationException());\n var csReferences = csAssembly.GetReferencedAssemblies();\n foreach (var reference in csReferences)\n {\n var name = reference.Name ?? throw new InvalidOperationException();\n if (!allReferenceSimpleNames.Contains(name, StringComparer.OrdinalIgnoreCase))\n {\n allReferenceSimpleNames.Add(name);\n }\n }\n\n var vbAssembly = typeof(Microsoft.CodeAnalysis.VisualBasic.VisualBasicSyntaxNode).Assembly;\n var vbReferences = vbAssembly.GetReferencedAssemblies();\n allReferenceSimpleNames.Add(vbAssembly.GetName().Name ?? throw new InvalidOperationException());\n foreach (var reference in vbReferences)\n {\n var name = reference.Name ?? throw new InvalidOperationException();\n if (!allReferenceSimpleNames.Contains(name, StringComparer.OrdinalIgnoreCase))\n {\n allReferenceSimpleNames.Add(name);\n }\n }\n\n if (!DefaultAnalyzerAssemblyLoader.CompilerAssemblySimpleNames.SetEquals(allReferenceSimpleNames))\n {\n allReferenceSimpleNames.Sort();\n var allNames = string.Join(\",\\r\\n \", allReferenceSimpleNames.Select(name => $@\"\"\"{name}\"\"\"));\n _output.WriteLine(\" internal static readonly ImmutableHashSet CompilerAssemblySimpleNames =\");\n _output.WriteLine(\" ImmutableHashSet.Create(\");\n _output.WriteLine(\" StringComparer.OrdinalIgnoreCase,\");\n _output.WriteLine($\" {allNames});\");\n allReferenceSimpleNames.Free();\n Assert.True(false, $\"{nameof(DefaultAnalyzerAssemblyLoader)}.{nameof(DefaultAnalyzerAssemblyLoader.CompilerAssemblySimpleNames)} is not up to date. Paste in the standard output of this test to update it.\");\n }\n else\n {\n allReferenceSimpleNames.Free();\n }\n }\n\n [Fact]\n public void AssemblyLoadingInNonDefaultContext_AnalyzerReferencesSystemCollectionsImmutable()\n {\n // Create a separate ALC as the compiler context, load the compiler assembly and a modified version of S.C.I into it,\n // then use that to load and run `AssemblyLoadingInNonDefaultContextHelper1` below. We expect the analyzer running in\n // its own `DirectoryLoadContext` would use the bogus S.C.I loaded in the compiler load context instead of the real one\n // in the default context.\n var compilerContext = new System.Runtime.Loader.AssemblyLoadContext(\"compilerContext\");\n _ = compilerContext.LoadFromAssemblyPath(_testFixture.UserSystemCollectionsImmutable.Path);\n _ = compilerContext.LoadFromAssemblyPath(typeof(DefaultAnalyzerAssemblyLoader).GetTypeInfo().Assembly.Location);\n\n var testAssembly = compilerContext.LoadFromAssemblyPath(typeof(DefaultAnalyzerAssemblyLoaderTests).GetTypeInfo().Assembly.Location);\n var testObject = testAssembly.CreateInstance(typeof(DefaultAnalyzerAssemblyLoaderTests).FullName!,\n ignoreCase: false, BindingFlags.Default, binder: null, args: new object[] { _output, _testFixture }, null, null)!;\n\n StringBuilder sb = new StringBuilder();\n testObject.GetType().GetMethod(nameof(AssemblyLoadingInNonDefaultContextHelper1), BindingFlags.Instance | BindingFlags.NonPublic)!.Invoke(testObject, new object[] { sb });\n Assert.Equal(\"42\", sb.ToString());\n }\n\n // This helper does the same thing as in `AssemblyLoading_AnalyzerReferencesSystemCollectionsImmutable_01` test above except the assertions.\n private void AssemblyLoadingInNonDefaultContextHelper1(StringBuilder sb)\n {\n var loader = new DefaultAnalyzerAssemblyLoader();\n loader.AddDependencyLocation(_testFixture.UserSystemCollectionsImmutable.Path);\n loader.AddDependencyLocation(_testFixture.AnalyzerReferencesSystemCollectionsImmutable1.Path);\n\n Assembly analyzerAssembly = loader.LoadFromPath(_testFixture.AnalyzerReferencesSystemCollectionsImmutable1.Path);\n var analyzer = analyzerAssembly.CreateInstance(\"Analyzer\")!;\n analyzer.GetType().GetMethod(\"Method\")!.Invoke(analyzer, new object[] { sb });\n }\n\n [Fact]\n public void AssemblyLoadingInNonDefaultContext_AnalyzerReferencesNonCompilerAssemblyUsedByDefaultContext()\n {\n // Load the V2 of Delta to default ALC, then create a separate ALC for compiler and load compiler assembly.\n // Next use compiler context to load and run `AssemblyLoadingInNonDefaultContextHelper2` below. We expect the analyzer running in\n // its own `DirectoryLoadContext` would load and use Delta V1 located in its directory instead of V2 already loaded in the default context.\n _ = System.Runtime.Loader.AssemblyLoadContext.Default.LoadFromAssemblyPath(_testFixture.Delta2.Path);\n var compilerContext = new System.Runtime.Loader.AssemblyLoadContext(\"compilerContext\");\n _ = compilerContext.LoadFromAssemblyPath(typeof(DefaultAnalyzerAssemblyLoader).GetTypeInfo().Assembly.Location);\n\n var testAssembly = compilerContext.LoadFromAssemblyPath(typeof(DefaultAnalyzerAssemblyLoaderTests).GetTypeInfo().Assembly.Location);\n var testObject = testAssembly.CreateInstance(typeof(DefaultAnalyzerAssemblyLoaderTests).FullName!,\n ignoreCase: false, BindingFlags.Default, binder: null, args: new object[] { _output, _testFixture }, null, null)!;\n\n StringBuilder sb = new StringBuilder();\n testObject.GetType().GetMethod(nameof(AssemblyLoadingInNonDefaultContextHelper2), BindingFlags.Instance | BindingFlags.NonPublic)!.Invoke(testObject, new object[] { sb });\n Assert.Equal(\n@\"Delta: Hello\n\",\n sb.ToString());\n }\n\n private void AssemblyLoadingInNonDefaultContextHelper2(StringBuilder sb)\n {\n var loader = new DefaultAnalyzerAssemblyLoader();\n loader.AddDependencyLocation(_testFixture.AnalyzerReferencesDelta1.Path);\n loader.AddDependencyLocation(_testFixture.Delta1.Path);\n\n Assembly analyzerAssembly = loader.LoadFromPath(_testFixture.AnalyzerReferencesDelta1.Path);\n var analyzer = analyzerAssembly.CreateInstance(\"Analyzer\")!;\n analyzer.GetType().GetMethod(\"Method\")!.Invoke(analyzer, new object[] { sb });\n }\n#endif\n }\n}\n"},"label":{"kind":"number","value":1,"string":"1"}}},{"rowIdx":637,"cells":{"repo_name":{"kind":"string","value":"dotnet/roslyn"},"pr_number":{"kind":"number","value":56432,"string":"56,432"},"pr_title":{"kind":"string","value":"When we're loading dependencies, don't require exact versions"},"pr_description":{"kind":"string","value":"When we're loading analyzer dependencies, our current logic was to require the exact version that was requested from the loading assembly. This is problematic in a lot of cases where you would normally have a binding redirect to ensure assemblies load cleanly; by requiring exact versions we'd end up in diamond dependency cases where you couldn't practically produce an analyzer package that would cleanly load.\r\n\r\nWhile doing this change, @RikkiGibson and I noticed several other problems:\r\n\r\n1. There was an errant cache that was left in the .NET Core implementation, which meant that we'd sometimes reuse assemblies even when we were able to load them correctly. This has also been fixed as a prerequisite to the main fix, since otherwise it was difficult to prove that the behavior changes here weren't also going to impact the .NET Core implementation.\r\n2. There were some race conditions in the implementation.\r\n\r\n**REVIEWING COMMIT-AT-A-TIME IS HIGHLY RECOMMENDED**, since those changes are broken out to separate commits.\r\n\r\nFixes #53672\r\nFixes #56216"},"author":{"kind":"string","value":"jasonmalinowski"},"date_created":{"kind":"timestamp","value":"2021-09-16T01:19:09Z","string":"2021-09-16T01:19:09Z"},"date_merged":{"kind":"timestamp","value":"2021-11-30T03:29:47Z","string":"2021-11-30T03:29:47Z"},"previous_commit":{"kind":"string","value":"e302aa0555624495ca1644c8488ddf33c6a65686"},"pr_commit":{"kind":"string","value":"0bdc85394f139a23d8363a47635efa878112a95b"},"query":{"kind":"string","value":"When we're loading dependencies, don't require exact versions. When we're loading analyzer dependencies, our current logic was to require the exact version that was requested from the loading assembly. This is problematic in a lot of cases where you would normally have a binding redirect to ensure assemblies load cleanly; by requiring exact versions we'd end up in diamond dependency cases where you couldn't practically produce an analyzer package that would cleanly load.\r\n\r\nWhile doing this change, @RikkiGibson and I noticed several other problems:\r\n\r\n1. There was an errant cache that was left in the .NET Core implementation, which meant that we'd sometimes reuse assemblies even when we were able to load them correctly. This has also been fixed as a prerequisite to the main fix, since otherwise it was difficult to prove that the behavior changes here weren't also going to impact the .NET Core implementation.\r\n2. There were some race conditions in the implementation.\r\n\r\n**REVIEWING COMMIT-AT-A-TIME IS HIGHLY RECOMMENDED**, since those changes are broken out to separate commits.\r\n\r\nFixes #53672\r\nFixes #56216"},"filepath":{"kind":"string","value":"./src/Compilers/Core/Portable/DiagnosticAnalyzer/AnalyzerAssemblyLoader.cs"},"before_content":{"kind":"string","value":"// Licensed to the .NET Foundation under one or more agreements.\n// The .NET Foundation licenses this file to you under the MIT license.\n// See the LICENSE file in the project root for more information.\n\n#nullable disable\n\nusing System;\nusing System.Collections.Generic;\nusing System.Collections.Immutable;\nusing System.Diagnostics;\nusing System.Reflection;\nusing Roslyn.Utilities;\n\nnamespace Microsoft.CodeAnalysis\n{\n internal abstract class AnalyzerAssemblyLoader : IAnalyzerAssemblyLoader\n {\n private readonly object _guard = new();\n\n // lock _guard to read/write\n private readonly Dictionary _loadedAssembliesByPath = new();\n private readonly Dictionary _loadedAssemblyIdentitiesByPath = new();\n private readonly Dictionary _loadedAssembliesByIdentity = new();\n\n // maps file name to a full path (lock _guard to read/write):\n private readonly Dictionary> _knownAssemblyPathsBySimpleName = new(StringComparer.OrdinalIgnoreCase);\n\n protected abstract Assembly LoadFromPathImpl(string fullPath);\n\n #region Public API\n\n public void AddDependencyLocation(string fullPath)\n {\n CompilerPathUtilities.RequireAbsolutePath(fullPath, nameof(fullPath));\n string simpleName = PathUtilities.GetFileName(fullPath, includeExtension: false);\n\n lock (_guard)\n {\n if (!_knownAssemblyPathsBySimpleName.TryGetValue(simpleName, out var paths))\n {\n paths = new HashSet(PathUtilities.Comparer);\n _knownAssemblyPathsBySimpleName.Add(simpleName, paths);\n }\n\n paths.Add(fullPath);\n }\n }\n\n public Assembly LoadFromPath(string fullPath)\n {\n CompilerPathUtilities.RequireAbsolutePath(fullPath, nameof(fullPath));\n return LoadFromPathUnchecked(fullPath);\n }\n\n #endregion\n\n private Assembly LoadFromPathUnchecked(string fullPath)\n {\n return LoadFromPathUncheckedCore(fullPath);\n }\n\n private Assembly LoadFromPathUncheckedCore(string fullPath, AssemblyIdentity identity = null)\n {\n Debug.Assert(PathUtilities.IsAbsolute(fullPath));\n\n // Check if we have already loaded an assembly with the same identity or from the given path.\n Assembly loadedAssembly = null;\n lock (_guard)\n {\n if (_loadedAssembliesByPath.TryGetValue(fullPath, out var existingAssembly))\n {\n loadedAssembly = existingAssembly;\n }\n else\n {\n identity ??= GetOrAddAssemblyIdentity(fullPath);\n if (identity != null && _loadedAssembliesByIdentity.TryGetValue(identity, out existingAssembly))\n {\n loadedAssembly = existingAssembly;\n }\n }\n }\n\n // Otherwise, load the assembly.\n if (loadedAssembly == null)\n {\n loadedAssembly = LoadFromPathImpl(fullPath);\n }\n\n // Add the loaded assembly to both path and identity cache.\n return AddToCache(loadedAssembly, fullPath, identity);\n }\n\n private Assembly AddToCache(Assembly assembly, string fullPath, AssemblyIdentity identity)\n {\n Debug.Assert(PathUtilities.IsAbsolute(fullPath));\n Debug.Assert(assembly != null);\n\n identity = AddToCache(fullPath, identity ?? AssemblyIdentity.FromAssemblyDefinition(assembly));\n Debug.Assert(identity != null);\n\n lock (_guard)\n {\n // The same assembly may be loaded from two different full paths (e.g. when loaded from GAC, etc.),\n // or another thread might have loaded the assembly after we checked above.\n if (_loadedAssembliesByIdentity.TryGetValue(identity, out var existingAssembly))\n {\n assembly = existingAssembly;\n }\n else\n {\n _loadedAssembliesByIdentity.Add(identity, assembly);\n }\n\n // An assembly file might be replaced by another file with a different identity.\n // Last one wins.\n _loadedAssembliesByPath[fullPath] = assembly;\n\n return assembly;\n }\n }\n\n private AssemblyIdentity GetOrAddAssemblyIdentity(string fullPath)\n {\n Debug.Assert(PathUtilities.IsAbsolute(fullPath));\n\n lock (_guard)\n {\n if (_loadedAssemblyIdentitiesByPath.TryGetValue(fullPath, out var existingIdentity))\n {\n return existingIdentity;\n }\n }\n\n var identity = AssemblyIdentityUtils.TryGetAssemblyIdentity(fullPath);\n return AddToCache(fullPath, identity);\n }\n\n private AssemblyIdentity AddToCache(string fullPath, AssemblyIdentity identity)\n {\n lock (_guard)\n {\n if (_loadedAssemblyIdentitiesByPath.TryGetValue(fullPath, out var existingIdentity) && existingIdentity != null)\n {\n identity = existingIdentity;\n }\n else\n {\n _loadedAssemblyIdentitiesByPath[fullPath] = identity;\n }\n }\n\n return identity;\n }\n\n#nullable enable\n protected HashSet? GetPaths(string simpleName)\n {\n _knownAssemblyPathsBySimpleName.TryGetValue(simpleName, out var paths);\n return paths;\n }\n\n /// \n /// When overridden in a derived class, allows substituting an assembly path after we've\n /// identified the context to load an assembly in, but before the assembly is actually\n /// loaded from disk.\n /// \n protected virtual string GetPathToLoad(string fullPath)\n {\n return fullPath;\n }\n#nullable disable\n\n public Assembly Load(string displayName)\n {\n if (!AssemblyIdentity.TryParseDisplayName(displayName, out var requestedIdentity))\n {\n return null;\n }\n\n ImmutableArray candidatePaths;\n lock (_guard)\n {\n\n // First, check if this loader already loaded the requested assembly:\n if (_loadedAssembliesByIdentity.TryGetValue(requestedIdentity, out var existingAssembly))\n {\n return existingAssembly;\n }\n // Second, check if an assembly file of the same simple name was registered with the loader:\n if (!_knownAssemblyPathsBySimpleName.TryGetValue(requestedIdentity.Name, out var pathList))\n {\n return null;\n }\n\n Debug.Assert(pathList.Count > 0);\n candidatePaths = pathList.ToImmutableArray();\n }\n\n // Multiple assemblies of the same simple name but different identities might have been registered.\n // Load the one that matches the requested identity (if any).\n foreach (var candidatePath in candidatePaths)\n {\n var candidateIdentity = GetOrAddAssemblyIdentity(candidatePath);\n\n if (requestedIdentity.Equals(candidateIdentity))\n {\n return LoadFromPathUncheckedCore(candidatePath, candidateIdentity);\n }\n }\n\n return null;\n }\n }\n}\n"},"after_content":{"kind":"string","value":"// Licensed to the .NET Foundation under one or more agreements.\n// The .NET Foundation licenses this file to you under the MIT license.\n// See the LICENSE file in the project root for more information.\n\nusing System;\nusing System.Collections.Generic;\nusing System.Collections.Immutable;\nusing System.Diagnostics;\nusing System.Reflection;\nusing Roslyn.Utilities;\n\nnamespace Microsoft.CodeAnalysis\n{\n /// \n /// The base implementation for . This type provides caching and tracking of inputs given\n /// to .\n /// \n /// \n /// This type generally assumes that files on disk aren't changing, since it ensure that two calls to \n /// will always return the same thing, per that interface's contract.\n /// \n internal abstract class AnalyzerAssemblyLoader : IAnalyzerAssemblyLoader\n {\n private readonly object _guard = new();\n\n // lock _guard to read/write\n private readonly Dictionary _loadedAssembliesByPath = new();\n\n // maps file name to a full path (lock _guard to read/write):\n private readonly Dictionary> _knownAssemblyPathsBySimpleName = new(StringComparer.OrdinalIgnoreCase);\n\n /// \n /// Implemented by derived types to actually perform the load for an assembly that doesn't have a cached result.\n /// \n protected abstract Assembly LoadFromPathUncheckedImpl(string fullPath);\n\n #region Public API\n\n public void AddDependencyLocation(string fullPath)\n {\n CompilerPathUtilities.RequireAbsolutePath(fullPath, nameof(fullPath));\n string simpleName = PathUtilities.GetFileName(fullPath, includeExtension: false);\n\n lock (_guard)\n {\n if (!_knownAssemblyPathsBySimpleName.TryGetValue(simpleName, out var paths))\n {\n paths = ImmutableHashSet.Create(PathUtilities.Comparer, fullPath);\n _knownAssemblyPathsBySimpleName.Add(simpleName, paths);\n }\n else\n {\n _knownAssemblyPathsBySimpleName[simpleName] = paths.Add(fullPath);\n }\n }\n }\n\n public Assembly LoadFromPath(string fullPath)\n {\n CompilerPathUtilities.RequireAbsolutePath(fullPath, nameof(fullPath));\n return LoadFromPathUnchecked(fullPath);\n }\n\n #endregion\n\n /// \n /// Returns the cached assembly for fullPath if we've done a load for this path before, or calls if\n /// it needs to be loaded. This method skips the check in release builds that the path is an absolute path, hence the \"Unchecked\" in the name.\n /// \n protected Assembly LoadFromPathUnchecked(string fullPath)\n {\n Debug.Assert(PathUtilities.IsAbsolute(fullPath));\n\n // Check if we have already loaded an assembly from the given path.\n Assembly? loadedAssembly = null;\n lock (_guard)\n {\n if (_loadedAssembliesByPath.TryGetValue(fullPath, out var existingAssembly))\n {\n loadedAssembly = existingAssembly;\n }\n }\n\n // Otherwise, load the assembly.\n if (loadedAssembly == null)\n {\n loadedAssembly = LoadFromPathUncheckedImpl(fullPath);\n }\n\n // Add the loaded assembly to the path cache.\n lock (_guard)\n {\n _loadedAssembliesByPath[fullPath] = loadedAssembly;\n }\n\n return loadedAssembly;\n }\n\n protected ImmutableHashSet? GetPaths(string simpleName)\n {\n lock (_guard)\n {\n _knownAssemblyPathsBySimpleName.TryGetValue(simpleName, out var paths);\n return paths;\n }\n }\n\n /// \n /// When overridden in a derived class, allows substituting an assembly path after we've\n /// identified the context to load an assembly in, but before the assembly is actually\n /// loaded from disk. This is used to substitute out the original path with the shadow-copied version.\n /// \n protected virtual string GetPathToLoad(string fullPath)\n {\n return fullPath;\n }\n }\n}\n"},"label":{"kind":"number","value":1,"string":"1"}}},{"rowIdx":638,"cells":{"repo_name":{"kind":"string","value":"dotnet/roslyn"},"pr_number":{"kind":"number","value":56432,"string":"56,432"},"pr_title":{"kind":"string","value":"When we're loading dependencies, don't require exact versions"},"pr_description":{"kind":"string","value":"When we're loading analyzer dependencies, our current logic was to require the exact version that was requested from the loading assembly. This is problematic in a lot of cases where you would normally have a binding redirect to ensure assemblies load cleanly; by requiring exact versions we'd end up in diamond dependency cases where you couldn't practically produce an analyzer package that would cleanly load.\r\n\r\nWhile doing this change, @RikkiGibson and I noticed several other problems:\r\n\r\n1. There was an errant cache that was left in the .NET Core implementation, which meant that we'd sometimes reuse assemblies even when we were able to load them correctly. This has also been fixed as a prerequisite to the main fix, since otherwise it was difficult to prove that the behavior changes here weren't also going to impact the .NET Core implementation.\r\n2. There were some race conditions in the implementation.\r\n\r\n**REVIEWING COMMIT-AT-A-TIME IS HIGHLY RECOMMENDED**, since those changes are broken out to separate commits.\r\n\r\nFixes #53672\r\nFixes #56216"},"author":{"kind":"string","value":"jasonmalinowski"},"date_created":{"kind":"timestamp","value":"2021-09-16T01:19:09Z","string":"2021-09-16T01:19:09Z"},"date_merged":{"kind":"timestamp","value":"2021-11-30T03:29:47Z","string":"2021-11-30T03:29:47Z"},"previous_commit":{"kind":"string","value":"e302aa0555624495ca1644c8488ddf33c6a65686"},"pr_commit":{"kind":"string","value":"0bdc85394f139a23d8363a47635efa878112a95b"},"query":{"kind":"string","value":"When we're loading dependencies, don't require exact versions. When we're loading analyzer dependencies, our current logic was to require the exact version that was requested from the loading assembly. This is problematic in a lot of cases where you would normally have a binding redirect to ensure assemblies load cleanly; by requiring exact versions we'd end up in diamond dependency cases where you couldn't practically produce an analyzer package that would cleanly load.\r\n\r\nWhile doing this change, @RikkiGibson and I noticed several other problems:\r\n\r\n1. There was an errant cache that was left in the .NET Core implementation, which meant that we'd sometimes reuse assemblies even when we were able to load them correctly. This has also been fixed as a prerequisite to the main fix, since otherwise it was difficult to prove that the behavior changes here weren't also going to impact the .NET Core implementation.\r\n2. There were some race conditions in the implementation.\r\n\r\n**REVIEWING COMMIT-AT-A-TIME IS HIGHLY RECOMMENDED**, since those changes are broken out to separate commits.\r\n\r\nFixes #53672\r\nFixes #56216"},"filepath":{"kind":"string","value":"./src/Compilers/Core/Portable/DiagnosticAnalyzer/DefaultAnalyzerAssemblyLoader.Core.cs"},"before_content":{"kind":"string","value":"// Licensed to the .NET Foundation under one or more agreements.\n// The .NET Foundation licenses this file to you under the MIT license.\n// See the LICENSE file in the project root for more information.\n\n\n#if NETCOREAPP\n\nusing System;\nusing System.Collections.Generic;\nusing System.Collections.Immutable;\nusing System.Diagnostics;\nusing System.IO;\nusing System.Linq;\nusing System.Reflection;\nusing System.Runtime.Loader;\n\nnamespace Microsoft.CodeAnalysis\n{\n internal class DefaultAnalyzerAssemblyLoader : AnalyzerAssemblyLoader\n {\n /// \n ///
Typically a user analyzer has a reference to the compiler and some of the compiler's\n /// dependencies such as System.Collections.Immutable. For the analyzer to correctly\n /// interoperate with the compiler that created it, we need to ensure that we always use the\n /// compiler's version of a given assembly over the analyzer's version.
\n ///\n ///
If we neglect to do this, then in the case where the user ships the compiler or its\n /// dependencies in the analyzer's bin directory, we could end up loading a separate\n /// instance of those assemblies in the process of loading the analyzer, which will surface\n /// as a failure to load the analyzer.
\n /// \n internal static readonly ImmutableHashSet CompilerAssemblySimpleNames =\n ImmutableHashSet.Create(\n StringComparer.OrdinalIgnoreCase,\n \"Microsoft.CodeAnalysis\",\n \"Microsoft.CodeAnalysis.CSharp\",\n \"Microsoft.CodeAnalysis.VisualBasic\",\n \"System.Collections\",\n \"System.Collections.Concurrent\",\n \"System.Collections.Immutable\",\n \"System.Console\",\n \"System.Diagnostics.Debug\",\n \"System.Diagnostics.StackTrace\",\n \"System.Diagnostics.Tracing\",\n \"System.IO.Compression\",\n \"System.IO.FileSystem\",\n \"System.Linq\",\n \"System.Linq.Expressions\",\n \"System.Memory\",\n \"System.Reflection.Metadata\",\n \"System.Reflection.Primitives\",\n \"System.Resources.ResourceManager\",\n \"System.Runtime\",\n \"System.Runtime.CompilerServices.Unsafe\",\n \"System.Runtime.Extensions\",\n \"System.Runtime.InteropServices\",\n \"System.Runtime.Loader\",\n \"System.Runtime.Numerics\",\n \"System.Runtime.Serialization.Primitives\",\n \"System.Security.Cryptography.Algorithms\",\n \"System.Security.Cryptography.Primitives\",\n \"System.Text.Encoding.CodePages\",\n \"System.Text.Encoding.Extensions\",\n \"System.Text.RegularExpressions\",\n \"System.Threading\",\n \"System.Threading.Tasks\",\n \"System.Threading.Tasks.Parallel\",\n \"System.Threading.Thread\",\n \"System.Threading.ThreadPool\",\n \"System.Xml.ReaderWriter\",\n \"System.Xml.XDocument\",\n \"System.Xml.XPath.XDocument\");\n\n internal virtual ImmutableHashSet AssemblySimpleNamesToBeLoadedInCompilerContext => CompilerAssemblySimpleNames;\n\n // This is the context where compiler (and some of its dependencies) are being loaded into, which might be different from AssemblyLoadContext.Default.\n private static readonly AssemblyLoadContext s_compilerLoadContext = AssemblyLoadContext.GetLoadContext(typeof(DefaultAnalyzerAssemblyLoader).GetTypeInfo().Assembly)!;\n\n private readonly object _guard = new object();\n private readonly Dictionary _loadContextByDirectory = new Dictionary(StringComparer.Ordinal);\n\n protected override Assembly LoadFromPathImpl(string fullPath)\n {\n DirectoryLoadContext? loadContext;\n\n var fullDirectoryPath = Path.GetDirectoryName(fullPath) ?? throw new ArgumentException(message: null, paramName: nameof(fullPath));\n lock (_guard)\n {\n if (!_loadContextByDirectory.TryGetValue(fullDirectoryPath, out loadContext))\n {\n loadContext = new DirectoryLoadContext(fullDirectoryPath, this, s_compilerLoadContext);\n _loadContextByDirectory[fullDirectoryPath] = loadContext;\n }\n }\n\n var name = AssemblyName.GetAssemblyName(fullPath);\n return loadContext.LoadFromAssemblyName(name);\n }\n\n internal static class TestAccessor\n {\n public static AssemblyLoadContext[] GetOrderedLoadContexts(DefaultAnalyzerAssemblyLoader loader)\n {\n return loader._loadContextByDirectory.Values.OrderBy(v => v.Directory).ToArray();\n }\n }\n\n private sealed class DirectoryLoadContext : AssemblyLoadContext\n {\n internal string Directory { get; }\n private readonly DefaultAnalyzerAssemblyLoader _loader;\n private readonly AssemblyLoadContext _compilerLoadContext;\n\n public DirectoryLoadContext(string directory, DefaultAnalyzerAssemblyLoader loader, AssemblyLoadContext compilerLoadContext)\n {\n Directory = directory;\n _loader = loader;\n _compilerLoadContext = compilerLoadContext;\n }\n\n protected override Assembly? Load(AssemblyName assemblyName)\n {\n var simpleName = assemblyName.Name!;\n if (_loader.AssemblySimpleNamesToBeLoadedInCompilerContext.Contains(simpleName))\n {\n // Delegate to the compiler's load context to load the compiler or anything\n // referenced by the compiler\n return _compilerLoadContext.LoadFromAssemblyName(assemblyName);\n }\n\n var assemblyPath = Path.Combine(Directory, simpleName + \".dll\");\n var paths = _loader.GetPaths(simpleName);\n if (paths is null)\n {\n // The analyzer didn't explicitly register this dependency. Most likely the\n // assembly we're trying to load here is netstandard or a similar framework\n // assembly. In this case, we want to load it in compiler's ALC to avoid any \n // potential type mismatch issue. Otherwise, if this is truly an unknown assembly,\n // we assume both compiler and default ALC will fail to load it.\n return _compilerLoadContext.LoadFromAssemblyName(assemblyName);\n }\n\n Debug.Assert(paths.Any());\n // A matching assembly in this directory was specified via /analyzer.\n if (paths.Contains(assemblyPath))\n {\n return LoadFromAssemblyPath(_loader.GetPathToLoad(assemblyPath));\n }\n\n AssemblyName? bestCandidateName = null;\n string? bestCandidatePath = null;\n // The assembly isn't expected to be found at 'assemblyPath',\n // but some assembly with the same simple name is known to the loader.\n foreach (var candidatePath in paths)\n {\n // Note: we assume that the assembly really can be found at 'candidatePath'\n // (without 'GetPathToLoad'), and that calling GetAssemblyName doesn't cause us\n // to hold a lock on the file. This prevents unnecessary shadow copies.\n var candidateName = AssemblyName.GetAssemblyName(candidatePath);\n // Checking FullName ensures that version and PublicKeyToken match exactly.\n if (candidateName.FullName.Equals(assemblyName.FullName, StringComparison.OrdinalIgnoreCase))\n {\n return LoadFromAssemblyPath(_loader.GetPathToLoad(candidatePath));\n }\n else if (bestCandidateName is null || bestCandidateName.Version < candidateName.Version)\n {\n bestCandidateName = candidateName;\n bestCandidatePath = candidatePath;\n }\n }\n\n Debug.Assert(bestCandidateName != null);\n Debug.Assert(bestCandidatePath != null);\n\n return LoadFromAssemblyPath(_loader.GetPathToLoad(bestCandidatePath));\n }\n\n protected override IntPtr LoadUnmanagedDll(string unmanagedDllName)\n {\n var assemblyPath = Path.Combine(Directory, unmanagedDllName + \".dll\");\n var paths = _loader.GetPaths(unmanagedDllName);\n if (paths is null || !paths.Contains(assemblyPath))\n {\n return IntPtr.Zero;\n }\n\n var pathToLoad = _loader.GetPathToLoad(assemblyPath);\n return LoadUnmanagedDllFromPath(pathToLoad);\n }\n }\n }\n}\n\n#endif\n"},"after_content":{"kind":"string","value":"// Licensed to the .NET Foundation under one or more agreements.\n// The .NET Foundation licenses this file to you under the MIT license.\n// See the LICENSE file in the project root for more information.\n\n\n#if NETCOREAPP\n\nusing System;\nusing System.Collections.Generic;\nusing System.Collections.Immutable;\nusing System.Diagnostics;\nusing System.IO;\nusing System.Linq;\nusing System.Reflection;\nusing System.Runtime.Loader;\n\nnamespace Microsoft.CodeAnalysis\n{\n internal class DefaultAnalyzerAssemblyLoader : AnalyzerAssemblyLoader\n {\n /// \n ///
Typically a user analyzer has a reference to the compiler and some of the compiler's\n /// dependencies such as System.Collections.Immutable. For the analyzer to correctly\n /// interoperate with the compiler that created it, we need to ensure that we always use the\n /// compiler's version of a given assembly over the analyzer's version.
\n ///\n ///
If we neglect to do this, then in the case where the user ships the compiler or its\n /// dependencies in the analyzer's bin directory, we could end up loading a separate\n /// instance of those assemblies in the process of loading the analyzer, which will surface\n /// as a failure to load the analyzer.
\n /// \n internal static readonly ImmutableHashSet CompilerAssemblySimpleNames =\n ImmutableHashSet.Create(\n StringComparer.OrdinalIgnoreCase,\n \"Microsoft.CodeAnalysis\",\n \"Microsoft.CodeAnalysis.CSharp\",\n \"Microsoft.CodeAnalysis.VisualBasic\",\n \"System.Collections\",\n \"System.Collections.Concurrent\",\n \"System.Collections.Immutable\",\n \"System.Console\",\n \"System.Diagnostics.Debug\",\n \"System.Diagnostics.StackTrace\",\n \"System.Diagnostics.Tracing\",\n \"System.IO.Compression\",\n \"System.IO.FileSystem\",\n \"System.Linq\",\n \"System.Linq.Expressions\",\n \"System.Memory\",\n \"System.Reflection.Metadata\",\n \"System.Reflection.Primitives\",\n \"System.Resources.ResourceManager\",\n \"System.Runtime\",\n \"System.Runtime.CompilerServices.Unsafe\",\n \"System.Runtime.Extensions\",\n \"System.Runtime.InteropServices\",\n \"System.Runtime.Loader\",\n \"System.Runtime.Numerics\",\n \"System.Runtime.Serialization.Primitives\",\n \"System.Security.Cryptography.Algorithms\",\n \"System.Security.Cryptography.Primitives\",\n \"System.Text.Encoding.CodePages\",\n \"System.Text.Encoding.Extensions\",\n \"System.Text.RegularExpressions\",\n \"System.Threading\",\n \"System.Threading.Tasks\",\n \"System.Threading.Tasks.Parallel\",\n \"System.Threading.Thread\",\n \"System.Threading.ThreadPool\",\n \"System.Xml.ReaderWriter\",\n \"System.Xml.XDocument\",\n \"System.Xml.XPath.XDocument\");\n\n internal virtual ImmutableHashSet AssemblySimpleNamesToBeLoadedInCompilerContext => CompilerAssemblySimpleNames;\n\n // This is the context where compiler (and some of its dependencies) are being loaded into, which might be different from AssemblyLoadContext.Default.\n private static readonly AssemblyLoadContext s_compilerLoadContext = AssemblyLoadContext.GetLoadContext(typeof(DefaultAnalyzerAssemblyLoader).GetTypeInfo().Assembly)!;\n\n private readonly object _guard = new object();\n private readonly Dictionary _loadContextByDirectory = new Dictionary(StringComparer.Ordinal);\n\n protected override Assembly LoadFromPathUncheckedImpl(string fullPath)\n {\n DirectoryLoadContext? loadContext;\n\n var fullDirectoryPath = Path.GetDirectoryName(fullPath) ?? throw new ArgumentException(message: null, paramName: nameof(fullPath));\n lock (_guard)\n {\n if (!_loadContextByDirectory.TryGetValue(fullDirectoryPath, out loadContext))\n {\n loadContext = new DirectoryLoadContext(fullDirectoryPath, this, s_compilerLoadContext);\n _loadContextByDirectory[fullDirectoryPath] = loadContext;\n }\n }\n\n var name = AssemblyName.GetAssemblyName(fullPath);\n return loadContext.LoadFromAssemblyName(name);\n }\n\n internal static class TestAccessor\n {\n public static AssemblyLoadContext[] GetOrderedLoadContexts(DefaultAnalyzerAssemblyLoader loader)\n {\n return loader._loadContextByDirectory.Values.OrderBy(v => v.Directory).ToArray();\n }\n }\n\n private sealed class DirectoryLoadContext : AssemblyLoadContext\n {\n internal string Directory { get; }\n private readonly DefaultAnalyzerAssemblyLoader _loader;\n private readonly AssemblyLoadContext _compilerLoadContext;\n\n public DirectoryLoadContext(string directory, DefaultAnalyzerAssemblyLoader loader, AssemblyLoadContext compilerLoadContext)\n {\n Directory = directory;\n _loader = loader;\n _compilerLoadContext = compilerLoadContext;\n }\n\n protected override Assembly? Load(AssemblyName assemblyName)\n {\n var simpleName = assemblyName.Name!;\n if (_loader.AssemblySimpleNamesToBeLoadedInCompilerContext.Contains(simpleName))\n {\n // Delegate to the compiler's load context to load the compiler or anything\n // referenced by the compiler\n return _compilerLoadContext.LoadFromAssemblyName(assemblyName);\n }\n\n var assemblyPath = Path.Combine(Directory, simpleName + \".dll\");\n var paths = _loader.GetPaths(simpleName);\n if (paths is null)\n {\n // The analyzer didn't explicitly register this dependency. Most likely the\n // assembly we're trying to load here is netstandard or a similar framework\n // assembly. In this case, we want to load it in compiler's ALC to avoid any \n // potential type mismatch issue. Otherwise, if this is truly an unknown assembly,\n // we assume both compiler and default ALC will fail to load it.\n return _compilerLoadContext.LoadFromAssemblyName(assemblyName);\n }\n\n Debug.Assert(paths.Any());\n // A matching assembly in this directory was specified via /analyzer.\n if (paths.Contains(assemblyPath))\n {\n return LoadFromAssemblyPath(_loader.GetPathToLoad(assemblyPath));\n }\n\n AssemblyName? bestCandidateName = null;\n string? bestCandidatePath = null;\n // The assembly isn't expected to be found at 'assemblyPath',\n // but some assembly with the same simple name is known to the loader.\n foreach (var candidatePath in paths)\n {\n // Note: we assume that the assembly really can be found at 'candidatePath'\n // (without 'GetPathToLoad'), and that calling GetAssemblyName doesn't cause us\n // to hold a lock on the file. This prevents unnecessary shadow copies.\n var candidateName = AssemblyName.GetAssemblyName(candidatePath);\n // Checking FullName ensures that version and PublicKeyToken match exactly.\n if (candidateName.FullName.Equals(assemblyName.FullName, StringComparison.OrdinalIgnoreCase))\n {\n return LoadFromAssemblyPath(_loader.GetPathToLoad(candidatePath));\n }\n else if (bestCandidateName is null || bestCandidateName.Version < candidateName.Version)\n {\n bestCandidateName = candidateName;\n bestCandidatePath = candidatePath;\n }\n }\n\n Debug.Assert(bestCandidateName != null);\n Debug.Assert(bestCandidatePath != null);\n\n return LoadFromAssemblyPath(_loader.GetPathToLoad(bestCandidatePath));\n }\n\n protected override IntPtr LoadUnmanagedDll(string unmanagedDllName)\n {\n var assemblyPath = Path.Combine(Directory, unmanagedDllName + \".dll\");\n var paths = _loader.GetPaths(unmanagedDllName);\n if (paths is null || !paths.Contains(assemblyPath))\n {\n return IntPtr.Zero;\n }\n\n var pathToLoad = _loader.GetPathToLoad(assemblyPath);\n return LoadUnmanagedDllFromPath(pathToLoad);\n }\n }\n }\n}\n\n#endif\n"},"label":{"kind":"number","value":1,"string":"1"}}},{"rowIdx":639,"cells":{"repo_name":{"kind":"string","value":"dotnet/roslyn"},"pr_number":{"kind":"number","value":56432,"string":"56,432"},"pr_title":{"kind":"string","value":"When we're loading dependencies, don't require exact versions"},"pr_description":{"kind":"string","value":"When we're loading analyzer dependencies, our current logic was to require the exact version that was requested from the loading assembly. This is problematic in a lot of cases where you would normally have a binding redirect to ensure assemblies load cleanly; by requiring exact versions we'd end up in diamond dependency cases where you couldn't practically produce an analyzer package that would cleanly load.\r\n\r\nWhile doing this change, @RikkiGibson and I noticed several other problems:\r\n\r\n1. There was an errant cache that was left in the .NET Core implementation, which meant that we'd sometimes reuse assemblies even when we were able to load them correctly. This has also been fixed as a prerequisite to the main fix, since otherwise it was difficult to prove that the behavior changes here weren't also going to impact the .NET Core implementation.\r\n2. There were some race conditions in the implementation.\r\n\r\n**REVIEWING COMMIT-AT-A-TIME IS HIGHLY RECOMMENDED**, since those changes are broken out to separate commits.\r\n\r\nFixes #53672\r\nFixes #56216"},"author":{"kind":"string","value":"jasonmalinowski"},"date_created":{"kind":"timestamp","value":"2021-09-16T01:19:09Z","string":"2021-09-16T01:19:09Z"},"date_merged":{"kind":"timestamp","value":"2021-11-30T03:29:47Z","string":"2021-11-30T03:29:47Z"},"previous_commit":{"kind":"string","value":"e302aa0555624495ca1644c8488ddf33c6a65686"},"pr_commit":{"kind":"string","value":"0bdc85394f139a23d8363a47635efa878112a95b"},"query":{"kind":"string","value":"When we're loading dependencies, don't require exact versions. When we're loading analyzer dependencies, our current logic was to require the exact version that was requested from the loading assembly. This is problematic in a lot of cases where you would normally have a binding redirect to ensure assemblies load cleanly; by requiring exact versions we'd end up in diamond dependency cases where you couldn't practically produce an analyzer package that would cleanly load.\r\n\r\nWhile doing this change, @RikkiGibson and I noticed several other problems:\r\n\r\n1. There was an errant cache that was left in the .NET Core implementation, which meant that we'd sometimes reuse assemblies even when we were able to load them correctly. This has also been fixed as a prerequisite to the main fix, since otherwise it was difficult to prove that the behavior changes here weren't also going to impact the .NET Core implementation.\r\n2. There were some race conditions in the implementation.\r\n\r\n**REVIEWING COMMIT-AT-A-TIME IS HIGHLY RECOMMENDED**, since those changes are broken out to separate commits.\r\n\r\nFixes #53672\r\nFixes #56216"},"filepath":{"kind":"string","value":"./src/Compilers/Core/Portable/DiagnosticAnalyzer/DefaultAnalyzerAssemblyLoader.Desktop.cs"},"before_content":{"kind":"string","value":"// Licensed to the .NET Foundation under one or more agreements.\n// The .NET Foundation licenses this file to you under the MIT license.\n// See the LICENSE file in the project root for more information.\n\n#nullable disable\n\n#if !NETCOREAPP\n\nusing System;\nusing System.Reflection;\nusing System.Threading;\n\nnamespace Microsoft.CodeAnalysis\n{\n /// \n /// Loads analyzer assemblies from their original locations in the file system.\n /// Assemblies will only be loaded from the locations specified when the loader\n /// is instantiated.\n /// \n /// \n /// This type is meant to be used in scenarios where it is OK for the analyzer\n /// assemblies to be locked on disk for the lifetime of the host; for example,\n /// csc.exe and vbc.exe. In scenarios where support for updating or deleting\n /// the analyzer on disk is required a different loader should be used.\n /// \n internal class DefaultAnalyzerAssemblyLoader : AnalyzerAssemblyLoader\n {\n private int _hookedAssemblyResolve;\n\n protected override Assembly LoadFromPathImpl(string fullPath)\n {\n if (Interlocked.CompareExchange(ref _hookedAssemblyResolve, 0, 1) == 0)\n {\n AppDomain.CurrentDomain.AssemblyResolve += CurrentDomain_AssemblyResolve;\n }\n\n var pathToLoad = GetPathToLoad(fullPath);\n return Assembly.LoadFrom(pathToLoad);\n }\n\n private Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args)\n {\n try\n {\n return Load(AppDomain.CurrentDomain.ApplyPolicy(args.Name));\n }\n catch\n {\n return null;\n }\n }\n }\n}\n\n#endif\n"},"after_content":{"kind":"string","value":"// Licensed to the .NET Foundation under one or more agreements.\n// The .NET Foundation licenses this file to you under the MIT license.\n// See the LICENSE file in the project root for more information.\n\n#if !NETCOREAPP\n\nusing System;\nusing System.Collections.Generic;\nusing System.Collections.Immutable;\nusing System.Diagnostics;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Linq;\nusing System.Reflection;\nusing System.Threading;\nusing Roslyn.Utilities;\n\nnamespace Microsoft.CodeAnalysis\n{\n /// \n /// Loads analyzer assemblies from their original locations in the file system.\n /// Assemblies will only be loaded from the locations specified when the loader\n /// is instantiated.\n /// \n /// \n /// This type is meant to be used in scenarios where it is OK for the analyzer\n /// assemblies to be locked on disk for the lifetime of the host; for example,\n /// csc.exe and vbc.exe. In scenarios where support for updating or deleting\n /// the analyzer on disk is required a different loader should be used.\n /// \n internal class DefaultAnalyzerAssemblyLoader : AnalyzerAssemblyLoader\n {\n private readonly object _guard = new();\n\n private readonly Dictionary _loadedAssembliesByIdentity = new();\n private readonly Dictionary _loadedAssemblyIdentitiesByPath = new();\n\n private int _hookedAssemblyResolve;\n\n protected override Assembly LoadFromPathUncheckedImpl(string fullPath)\n {\n if (Interlocked.CompareExchange(ref _hookedAssemblyResolve, 0, 1) == 0)\n {\n AppDomain.CurrentDomain.AssemblyResolve += CurrentDomain_AssemblyResolve;\n }\n\n AssemblyIdentity? identity;\n\n lock (_guard)\n {\n identity = GetOrAddAssemblyIdentity(fullPath);\n if (identity != null && _loadedAssembliesByIdentity.TryGetValue(identity, out var existingAssembly))\n {\n return existingAssembly;\n }\n }\n\n var pathToLoad = GetPathToLoad(fullPath);\n var loadedAssembly = Assembly.LoadFrom(pathToLoad);\n\n lock (_guard)\n {\n identity ??= identity ?? AssemblyIdentity.FromAssemblyDefinition(loadedAssembly);\n\n // The same assembly may be loaded from two different full paths (e.g. when loaded from GAC, etc.),\n // or another thread might have loaded the assembly after we checked above.\n if (_loadedAssembliesByIdentity.TryGetValue(identity, out var existingAssembly))\n {\n loadedAssembly = existingAssembly;\n }\n else\n {\n _loadedAssembliesByIdentity.Add(identity, loadedAssembly);\n }\n\n return loadedAssembly;\n }\n }\n\n private Assembly? CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args)\n {\n // In the .NET Framework, if a handler to AssemblyResolve throws an exception, other handlers\n // are not called. To avoid any bug in our handler breaking other handlers running in the same process\n // we catch exceptions here. We do not expect exceptions to be thrown though.\n try\n {\n return GetOrLoad(AppDomain.CurrentDomain.ApplyPolicy(args.Name));\n }\n catch\n {\n return null;\n }\n }\n\n private AssemblyIdentity? GetOrAddAssemblyIdentity(string fullPath)\n {\n Debug.Assert(PathUtilities.IsAbsolute(fullPath));\n\n lock (_guard)\n {\n if (_loadedAssemblyIdentitiesByPath.TryGetValue(fullPath, out var existingIdentity))\n {\n return existingIdentity;\n }\n }\n\n var identity = AssemblyIdentityUtils.TryGetAssemblyIdentity(fullPath);\n\n lock (_guard)\n {\n if (_loadedAssemblyIdentitiesByPath.TryGetValue(fullPath, out var existingIdentity) && existingIdentity != null)\n {\n // Somebody else beat us, so used the cached value\n identity = existingIdentity;\n }\n else\n {\n _loadedAssemblyIdentitiesByPath[fullPath] = identity;\n }\n }\n\n return identity;\n }\n\n private Assembly? GetOrLoad(string displayName)\n {\n if (!AssemblyIdentity.TryParseDisplayName(displayName, out var requestedIdentity))\n {\n return null;\n }\n\n ImmutableHashSet candidatePaths;\n lock (_guard)\n {\n\n // First, check if this loader already loaded the requested assembly:\n if (_loadedAssembliesByIdentity.TryGetValue(requestedIdentity, out var existingAssembly))\n {\n return existingAssembly;\n }\n // Second, check if an assembly file of the same simple name was registered with the loader:\n candidatePaths = GetPaths(requestedIdentity.Name);\n if (candidatePaths is null)\n {\n return null;\n }\n\n Debug.Assert(candidatePaths.Count > 0);\n }\n\n // Find the highest version that satisfies the original request. We'll match for the highest version we can, assuming it\n // actually matches the original request\n string? bestPath = null;\n Version? bestIdentityVersion = null;\n\n // Sort the candidate paths by ordinal, to ensure determinism with the same inputs if you were to have multiple assemblies\n // providing the same version.\n foreach (var candidatePath in candidatePaths.OrderBy(StringComparer.Ordinal))\n {\n var candidateIdentity = GetOrAddAssemblyIdentity(candidatePath);\n\n if (candidateIdentity is not null &&\n candidateIdentity.Version >= requestedIdentity.Version &&\n candidateIdentity.PublicKeyToken.SequenceEqual(requestedIdentity.PublicKeyToken))\n {\n if (bestIdentityVersion is null || candidateIdentity.Version > bestIdentityVersion)\n {\n bestPath = candidatePath;\n bestIdentityVersion = candidateIdentity.Version;\n }\n }\n }\n\n if (bestPath != null)\n {\n return LoadFromPathUnchecked(bestPath);\n }\n\n return null;\n }\n }\n}\n\n#endif\n"},"label":{"kind":"number","value":1,"string":"1"}}},{"rowIdx":640,"cells":{"repo_name":{"kind":"string","value":"dotnet/roslyn"},"pr_number":{"kind":"number","value":56432,"string":"56,432"},"pr_title":{"kind":"string","value":"When we're loading dependencies, don't require exact versions"},"pr_description":{"kind":"string","value":"When we're loading analyzer dependencies, our current logic was to require the exact version that was requested from the loading assembly. This is problematic in a lot of cases where you would normally have a binding redirect to ensure assemblies load cleanly; by requiring exact versions we'd end up in diamond dependency cases where you couldn't practically produce an analyzer package that would cleanly load.\r\n\r\nWhile doing this change, @RikkiGibson and I noticed several other problems:\r\n\r\n1. There was an errant cache that was left in the .NET Core implementation, which meant that we'd sometimes reuse assemblies even when we were able to load them correctly. This has also been fixed as a prerequisite to the main fix, since otherwise it was difficult to prove that the behavior changes here weren't also going to impact the .NET Core implementation.\r\n2. There were some race conditions in the implementation.\r\n\r\n**REVIEWING COMMIT-AT-A-TIME IS HIGHLY RECOMMENDED**, since those changes are broken out to separate commits.\r\n\r\nFixes #53672\r\nFixes #56216"},"author":{"kind":"string","value":"jasonmalinowski"},"date_created":{"kind":"timestamp","value":"2021-09-16T01:19:09Z","string":"2021-09-16T01:19:09Z"},"date_merged":{"kind":"timestamp","value":"2021-11-30T03:29:47Z","string":"2021-11-30T03:29:47Z"},"previous_commit":{"kind":"string","value":"e302aa0555624495ca1644c8488ddf33c6a65686"},"pr_commit":{"kind":"string","value":"0bdc85394f139a23d8363a47635efa878112a95b"},"query":{"kind":"string","value":"When we're loading dependencies, don't require exact versions. When we're loading analyzer dependencies, our current logic was to require the exact version that was requested from the loading assembly. This is problematic in a lot of cases where you would normally have a binding redirect to ensure assemblies load cleanly; by requiring exact versions we'd end up in diamond dependency cases where you couldn't practically produce an analyzer package that would cleanly load.\r\n\r\nWhile doing this change, @RikkiGibson and I noticed several other problems:\r\n\r\n1. There was an errant cache that was left in the .NET Core implementation, which meant that we'd sometimes reuse assemblies even when we were able to load them correctly. This has also been fixed as a prerequisite to the main fix, since otherwise it was difficult to prove that the behavior changes here weren't also going to impact the .NET Core implementation.\r\n2. There were some race conditions in the implementation.\r\n\r\n**REVIEWING COMMIT-AT-A-TIME IS HIGHLY RECOMMENDED**, since those changes are broken out to separate commits.\r\n\r\nFixes #53672\r\nFixes #56216"},"filepath":{"kind":"string","value":"./src/Compilers/Core/Portable/DiagnosticAnalyzer/ShadowCopyAnalyzerAssemblyLoader.cs"},"before_content":{"kind":"string","value":"// Licensed to the .NET Foundation under one or more agreements.\n// The .NET Foundation licenses this file to you under the MIT license.\n// See the LICENSE file in the project root for more information.\n\n#nullable disable\n\nusing System;\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Reflection;\nusing System.Threading;\nusing System.Threading.Tasks;\n\nnamespace Microsoft.CodeAnalysis\n{\n internal sealed class ShadowCopyAnalyzerAssemblyLoader : DefaultAnalyzerAssemblyLoader\n {\n /// \n /// The base directory for shadow copies. Each instance of\n /// gets its own\n /// subdirectory under this directory. This is also the starting point\n /// for scavenge operations.\n /// \n private readonly string _baseDirectory;\n\n internal readonly Task DeleteLeftoverDirectoriesTask;\n\n /// \n /// The directory where this instance of \n /// will shadow-copy assemblies, and the mutex created to mark that the owner of it is still active.\n /// \n private readonly Lazy<(string directory, Mutex)> _shadowCopyDirectoryAndMutex;\n\n /// \n /// Used to generate unique names for per-assembly directories. Should be updated with .\n /// \n private int _assemblyDirectoryId;\n\n public ShadowCopyAnalyzerAssemblyLoader(string baseDirectory = null)\n {\n if (baseDirectory != null)\n {\n _baseDirectory = baseDirectory;\n }\n else\n {\n _baseDirectory = Path.Combine(Path.GetTempPath(), \"CodeAnalysis\", \"AnalyzerShadowCopies\");\n }\n\n _shadowCopyDirectoryAndMutex = new Lazy<(string directory, Mutex)>(\n () => CreateUniqueDirectoryForProcess(), LazyThreadSafetyMode.ExecutionAndPublication);\n\n DeleteLeftoverDirectoriesTask = Task.Run(DeleteLeftoverDirectories);\n }\n\n private void DeleteLeftoverDirectories()\n {\n // Avoid first chance exception\n if (!Directory.Exists(_baseDirectory))\n return;\n\n IEnumerable subDirectories;\n try\n {\n subDirectories = Directory.EnumerateDirectories(_baseDirectory);\n }\n catch (DirectoryNotFoundException)\n {\n return;\n }\n\n foreach (var subDirectory in subDirectories)\n {\n string name = Path.GetFileName(subDirectory).ToLowerInvariant();\n Mutex mutex = null;\n try\n {\n // We only want to try deleting the directory if no-one else is currently\n // using it. That is, if there is no corresponding mutex.\n if (!Mutex.TryOpenExisting(name, out mutex))\n {\n ClearReadOnlyFlagOnFiles(subDirectory);\n Directory.Delete(subDirectory, recursive: true);\n }\n }\n catch\n {\n // If something goes wrong we will leave it to the next run to clean up.\n // Just swallow the exception and move on.\n }\n finally\n {\n if (mutex != null)\n {\n mutex.Dispose();\n }\n }\n }\n }\n\n#nullable enable\n protected override string GetPathToLoad(string fullPath)\n {\n string assemblyDirectory = CreateUniqueDirectoryForAssembly();\n string shadowCopyPath = CopyFileAndResources(fullPath, assemblyDirectory);\n return shadowCopyPath;\n }\n#nullable disable\n\n private static string CopyFileAndResources(string fullPath, string assemblyDirectory)\n {\n string fileNameWithExtension = Path.GetFileName(fullPath);\n string shadowCopyPath = Path.Combine(assemblyDirectory, fileNameWithExtension);\n\n CopyFile(fullPath, shadowCopyPath);\n\n string originalDirectory = Path.GetDirectoryName(fullPath);\n string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(fileNameWithExtension);\n string resourcesNameWithoutExtension = fileNameWithoutExtension + \".resources\";\n string resourcesNameWithExtension = resourcesNameWithoutExtension + \".dll\";\n\n foreach (var directory in Directory.EnumerateDirectories(originalDirectory))\n {\n string directoryName = Path.GetFileName(directory);\n\n string resourcesPath = Path.Combine(directory, resourcesNameWithExtension);\n if (File.Exists(resourcesPath))\n {\n string resourcesShadowCopyPath = Path.Combine(assemblyDirectory, directoryName, resourcesNameWithExtension);\n CopyFile(resourcesPath, resourcesShadowCopyPath);\n }\n\n resourcesPath = Path.Combine(directory, resourcesNameWithoutExtension, resourcesNameWithExtension);\n if (File.Exists(resourcesPath))\n {\n string resourcesShadowCopyPath = Path.Combine(assemblyDirectory, directoryName, resourcesNameWithoutExtension, resourcesNameWithExtension);\n CopyFile(resourcesPath, resourcesShadowCopyPath);\n }\n }\n\n return shadowCopyPath;\n }\n\n private static void CopyFile(string originalPath, string shadowCopyPath)\n {\n var directory = Path.GetDirectoryName(shadowCopyPath);\n Directory.CreateDirectory(directory);\n\n File.Copy(originalPath, shadowCopyPath);\n\n ClearReadOnlyFlagOnFile(new FileInfo(shadowCopyPath));\n }\n\n private static void ClearReadOnlyFlagOnFiles(string directoryPath)\n {\n DirectoryInfo directory = new DirectoryInfo(directoryPath);\n\n foreach (var file in directory.EnumerateFiles(searchPattern: \"*\", searchOption: SearchOption.AllDirectories))\n {\n ClearReadOnlyFlagOnFile(file);\n }\n }\n\n private static void ClearReadOnlyFlagOnFile(FileInfo fileInfo)\n {\n try\n {\n if (fileInfo.IsReadOnly)\n {\n fileInfo.IsReadOnly = false;\n }\n }\n catch\n {\n // There are many reasons this could fail. Ignore it and keep going.\n }\n }\n\n private string CreateUniqueDirectoryForAssembly()\n {\n int directoryId = Interlocked.Increment(ref _assemblyDirectoryId);\n\n string directory = Path.Combine(_shadowCopyDirectoryAndMutex.Value.directory, directoryId.ToString());\n\n Directory.CreateDirectory(directory);\n return directory;\n }\n\n private (string directory, Mutex mutex) CreateUniqueDirectoryForProcess()\n {\n string guid = Guid.NewGuid().ToString(\"N\").ToLowerInvariant();\n string directory = Path.Combine(_baseDirectory, guid);\n\n var mutex = new Mutex(initiallyOwned: false, name: guid);\n\n Directory.CreateDirectory(directory);\n\n return (directory, mutex);\n }\n }\n}\n"},"after_content":{"kind":"string","value":"// Licensed to the .NET Foundation under one or more agreements.\n// The .NET Foundation licenses this file to you under the MIT license.\n// See the LICENSE file in the project root for more information.\n\nusing System;\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Threading;\nusing System.Threading.Tasks;\n\nnamespace Microsoft.CodeAnalysis\n{\n internal sealed class ShadowCopyAnalyzerAssemblyLoader : DefaultAnalyzerAssemblyLoader\n {\n /// \n /// The base directory for shadow copies. Each instance of\n /// gets its own\n /// subdirectory under this directory. This is also the starting point\n /// for scavenge operations.\n /// \n private readonly string _baseDirectory;\n\n internal readonly Task DeleteLeftoverDirectoriesTask;\n\n /// \n /// The directory where this instance of \n /// will shadow-copy assemblies, and the mutex created to mark that the owner of it is still active.\n /// \n private readonly Lazy<(string directory, Mutex)> _shadowCopyDirectoryAndMutex;\n\n /// \n /// Used to generate unique names for per-assembly directories. Should be updated with .\n /// \n private int _assemblyDirectoryId;\n\n public ShadowCopyAnalyzerAssemblyLoader(string? baseDirectory = null)\n {\n if (baseDirectory != null)\n {\n _baseDirectory = baseDirectory;\n }\n else\n {\n _baseDirectory = Path.Combine(Path.GetTempPath(), \"CodeAnalysis\", \"AnalyzerShadowCopies\");\n }\n\n _shadowCopyDirectoryAndMutex = new Lazy<(string directory, Mutex)>(\n () => CreateUniqueDirectoryForProcess(), LazyThreadSafetyMode.ExecutionAndPublication);\n\n DeleteLeftoverDirectoriesTask = Task.Run(DeleteLeftoverDirectories);\n }\n\n private void DeleteLeftoverDirectories()\n {\n // Avoid first chance exception\n if (!Directory.Exists(_baseDirectory))\n return;\n\n IEnumerable subDirectories;\n try\n {\n subDirectories = Directory.EnumerateDirectories(_baseDirectory);\n }\n catch (DirectoryNotFoundException)\n {\n return;\n }\n\n foreach (var subDirectory in subDirectories)\n {\n string name = Path.GetFileName(subDirectory).ToLowerInvariant();\n Mutex? mutex = null;\n try\n {\n // We only want to try deleting the directory if no-one else is currently\n // using it. That is, if there is no corresponding mutex.\n if (!Mutex.TryOpenExisting(name, out mutex))\n {\n ClearReadOnlyFlagOnFiles(subDirectory);\n Directory.Delete(subDirectory, recursive: true);\n }\n }\n catch\n {\n // If something goes wrong we will leave it to the next run to clean up.\n // Just swallow the exception and move on.\n }\n finally\n {\n if (mutex != null)\n {\n mutex.Dispose();\n }\n }\n }\n }\n\n protected override string GetPathToLoad(string fullPath)\n {\n string assemblyDirectory = CreateUniqueDirectoryForAssembly();\n string shadowCopyPath = CopyFileAndResources(fullPath, assemblyDirectory);\n return shadowCopyPath;\n }\n\n private static string CopyFileAndResources(string fullPath, string assemblyDirectory)\n {\n string fileNameWithExtension = Path.GetFileName(fullPath);\n string shadowCopyPath = Path.Combine(assemblyDirectory, fileNameWithExtension);\n\n CopyFile(fullPath, shadowCopyPath);\n\n string originalDirectory = Path.GetDirectoryName(fullPath)!;\n string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(fileNameWithExtension);\n string resourcesNameWithoutExtension = fileNameWithoutExtension + \".resources\";\n string resourcesNameWithExtension = resourcesNameWithoutExtension + \".dll\";\n\n foreach (var directory in Directory.EnumerateDirectories(originalDirectory))\n {\n string directoryName = Path.GetFileName(directory);\n\n string resourcesPath = Path.Combine(directory, resourcesNameWithExtension);\n if (File.Exists(resourcesPath))\n {\n string resourcesShadowCopyPath = Path.Combine(assemblyDirectory, directoryName, resourcesNameWithExtension);\n CopyFile(resourcesPath, resourcesShadowCopyPath);\n }\n\n resourcesPath = Path.Combine(directory, resourcesNameWithoutExtension, resourcesNameWithExtension);\n if (File.Exists(resourcesPath))\n {\n string resourcesShadowCopyPath = Path.Combine(assemblyDirectory, directoryName, resourcesNameWithoutExtension, resourcesNameWithExtension);\n CopyFile(resourcesPath, resourcesShadowCopyPath);\n }\n }\n\n return shadowCopyPath;\n }\n\n private static void CopyFile(string originalPath, string shadowCopyPath)\n {\n var directory = Path.GetDirectoryName(shadowCopyPath);\n Directory.CreateDirectory(directory);\n\n File.Copy(originalPath, shadowCopyPath);\n\n ClearReadOnlyFlagOnFile(new FileInfo(shadowCopyPath));\n }\n\n private static void ClearReadOnlyFlagOnFiles(string directoryPath)\n {\n DirectoryInfo directory = new DirectoryInfo(directoryPath);\n\n foreach (var file in directory.EnumerateFiles(searchPattern: \"*\", searchOption: SearchOption.AllDirectories))\n {\n ClearReadOnlyFlagOnFile(file);\n }\n }\n\n private static void ClearReadOnlyFlagOnFile(FileInfo fileInfo)\n {\n try\n {\n if (fileInfo.IsReadOnly)\n {\n fileInfo.IsReadOnly = false;\n }\n }\n catch\n {\n // There are many reasons this could fail. Ignore it and keep going.\n }\n }\n\n private string CreateUniqueDirectoryForAssembly()\n {\n int directoryId = Interlocked.Increment(ref _assemblyDirectoryId);\n\n string directory = Path.Combine(_shadowCopyDirectoryAndMutex.Value.directory, directoryId.ToString());\n\n Directory.CreateDirectory(directory);\n return directory;\n }\n\n private (string directory, Mutex mutex) CreateUniqueDirectoryForProcess()\n {\n string guid = Guid.NewGuid().ToString(\"N\").ToLowerInvariant();\n string directory = Path.Combine(_baseDirectory, guid);\n\n var mutex = new Mutex(initiallyOwned: false, name: guid);\n\n Directory.CreateDirectory(directory);\n\n return (directory, mutex);\n }\n }\n}\n"},"label":{"kind":"number","value":1,"string":"1"}}},{"rowIdx":641,"cells":{"repo_name":{"kind":"string","value":"dotnet/roslyn"},"pr_number":{"kind":"number","value":56432,"string":"56,432"},"pr_title":{"kind":"string","value":"When we're loading dependencies, don't require exact versions"},"pr_description":{"kind":"string","value":"When we're loading analyzer dependencies, our current logic was to require the exact version that was requested from the loading assembly. This is problematic in a lot of cases where you would normally have a binding redirect to ensure assemblies load cleanly; by requiring exact versions we'd end up in diamond dependency cases where you couldn't practically produce an analyzer package that would cleanly load.\r\n\r\nWhile doing this change, @RikkiGibson and I noticed several other problems:\r\n\r\n1. There was an errant cache that was left in the .NET Core implementation, which meant that we'd sometimes reuse assemblies even when we were able to load them correctly. This has also been fixed as a prerequisite to the main fix, since otherwise it was difficult to prove that the behavior changes here weren't also going to impact the .NET Core implementation.\r\n2. There were some race conditions in the implementation.\r\n\r\n**REVIEWING COMMIT-AT-A-TIME IS HIGHLY RECOMMENDED**, since those changes are broken out to separate commits.\r\n\r\nFixes #53672\r\nFixes #56216"},"author":{"kind":"string","value":"jasonmalinowski"},"date_created":{"kind":"timestamp","value":"2021-09-16T01:19:09Z","string":"2021-09-16T01:19:09Z"},"date_merged":{"kind":"timestamp","value":"2021-11-30T03:29:47Z","string":"2021-11-30T03:29:47Z"},"previous_commit":{"kind":"string","value":"e302aa0555624495ca1644c8488ddf33c6a65686"},"pr_commit":{"kind":"string","value":"0bdc85394f139a23d8363a47635efa878112a95b"},"query":{"kind":"string","value":"When we're loading dependencies, don't require exact versions. When we're loading analyzer dependencies, our current logic was to require the exact version that was requested from the loading assembly. This is problematic in a lot of cases where you would normally have a binding redirect to ensure assemblies load cleanly; by requiring exact versions we'd end up in diamond dependency cases where you couldn't practically produce an analyzer package that would cleanly load.\r\n\r\nWhile doing this change, @RikkiGibson and I noticed several other problems:\r\n\r\n1. There was an errant cache that was left in the .NET Core implementation, which meant that we'd sometimes reuse assemblies even when we were able to load them correctly. This has also been fixed as a prerequisite to the main fix, since otherwise it was difficult to prove that the behavior changes here weren't also going to impact the .NET Core implementation.\r\n2. There were some race conditions in the implementation.\r\n\r\n**REVIEWING COMMIT-AT-A-TIME IS HIGHLY RECOMMENDED**, since those changes are broken out to separate commits.\r\n\r\nFixes #53672\r\nFixes #56216"},"filepath":{"kind":"string","value":"./src/Compilers/Test/Core/AssemblyLoadTestFixture.cs"},"before_content":{"kind":"string","value":"// Licensed to the .NET Foundation under one or more agreements.\n// The .NET Foundation licenses this file to you under the MIT license.\n// See the LICENSE file in the project root for more information.\n\nusing System;\nusing System.Collections.Immutable;\nusing System.Linq;\nusing Basic.Reference.Assemblies;\nusing Microsoft.CodeAnalysis;\nusing Microsoft.CodeAnalysis.CSharp;\nusing Roslyn.Test.Utilities;\nusing Roslyn.Utilities;\n\nnamespace Microsoft.CodeAnalysis.Test.Utilities\n{\n public sealed class AssemblyLoadTestFixture : IDisposable\n {\n private static readonly CSharpCompilationOptions s_dllWithMaxWarningLevel = new(OutputKind.DynamicallyLinkedLibrary, warningLevel: Diagnostic.MaxWarningLevel);\n\n private readonly TempRoot _temp;\n private readonly TempDirectory _directory;\n\n public TempFile Delta1 { get; }\n public TempFile Gamma { get; }\n public TempFile Beta { get; }\n public TempFile Alpha { get; }\n\n public TempFile Delta2 { get; }\n public TempFile Epsilon { get; }\n\n public TempFile Delta2B { get; }\n public TempFile Delta3 { get; }\n\n public TempFile UserSystemCollectionsImmutable { get; }\n\n /// \n /// An analyzer which uses members in its referenced version of System.Collections.Immutable\n /// that are not present in the compiler's version of System.Collections.Immutable.\n /// \n public TempFile AnalyzerReferencesSystemCollectionsImmutable1 { get; }\n\n /// \n /// An analyzer which uses members in its referenced version of System.Collections.Immutable\n /// which have different behavior than the same members in compiler's version of System.Collections.Immutable.\n /// \n public TempFile AnalyzerReferencesSystemCollectionsImmutable2 { get; }\n\n public TempFile AnalyzerReferencesDelta1 { get; }\n\n public TempFile FaultyAnalyzer { get; }\n\n public TempFile AnalyzerWithDependency { get; }\n public TempFile AnalyzerDependency { get; }\n\n public TempFile AnalyzerWithNativeDependency { get; }\n\n public AssemblyLoadTestFixture()\n {\n _temp = new TempRoot();\n _directory = _temp.CreateDirectory();\n\n Delta1 = GenerateDll(\"Delta\", _directory, @\"\nusing System.Text;\n\n[assembly: System.Reflection.AssemblyTitle(\"\"Delta\"\")]\n[assembly: System.Reflection.AssemblyVersion(\"\"1.0.0.0\"\")]\n\nnamespace Delta\n{\n public class D\n {\n public void Write(StringBuilder sb, string s)\n {\n sb.AppendLine(\"\"Delta: \"\" + s);\n }\n }\n}\n\");\n var delta1Reference = MetadataReference.CreateFromFile(Delta1.Path);\n Gamma = GenerateDll(\"Gamma\", _directory, @\"\nusing System.Text;\nusing Delta;\n\nnamespace Gamma\n{\n public class G\n {\n public void Write(StringBuilder sb, string s)\n {\n D d = new D();\n\n d.Write(sb, \"\"Gamma: \"\" + s);\n }\n }\n}\n\", delta1Reference);\n\n var gammaReference = MetadataReference.CreateFromFile(Gamma.Path);\n Beta = GenerateDll(\"Beta\", _directory, @\"\nusing System.Text;\nusing Gamma;\n\nnamespace Beta\n{\n public class B\n {\n public void Write(StringBuilder sb, string s)\n {\n G g = new G();\n\n g.Write(sb, \"\"Beta: \"\" + s);\n }\n }\n}\n\", gammaReference);\n\n Alpha = GenerateDll(\"Alpha\", _directory, @\"\nusing System.Text;\nusing Gamma;\n\nnamespace Alpha\n{\n public class A\n {\n public void Write(StringBuilder sb, string s)\n {\n G g = new G();\n g.Write(sb, \"\"Alpha: \"\" + s);\n }\n }\n}\n\", gammaReference);\n\n var v2Directory = _directory.CreateDirectory(\"Version2\");\n Delta2 = GenerateDll(\"Delta\", v2Directory, @\"\nusing System.Text;\n\n[assembly: System.Reflection.AssemblyTitle(\"\"Delta\"\")]\n[assembly: System.Reflection.AssemblyVersion(\"\"2.0.0.0\"\")]\n\nnamespace Delta\n{\n public class D\n {\n public void Write(StringBuilder sb, string s)\n {\n sb.AppendLine(\"\"Delta.2: \"\" + s);\n }\n }\n}\n\");\n var delta2Reference = MetadataReference.CreateFromFile(Delta2.Path);\n Epsilon = GenerateDll(\"Epsilon\", v2Directory, @\"\nusing System.Text;\nusing Delta;\n\nnamespace Epsilon\n{\n public class E\n {\n public void Write(StringBuilder sb, string s)\n {\n D d = new D();\n\n d.Write(sb, \"\"Epsilon: \"\" + s);\n }\n }\n}\n\", delta2Reference);\n\n var v2BDirectory = _directory.CreateDirectory(\"Version2B\");\n Delta2B = GenerateDll(\"Delta\", v2BDirectory, @\"\nusing System.Text;\n\n[assembly: System.Reflection.AssemblyTitle(\"\"Delta\"\")]\n[assembly: System.Reflection.AssemblyVersion(\"\"2.0.0.0\"\")]\n\nnamespace Delta\n{\n public class D\n {\n public void Write(StringBuilder sb, string s)\n {\n sb.AppendLine(\"\"Delta.2B: \"\" + s);\n }\n }\n}\n\");\n\n var v3Directory = _directory.CreateDirectory(\"Version3\");\n Delta3 = GenerateDll(\"Delta\", v3Directory, @\"\nusing System.Text;\n\n[assembly: System.Reflection.AssemblyTitle(\"\"Delta\"\")]\n[assembly: System.Reflection.AssemblyVersion(\"\"3.0.0.0\"\")]\n\nnamespace Delta\n{\n public class D\n {\n public void Write(StringBuilder sb, string s)\n {\n sb.AppendLine(\"\"Delta.3: \"\" + s);\n }\n }\n}\n\");\n\n var sciUserDirectory = _directory.CreateDirectory(\"SCIUser\");\n var compilerReference = MetadataReference.CreateFromFile(typeof(Microsoft.CodeAnalysis.SyntaxNode).Assembly.Location);\n\n UserSystemCollectionsImmutable = GenerateDll(\"System.Collections.Immutable\", sciUserDirectory, @\"\nnamespace System.Collections.Immutable\n{\n public static class ImmutableArray\n {\n public static ImmutableArray Create(T t) => new();\n }\n\n public struct ImmutableArray\n {\n public int Length => 42;\n\n public static int MyMethod() => 42;\n }\n}\n\", compilerReference);\n\n var userSystemCollectionsImmutableReference = MetadataReference.CreateFromFile(UserSystemCollectionsImmutable.Path);\n AnalyzerReferencesSystemCollectionsImmutable1 = GenerateDll(\"AnalyzerUsesSystemCollectionsImmutable1\", sciUserDirectory, @\"\nusing System.Text;\nusing System.Collections.Immutable;\n\npublic class Analyzer\n{\n public void Method(StringBuilder sb)\n {\n sb.Append(ImmutableArray