From 89cd58b324ecb108fa29467cf09b30d48929bf72 Mon Sep 17 00:00:00 2001 From: tmat Date: Wed, 15 May 2024 12:33:31 -0700 Subject: [PATCH 1/4] Remove SourceCodeKind and MetadataReferenceProperties --- .../MSBuild/CSharp/CSharpProjectFile.cs | 6 ------ .../MSBuild/ProjectFile/ProjectFile.cs | 14 +++++--------- .../MSBuild/VisualBasic/VisualBasicProjectFile.cs | 6 ------ .../Rpc/Contracts/DocumentFileInfo.cs | 10 ++-------- .../Rpc/Contracts/IProjectFile.cs | 3 +-- .../MSBuild/MSBuild/MSBuildProjectLoader.Worker.cs | 2 +- .../Core/MSBuild/MSBuild/MSBuildWorkspace.cs | 14 ++++++++++---- .../Core/MSBuild/Rpc/RemoteProjectFile.cs | 7 ++----- 8 files changed, 21 insertions(+), 41 deletions(-) diff --git a/src/Workspaces/Core/MSBuild.BuildHost/MSBuild/CSharp/CSharpProjectFile.cs b/src/Workspaces/Core/MSBuild.BuildHost/MSBuild/CSharp/CSharpProjectFile.cs index cc81848d8f3e4..e95f95c7653c1 100644 --- a/src/Workspaces/Core/MSBuild.BuildHost/MSBuild/CSharp/CSharpProjectFile.cs +++ b/src/Workspaces/Core/MSBuild.BuildHost/MSBuild/CSharp/CSharpProjectFile.cs @@ -16,12 +16,6 @@ public CSharpProjectFile(CSharpProjectFileLoader loader, MSB.Evaluation.Project? { } - protected override SourceCodeKind GetSourceCodeKind(string documentFileName) - => SourceCodeKind.Regular; - - public override string GetDocumentExtension(SourceCodeKind sourceCodeKind) - => ".cs"; - protected override IEnumerable GetCompilerCommandLineArgs(MSB.Execution.ProjectInstance executedProject) => executedProject.GetItems(ItemNames.CscCommandLineArgs); diff --git a/src/Workspaces/Core/MSBuild.BuildHost/MSBuild/ProjectFile/ProjectFile.cs b/src/Workspaces/Core/MSBuild.BuildHost/MSBuild/ProjectFile/ProjectFile.cs index 788b90134bd08..a506b6ece89a8 100644 --- a/src/Workspaces/Core/MSBuild.BuildHost/MSBuild/ProjectFile/ProjectFile.cs +++ b/src/Workspaces/Core/MSBuild.BuildHost/MSBuild/ProjectFile/ProjectFile.cs @@ -10,7 +10,6 @@ using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.Diagnostics; using Roslyn.Utilities; using MSB = Microsoft.Build; @@ -39,8 +38,6 @@ protected ProjectFile(ProjectFileLoader loader, MSB.Evaluation.Project? loadedPr public ImmutableArray GetDiagnosticLogItems() => [.. Log]; - protected abstract SourceCodeKind GetSourceCodeKind(string documentFileName); - public abstract string GetDocumentExtension(SourceCodeKind kind); protected abstract IEnumerable GetCompilerCommandLineArgs(MSB.Execution.ProjectInstance executedProject); protected abstract ImmutableArray ReadCommandLineArgs(MSB.Execution.ProjectInstance project); @@ -228,10 +225,9 @@ private DocumentFileInfo MakeDocumentFileInfo(MSB.Framework.ITaskItem documentIt var logicalPath = GetDocumentLogicalPath(documentItem, _projectDirectory); var isLinked = IsDocumentLinked(documentItem); var isGenerated = IsDocumentGenerated(documentItem); - var sourceCodeKind = GetSourceCodeKind(filePath); var folders = GetRelativeFolders(documentItem); - return new DocumentFileInfo(filePath, logicalPath, isLinked, isGenerated, sourceCodeKind, folders); + return new DocumentFileInfo(filePath, logicalPath, isLinked, isGenerated, folders); } private DocumentFileInfo MakeNonSourceFileDocumentFileInfo(MSB.Framework.ITaskItem documentItem) @@ -242,7 +238,7 @@ private DocumentFileInfo MakeNonSourceFileDocumentFileInfo(MSB.Framework.ITaskIt var isGenerated = IsDocumentGenerated(documentItem); var folders = GetRelativeFolders(documentItem); - return new DocumentFileInfo(filePath, logicalPath, isLinked, isGenerated, SourceCodeKind.Regular, folders); + return new DocumentFileInfo(filePath, logicalPath, isLinked, isGenerated, folders); } private ImmutableArray GetRelativeFolders(MSB.Framework.ITaskItem documentItem) @@ -380,7 +376,7 @@ public void RemoveDocument(string filePath) } } - public void AddMetadataReference(string metadataReferenceIdentity, MetadataReferenceProperties properties, string? hintPath) + public void AddMetadataReference(string metadataReferenceIdentity, ImmutableArray aliases, string? hintPath) { if (_loadedProject is null) { @@ -388,8 +384,8 @@ public void AddMetadataReference(string metadataReferenceIdentity, MetadataRefer } var metadata = new Dictionary(); - if (!properties.Aliases.IsEmpty) - metadata.Add(MetadataNames.Aliases, string.Join(",", properties.Aliases)); + if (!aliases.IsEmpty) + metadata.Add(MetadataNames.Aliases, string.Join(",", aliases)); if (hintPath is not null) metadata.Add(MetadataNames.HintPath, hintPath); diff --git a/src/Workspaces/Core/MSBuild.BuildHost/MSBuild/VisualBasic/VisualBasicProjectFile.cs b/src/Workspaces/Core/MSBuild.BuildHost/MSBuild/VisualBasic/VisualBasicProjectFile.cs index 2acfd35e517e1..f6b50f68b97f7 100644 --- a/src/Workspaces/Core/MSBuild.BuildHost/MSBuild/VisualBasic/VisualBasicProjectFile.cs +++ b/src/Workspaces/Core/MSBuild.BuildHost/MSBuild/VisualBasic/VisualBasicProjectFile.cs @@ -15,12 +15,6 @@ public VisualBasicProjectFile(VisualBasicProjectFileLoader loader, MSB.Evaluatio { } - protected override SourceCodeKind GetSourceCodeKind(string documentFileName) - => SourceCodeKind.Regular; - - public override string GetDocumentExtension(SourceCodeKind sourceCodeKind) - => ".vb"; - protected override IEnumerable GetCompilerCommandLineArgs(MSB.Execution.ProjectInstance executedProject) => executedProject.GetItems(ItemNames.VbcCommandLineArgs); diff --git a/src/Workspaces/Core/MSBuild.BuildHost/Rpc/Contracts/DocumentFileInfo.cs b/src/Workspaces/Core/MSBuild.BuildHost/Rpc/Contracts/DocumentFileInfo.cs index b411cdd5a873a..a040cce7fbdfd 100644 --- a/src/Workspaces/Core/MSBuild.BuildHost/Rpc/Contracts/DocumentFileInfo.cs +++ b/src/Workspaces/Core/MSBuild.BuildHost/Rpc/Contracts/DocumentFileInfo.cs @@ -11,7 +11,7 @@ namespace Microsoft.CodeAnalysis.MSBuild /// Represents a source file that is part of a project file. /// [DataContract] - internal sealed class DocumentFileInfo(string filePath, string logicalPath, bool isLinked, bool isGenerated, SourceCodeKind sourceCodeKind, ImmutableArray folders) + internal sealed class DocumentFileInfo(string filePath, string logicalPath, bool isLinked, bool isGenerated, ImmutableArray folders) { /// /// The absolute path to the document file on disk. @@ -40,16 +40,10 @@ internal sealed class DocumentFileInfo(string filePath, string logicalPath, bool [DataMember(Order = 3)] public bool IsGenerated { get; } = isGenerated; - /// - /// The of this document. - /// - [DataMember(Order = 4)] - public SourceCodeKind SourceCodeKind { get; } = sourceCodeKind; - /// /// Containing folders of the document relative to the containing project root path. /// - [DataMember(Order = 5)] + [DataMember(Order = 4)] public ImmutableArray Folders { get; } = folders; } } diff --git a/src/Workspaces/Core/MSBuild.BuildHost/Rpc/Contracts/IProjectFile.cs b/src/Workspaces/Core/MSBuild.BuildHost/Rpc/Contracts/IProjectFile.cs index 7d93476b118ef..20b7633377fbf 100644 --- a/src/Workspaces/Core/MSBuild.BuildHost/Rpc/Contracts/IProjectFile.cs +++ b/src/Workspaces/Core/MSBuild.BuildHost/Rpc/Contracts/IProjectFile.cs @@ -14,11 +14,10 @@ namespace Microsoft.CodeAnalysis.MSBuild; internal interface IProjectFile { ImmutableArray GetDiagnosticLogItems(); - string GetDocumentExtension(SourceCodeKind kind); Task> GetProjectFileInfosAsync(CancellationToken cancellationToken); void AddDocument(string filePath, string? logicalPath); void RemoveDocument(string filePath); - void AddMetadataReference(string metadataReferenceIdentity, MetadataReferenceProperties properties, string? hintPath); + void AddMetadataReference(string metadataReferenceIdentity, ImmutableArray aliases, string? hintPath); void RemoveMetadataReference(string shortAssemblyName, string fullAssemblyName, string filePath); void AddProjectReference(string projectName, ProjectFileReference reference); void RemoveProjectReference(string projectName, string projectFilePath); diff --git a/src/Workspaces/Core/MSBuild/MSBuild/MSBuildProjectLoader.Worker.cs b/src/Workspaces/Core/MSBuild/MSBuild/MSBuildProjectLoader.Worker.cs index 8a89561728484..33d48c9d7d80c 100644 --- a/src/Workspaces/Core/MSBuild/MSBuild/MSBuildProjectLoader.Worker.cs +++ b/src/Workspaces/Core/MSBuild/MSBuild/MSBuildProjectLoader.Worker.cs @@ -444,7 +444,7 @@ private ImmutableArray CreateDocumentInfos(IReadOnlyList ".cs", + LanguageNames.VisualBasic => ".vb", + _ => throw ExceptionUtilities.UnexpectedValue(project.Language) + }; + var fileName = Path.ChangeExtension(info.Name, extension); var relativePath = (info.Folders != null && info.Folders.Count > 0) @@ -578,19 +584,19 @@ protected override void ApplyMetadataReferenceAdded(ProjectId projectId, Metadat { // Since the location of the reference is in GAC, need to use full identity name to find it again. // This typically happens when you base the reference off of a reflection assembly location. - _applyChangesProjectFile.AddMetadataReferenceAsync(identity.GetDisplayName(), metadataReference.Properties, hintPath: null, CancellationToken.None).Wait(); + _applyChangesProjectFile.AddMetadataReferenceAsync(identity.GetDisplayName(), metadataReference.Properties.Aliases, hintPath: null, CancellationToken.None).Wait(); } else if (IsFrameworkReferenceAssembly(peRef.FilePath)) { // just use short name since this will be resolved by msbuild relative to the known framework reference assemblies. var fileName = identity != null ? identity.Name : Path.GetFileNameWithoutExtension(peRef.FilePath); - _applyChangesProjectFile.AddMetadataReferenceAsync(fileName, metadataReference.Properties, hintPath: null, CancellationToken.None).Wait(); + _applyChangesProjectFile.AddMetadataReferenceAsync(fileName, metadataReference.Properties.Aliases, hintPath: null, CancellationToken.None).Wait(); } else // other location -- need hint to find correct assembly { var relativePath = PathUtilities.GetRelativePath(Path.GetDirectoryName(CurrentSolution.GetRequiredProject(projectId).FilePath)!, peRef.FilePath); var fileName = Path.GetFileNameWithoutExtension(peRef.FilePath); - _applyChangesProjectFile.AddMetadataReferenceAsync(fileName, metadataReference.Properties, relativePath, CancellationToken.None).Wait(); + _applyChangesProjectFile.AddMetadataReferenceAsync(fileName, metadataReference.Properties.Aliases, relativePath, CancellationToken.None).Wait(); } } diff --git a/src/Workspaces/Core/MSBuild/Rpc/RemoteProjectFile.cs b/src/Workspaces/Core/MSBuild/Rpc/RemoteProjectFile.cs index 59b91fbb346c2..038e2cf1a880a 100644 --- a/src/Workspaces/Core/MSBuild/Rpc/RemoteProjectFile.cs +++ b/src/Workspaces/Core/MSBuild/Rpc/RemoteProjectFile.cs @@ -22,9 +22,6 @@ public RemoteProjectFile(RpcClient client, int remoteProjectFileTargetObject) public Task> GetDiagnosticLogItemsAsync(CancellationToken cancellationToken) => _client.InvokeAsync>(_remoteProjectFileTargetObject, nameof(IProjectFile.GetDiagnosticLogItems), parameters: [], cancellationToken); - public Task GetDocumentExtensionAsync(SourceCodeKind sourceCodeKind, CancellationToken cancellationToken) - => _client.InvokeAsync(_remoteProjectFileTargetObject, nameof(IProjectFile.GetDocumentExtension), parameters: [sourceCodeKind], cancellationToken); - public Task> GetProjectFileInfosAsync(CancellationToken cancellationToken) => _client.InvokeAsync>(_remoteProjectFileTargetObject, nameof(IProjectFile.GetProjectFileInfosAsync), parameters: [], cancellationToken); @@ -34,8 +31,8 @@ public Task AddDocumentAsync(string filePath, string? logicalPath, CancellationT public Task RemoveDocumentAsync(string filePath, CancellationToken cancellationToken) => _client.InvokeAsync(_remoteProjectFileTargetObject, nameof(IProjectFile.RemoveDocument), parameters: [filePath], cancellationToken); - public Task AddMetadataReferenceAsync(string metadataReferenceIdentity, MetadataReferenceProperties properties, string? hintPath, CancellationToken cancellationToken) - => _client.InvokeAsync(_remoteProjectFileTargetObject, nameof(IProjectFile.AddMetadataReference), parameters: [metadataReferenceIdentity, properties, hintPath], cancellationToken); + public Task AddMetadataReferenceAsync(string metadataReferenceIdentity, ImmutableArray aliases, string? hintPath, CancellationToken cancellationToken) + => _client.InvokeAsync(_remoteProjectFileTargetObject, nameof(IProjectFile.AddMetadataReference), parameters: [metadataReferenceIdentity, aliases, hintPath], cancellationToken); public Task RemoveMetadataReferenceAsync(string shortAssemblyName, string fullAssemblyName, string filePath, CancellationToken cancellationToken) => _client.InvokeAsync(_remoteProjectFileTargetObject, nameof(IProjectFile.RemoveMetadataReference), parameters: [shortAssemblyName, fullAssemblyName, filePath], cancellationToken); From e6199173afdee20060a4ade94710097d10f91c36 Mon Sep 17 00:00:00 2001 From: tmat Date: Wed, 15 May 2024 12:34:39 -0700 Subject: [PATCH 2/4] Remove CodeAnalysis dependencies --- Roslyn.sln | 2 + .../Collections/ImmutableArrayExtensions.cs | 23 +++-------- .../NoThrowStreamDisposer.cs | 0 .../Diagnostic/DiagnosticArrayExtensions.cs | 23 +++++++++++ .../AdditionalTextComparer.cs | 0 .../Core/Portable/EncodedStringText.cs | 2 +- .../InternalUtilities/EncodingExtensions.cs | 26 ------------- .../InternalUtilities/EnumUtilties.cs | 39 ------------------- .../InternalUtilities/TextKeyedCache.cs | 10 +---- .../AssemblyIdentityUtils.cs | 0 .../GeneratedCodeUtilities.cs | 0 .../Core/Portable/SpecialTypeExtensions.cs | 30 ++++++++++++++ .../AbstractSymbolDisplayVisitor.cs | 6 +-- src/Compilers/Core/Portable/Text/LargeText.cs | 2 +- .../Core/Portable/Text/SourceText.cs | 18 ++++++++- .../TextChangeRangeExtensions.cs | 0 .../Core/MSBuild.BuildHost/BuildHost.cs | 10 ++--- .../Logging/MSBuildDiagnosticLogger.cs | 4 +- .../ProjectFile/CommandLineArgumentReader.cs | 4 +- .../MSBuild/ProjectFile/Extensions.cs | 4 +- .../MSBuild/ProjectFile/ProjectFile.cs | 1 - ...alysis.Workspaces.MSBuild.BuildHost.csproj | 35 ++++++++++++----- .../Core/CompilerExtensions.projitems | 11 +++--- .../Extensions/ImmutableArrayExtensions.cs | 7 +--- .../Core/Utilities/ConcatImmutableArray`1.cs | 6 +++ .../CSharpFlagsEnumGenerator.cs | 2 +- .../AbstractFlagsEnumGenerator.cs | 8 ++-- .../VisualBasicFlagsEnumGenerator.vb | 2 +- 28 files changed, 137 insertions(+), 138 deletions(-) rename src/Compilers/Core/Portable/{InternalUtilities => CommandLine}/NoThrowStreamDisposer.cs (100%) create mode 100644 src/Compilers/Core/Portable/Diagnostic/DiagnosticArrayExtensions.cs rename src/Compilers/Core/Portable/{InternalUtilities => DiagnosticAnalyzer}/AdditionalTextComparer.cs (100%) rename src/Compilers/Core/Portable/{InternalUtilities => MetadataReference}/AssemblyIdentityUtils.cs (100%) rename src/Compilers/Core/Portable/{InternalUtilities => SourceGeneration}/GeneratedCodeUtilities.cs (100%) rename src/Compilers/Core/Portable/{InternalUtilities => Text}/TextChangeRangeExtensions.cs (100%) diff --git a/Roslyn.sln b/Roslyn.sln index 848adc0f76206..894a41eefa9df 100644 --- a/Roslyn.sln +++ b/Roslyn.sln @@ -1698,6 +1698,8 @@ Global src\ExpressionEvaluator\Core\Source\ResultProvider\ResultProvider.projitems*{abdbac1e-350e-4dc3-bb45-3504404545ee}*SharedItemsImports = 5 src\ExpressionEvaluator\VisualBasic\Source\ResultProvider\BasicResultProvider.projitems*{ace53515-482c-4c6a-e2d2-4242a687dfee}*SharedItemsImports = 5 src\Compilers\CSharp\csc\CscCommandLine.projitems*{b021ccbc-b2af-4560-af28-ed055f0ed696}*SharedItemsImports = 13 + src\Dependencies\Collections\Microsoft.CodeAnalysis.Collections.projitems*{b1481d94-682e-46ec-adbe-a16eb46feee9}*SharedItemsImports = 5 + src\Dependencies\PooledObjects\Microsoft.CodeAnalysis.PooledObjects.projitems*{b1481d94-682e-46ec-adbe-a16eb46feee9}*SharedItemsImports = 5 src\Compilers\CSharp\CSharpAnalyzerDriver\CSharpAnalyzerDriver.projitems*{b501a547-c911-4a05-ac6e-274a50dff30e}*SharedItemsImports = 5 src\ExpressionEvaluator\Core\Source\ResultProvider\ResultProvider.projitems*{bb3ca047-5d00-48d4-b7d3-233c1265c065}*SharedItemsImports = 13 src\ExpressionEvaluator\CSharp\Source\ResultProvider\CSharpResultProvider.projitems*{bf9dac1e-3a5e-4dc3-bb44-9a64e0d4e9d4}*SharedItemsImports = 5 diff --git a/src/Compilers/Core/Portable/Collections/ImmutableArrayExtensions.cs b/src/Compilers/Core/Portable/Collections/ImmutableArrayExtensions.cs index 51ccab0fd9398..2fbb864964308 100644 --- a/src/Compilers/Core/Portable/Collections/ImmutableArrayExtensions.cs +++ b/src/Compilers/Core/Portable/Collections/ImmutableArrayExtensions.cs @@ -764,19 +764,6 @@ public static ImmutableArray Distinct(this ImmutableArray array, IEqual return result; } - internal static bool HasAnyErrors(this ImmutableArray diagnostics) where T : Diagnostic - { - foreach (var diagnostic in diagnostics) - { - if (diagnostic.Severity == DiagnosticSeverity.Error) - { - return true; - } - } - - return false; - } - // In DEBUG, swap the first and last elements of a read-only array, yielding a new read only array. // This helps to avoid depending on accidentally sorted arrays. internal static ImmutableArray ConditionallyDeOrder(this ImmutableArray array) @@ -1034,8 +1021,8 @@ internal static void CreateNameToMembersMap> GetTypesFromM var dictionary = new Dictionary>(capacity, comparer); - foreach (var (name, members) in map) + foreach (var entry in map) { - var namedTypes = getOrCreateNamedTypes(members); + var namedTypes = getOrCreateNamedTypes(entry.Value); if (namedTypes.Length > 0) - dictionary.Add(name, namedTypes); + dictionary.Add(entry.Key, namedTypes); } return dictionary; diff --git a/src/Compilers/Core/Portable/InternalUtilities/NoThrowStreamDisposer.cs b/src/Compilers/Core/Portable/CommandLine/NoThrowStreamDisposer.cs similarity index 100% rename from src/Compilers/Core/Portable/InternalUtilities/NoThrowStreamDisposer.cs rename to src/Compilers/Core/Portable/CommandLine/NoThrowStreamDisposer.cs diff --git a/src/Compilers/Core/Portable/Diagnostic/DiagnosticArrayExtensions.cs b/src/Compilers/Core/Portable/Diagnostic/DiagnosticArrayExtensions.cs new file mode 100644 index 0000000000000..c22f86921e8ac --- /dev/null +++ b/src/Compilers/Core/Portable/Diagnostic/DiagnosticArrayExtensions.cs @@ -0,0 +1,23 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using System.Collections.Immutable; + +namespace Microsoft.CodeAnalysis; + +internal static class DiagnosticArrayExtensions +{ + internal static bool HasAnyErrors(this ImmutableArray diagnostics) where T : Diagnostic + { + foreach (var diagnostic in diagnostics) + { + if (diagnostic.Severity == DiagnosticSeverity.Error) + { + return true; + } + } + + return false; + } +} diff --git a/src/Compilers/Core/Portable/InternalUtilities/AdditionalTextComparer.cs b/src/Compilers/Core/Portable/DiagnosticAnalyzer/AdditionalTextComparer.cs similarity index 100% rename from src/Compilers/Core/Portable/InternalUtilities/AdditionalTextComparer.cs rename to src/Compilers/Core/Portable/DiagnosticAnalyzer/AdditionalTextComparer.cs diff --git a/src/Compilers/Core/Portable/EncodedStringText.cs b/src/Compilers/Core/Portable/EncodedStringText.cs index 71ddfe9c398b0..61fa6f128e688 100644 --- a/src/Compilers/Core/Portable/EncodedStringText.cs +++ b/src/Compilers/Core/Portable/EncodedStringText.cs @@ -139,7 +139,7 @@ private static SourceText Decode( data.Seek(0, SeekOrigin.Begin); // For small streams, see if we can read the byte buffer directly. - if (encoding.GetMaxCharCountOrThrowIfHuge(data) < LargeObjectHeapLimitInChars) + if (encoding.TryGetMaxCharCount(data.Length, out int maxCharCount) && maxCharCount < LargeObjectHeapLimitInChars) { if (TryGetBytesFromStream(data, out ArraySegment bytes) && bytes.Offset == 0 && bytes.Array is object) { diff --git a/src/Compilers/Core/Portable/InternalUtilities/EncodingExtensions.cs b/src/Compilers/Core/Portable/InternalUtilities/EncodingExtensions.cs index 799070e325d4a..91acd015a8eb6 100644 --- a/src/Compilers/Core/Portable/InternalUtilities/EncodingExtensions.cs +++ b/src/Compilers/Core/Portable/InternalUtilities/EncodingExtensions.cs @@ -2,39 +2,13 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -using Microsoft.CodeAnalysis; using System; -using System.Diagnostics; -using System.IO; using System.Text; namespace Microsoft.CodeAnalysis { internal static partial class EncodingExtensions { - /// - /// Get maximum char count needed to decode the entire stream. - /// - /// Stream is so big that max char count can't fit in . - internal static int GetMaxCharCountOrThrowIfHuge(this Encoding encoding, Stream stream) - { - Debug.Assert(stream.CanSeek); - long length = stream.Length; - - if (encoding.TryGetMaxCharCount(length, out int maxCharCount)) - { - return maxCharCount; - } - -#if CODE_STYLE - throw new IOException(CodeStyleResources.Stream_is_too_long); -#elif WORKSPACE - throw new IOException(WorkspacesResources.Stream_is_too_long); -#else - throw new IOException(CodeAnalysisResources.StreamIsTooLong); -#endif - } - internal static bool TryGetMaxCharCount(this Encoding encoding, long length, out int maxCharCount) { maxCharCount = 0; diff --git a/src/Compilers/Core/Portable/InternalUtilities/EnumUtilties.cs b/src/Compilers/Core/Portable/InternalUtilities/EnumUtilties.cs index 8e0d40e161b1c..a39b43bf02f2b 100644 --- a/src/Compilers/Core/Portable/InternalUtilities/EnumUtilties.cs +++ b/src/Compilers/Core/Portable/InternalUtilities/EnumUtilties.cs @@ -11,45 +11,6 @@ namespace Roslyn.Utilities { internal static class EnumUtilities { - /// - /// Convert a boxed primitive (generally of the backing type of an enum) into a ulong. - /// - /// - /// - internal static ulong ConvertEnumUnderlyingTypeToUInt64(object value, SpecialType specialType) - { - RoslynDebug.Assert(value != null); - Debug.Assert(value.GetType().GetTypeInfo().IsPrimitive); - - unchecked - { - switch (specialType) - { - case SpecialType.System_SByte: - return (ulong)(sbyte)value; - case SpecialType.System_Int16: - return (ulong)(short)value; - case SpecialType.System_Int32: - return (ulong)(int)value; - case SpecialType.System_Int64: - return (ulong)(long)value; - case SpecialType.System_Byte: - return (byte)value; - case SpecialType.System_UInt16: - return (ushort)value; - case SpecialType.System_UInt32: - return (uint)value; - case SpecialType.System_UInt64: - return (ulong)value; - - default: - // not using ExceptionUtilities.UnexpectedValue() because this is used by the Services layer - // which doesn't have those utilities. - throw new InvalidOperationException(string.Format("{0} is not a valid underlying type for an enum", specialType)); - } - } - } - internal static T[] GetValues() where T : struct { return (T[])Enum.GetValues(typeof(T)); diff --git a/src/Compilers/Core/Portable/InternalUtilities/TextKeyedCache.cs b/src/Compilers/Core/Portable/InternalUtilities/TextKeyedCache.cs index 9164416313002..b1cafb1babf32 100644 --- a/src/Compilers/Core/Portable/InternalUtilities/TextKeyedCache.cs +++ b/src/Compilers/Core/Portable/InternalUtilities/TextKeyedCache.cs @@ -3,16 +3,8 @@ // See the LICENSE file in the project root for more information. using System; -using System.Collections.Generic; -using System.Diagnostics; -using System.Diagnostics.CodeAnalysis; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using Microsoft.CodeAnalysis.PooledObjects; -using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.Text; using System.Threading; +using Microsoft.CodeAnalysis.PooledObjects; namespace Roslyn.Utilities { diff --git a/src/Compilers/Core/Portable/InternalUtilities/AssemblyIdentityUtils.cs b/src/Compilers/Core/Portable/MetadataReference/AssemblyIdentityUtils.cs similarity index 100% rename from src/Compilers/Core/Portable/InternalUtilities/AssemblyIdentityUtils.cs rename to src/Compilers/Core/Portable/MetadataReference/AssemblyIdentityUtils.cs diff --git a/src/Compilers/Core/Portable/InternalUtilities/GeneratedCodeUtilities.cs b/src/Compilers/Core/Portable/SourceGeneration/GeneratedCodeUtilities.cs similarity index 100% rename from src/Compilers/Core/Portable/InternalUtilities/GeneratedCodeUtilities.cs rename to src/Compilers/Core/Portable/SourceGeneration/GeneratedCodeUtilities.cs diff --git a/src/Compilers/Core/Portable/SpecialTypeExtensions.cs b/src/Compilers/Core/Portable/SpecialTypeExtensions.cs index 553126db2e869..85dd34f4a0b7f 100644 --- a/src/Compilers/Core/Portable/SpecialTypeExtensions.cs +++ b/src/Compilers/Core/Portable/SpecialTypeExtensions.cs @@ -3,6 +3,7 @@ // See the LICENSE file in the project root for more information. using System; +using System.Diagnostics; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis @@ -364,5 +365,34 @@ public static SpecialType FromRuntimeTypeOfLiteralValue(object value) /// public static bool CanOptimizeBehavior(this SpecialType specialType) => specialType is >= SpecialType.System_Object and <= SpecialType.System_Runtime_CompilerServices_InlineArrayAttribute; + + + /// + /// Convert a boxed primitive (generally of the backing type of an enum) into a ulong. + /// + /// + /// + internal static ulong ConvertUnderlyingValueToUInt64(this SpecialType enumUnderlyingType, object value) + { + RoslynDebug.Assert(value != null); + Debug.Assert(value.GetType().IsPrimitive); + + unchecked + { + return enumUnderlyingType switch + { + SpecialType.System_SByte => (ulong)(sbyte)value, + SpecialType.System_Int16 => (ulong)(short)value, + SpecialType.System_Int32 => (ulong)(int)value, + SpecialType.System_Int64 => (ulong)(long)value, + SpecialType.System_Byte => (byte)value, + SpecialType.System_UInt16 => (ushort)value, + SpecialType.System_UInt32 => (uint)value, + SpecialType.System_UInt64 => (ulong)value, + _ => throw ExceptionUtilities.UnexpectedValue(enumUnderlyingType), + }; + } + } + } } diff --git a/src/Compilers/Core/Portable/SymbolDisplay/AbstractSymbolDisplayVisitor.cs b/src/Compilers/Core/Portable/SymbolDisplay/AbstractSymbolDisplayVisitor.cs index bb75846ec1e50..34c2c27a48c1f 100644 --- a/src/Compilers/Core/Portable/SymbolDisplay/AbstractSymbolDisplayVisitor.cs +++ b/src/Compilers/Core/Portable/SymbolDisplay/AbstractSymbolDisplayVisitor.cs @@ -235,7 +235,7 @@ private void AddFlagsEnumConstantValue( { Debug.Assert(enumType.EnumUnderlyingType is not null); var underlyingSpecialType = enumType.EnumUnderlyingType.SpecialType; - var constantValueULong = EnumUtilities.ConvertEnumUnderlyingTypeToUInt64(constantValue, underlyingSpecialType); + var constantValueULong = underlyingSpecialType.ConvertUnderlyingValueToUInt64(constantValue); var result = constantValueULong; @@ -321,7 +321,7 @@ private static void GetSortedEnumFields( var field = (IFieldSymbol)member; if (field.HasConstantValue) { - var enumField = new EnumField(field.Name, EnumUtilities.ConvertEnumUnderlyingTypeToUInt64(field.ConstantValue, underlyingSpecialType), field); + var enumField = new EnumField(field.Name, underlyingSpecialType.ConvertUnderlyingValueToUInt64(field.ConstantValue), field); enumFields.Add(enumField); } } @@ -334,7 +334,7 @@ private void AddNonFlagsEnumConstantValue(INamedTypeSymbol enumType, object cons { Debug.Assert(enumType.EnumUnderlyingType is not null); var underlyingSpecialType = enumType.EnumUnderlyingType.SpecialType; - var constantValueULong = EnumUtilities.ConvertEnumUnderlyingTypeToUInt64(constantValue, underlyingSpecialType); + var constantValueULong = underlyingSpecialType.ConvertUnderlyingValueToUInt64(constantValue); var enumFields = ArrayBuilder.GetInstance(); GetSortedEnumFields(enumType, enumFields); diff --git a/src/Compilers/Core/Portable/Text/LargeText.cs b/src/Compilers/Core/Portable/Text/LargeText.cs index 293623460eaef..9fc77a99eb920 100644 --- a/src/Compilers/Core/Portable/Text/LargeText.cs +++ b/src/Compilers/Core/Portable/Text/LargeText.cs @@ -62,7 +62,7 @@ internal static SourceText Decode(Stream stream, Encoding encoding, SourceHashAl return SourceText.From(string.Empty, encoding, checksumAlgorithm); } - var maxCharRemainingGuess = encoding.GetMaxCharCountOrThrowIfHuge(stream); + var maxCharRemainingGuess = GetMaxCharCountOrThrowIfHuge(encoding, stream); Debug.Assert(longLength > 0 && longLength <= int.MaxValue); // GetMaxCharCountOrThrowIfHuge should have thrown. int length = (int)longLength; diff --git a/src/Compilers/Core/Portable/Text/SourceText.cs b/src/Compilers/Core/Portable/Text/SourceText.cs index 4f5421e1c0053..0dac9ac001d04 100644 --- a/src/Compilers/Core/Portable/Text/SourceText.cs +++ b/src/Compilers/Core/Portable/Text/SourceText.cs @@ -201,7 +201,7 @@ public static SourceText From( if (stream.CanSeek) { // If the resulting string would end up on the large object heap, then use LargeEncodedText. - if (encoding.GetMaxCharCountOrThrowIfHuge(stream) >= LargeObjectHeapLimitInChars) + if (GetMaxCharCountOrThrowIfHuge(encoding, stream) >= LargeObjectHeapLimitInChars) { return LargeText.Decode(stream, encoding, checksumAlgorithm, throwIfBinaryDetected, canBeEmbedded); } @@ -1260,5 +1260,21 @@ public override event EventHandler TextChanged } } } + + /// + /// Get maximum char count needed to decode the entire stream. + /// + /// Stream is so big that max char count can't fit in . + internal static int GetMaxCharCountOrThrowIfHuge(Encoding encoding, Stream stream) + { + Debug.Assert(stream.CanSeek); + + if (encoding.TryGetMaxCharCount(stream.Length, out int maxCharCount)) + { + return maxCharCount; + } + + throw new IOException(CodeAnalysisResources.StreamIsTooLong); + } } } diff --git a/src/Compilers/Core/Portable/InternalUtilities/TextChangeRangeExtensions.cs b/src/Compilers/Core/Portable/Text/TextChangeRangeExtensions.cs similarity index 100% rename from src/Compilers/Core/Portable/InternalUtilities/TextChangeRangeExtensions.cs rename to src/Compilers/Core/Portable/Text/TextChangeRangeExtensions.cs diff --git a/src/Workspaces/Core/MSBuild.BuildHost/BuildHost.cs b/src/Workspaces/Core/MSBuild.BuildHost/BuildHost.cs index bc1e0320e7e40..08e8008ad8046 100644 --- a/src/Workspaces/Core/MSBuild.BuildHost/BuildHost.cs +++ b/src/Workspaces/Core/MSBuild.BuildHost/BuildHost.cs @@ -2,10 +2,10 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -extern alias workspaces; using System.Collections.Immutable; -using System.IO; +using System.Diagnostics.CodeAnalysis; using System.Linq; +using System.IO; using System.Runtime.CompilerServices; using System.Threading; using System.Threading.Tasks; @@ -101,11 +101,7 @@ private bool TryEnsureMSBuildLoaded(string projectOrSolutionFilePath) } } -#if NET472 || NET6_0 // If we're compiling against net472 or net6.0, we get our MemberNotNull from the workspaces assembly. It has it in the net6.0 case since we're consuming the netstandard2.0 version of Workspaces. - [workspaces::System.Diagnostics.CodeAnalysis.MemberNotNull(nameof(_buildManager))] -#else // If we're compiling against net7.0 or higher, then we're getting it staright from the framework. - [System.Diagnostics.CodeAnalysis.MemberNotNull(nameof(_buildManager))] -#endif + [MemberNotNull(nameof(_buildManager))] [MethodImpl(MethodImplOptions.NoInlining)] // Do not inline this, since this creates MSBuild types which are being loaded by the caller private void CreateBuildManager() { diff --git a/src/Workspaces/Core/MSBuild.BuildHost/MSBuild/Logging/MSBuildDiagnosticLogger.cs b/src/Workspaces/Core/MSBuild.BuildHost/MSBuild/Logging/MSBuildDiagnosticLogger.cs index 43f720925310d..fb40e57d11bd7 100644 --- a/src/Workspaces/Core/MSBuild.BuildHost/MSBuild/Logging/MSBuildDiagnosticLogger.cs +++ b/src/Workspaces/Core/MSBuild.BuildHost/MSBuild/Logging/MSBuildDiagnosticLogger.cs @@ -25,13 +25,13 @@ public void SetProjectAndLog(string projectFilePath, DiagnosticLog log) private void OnErrorRaised(object sender, MSB.Framework.BuildErrorEventArgs e) { - RoslynDebug.AssertNotNull(_projectFilePath); + Debug.Assert(_projectFilePath != null); _log?.Add(new MSBuildDiagnosticLogItem(WorkspaceDiagnosticKind.Failure, _projectFilePath, e.Message ?? "", e.File, e.LineNumber, e.ColumnNumber)); } private void OnWarningRaised(object sender, MSB.Framework.BuildWarningEventArgs e) { - RoslynDebug.AssertNotNull(_projectFilePath); + Debug.Assert(_projectFilePath != null); _log?.Add(new MSBuildDiagnosticLogItem(WorkspaceDiagnosticKind.Warning, _projectFilePath, e.Message ?? "", e.File, e.LineNumber, e.ColumnNumber)); } diff --git a/src/Workspaces/Core/MSBuild.BuildHost/MSBuild/ProjectFile/CommandLineArgumentReader.cs b/src/Workspaces/Core/MSBuild.BuildHost/MSBuild/ProjectFile/CommandLineArgumentReader.cs index e8416d6a98327..224cf14c1b01c 100644 --- a/src/Workspaces/Core/MSBuild.BuildHost/MSBuild/ProjectFile/CommandLineArgumentReader.cs +++ b/src/Workspaces/Core/MSBuild.BuildHost/MSBuild/ProjectFile/CommandLineArgumentReader.cs @@ -26,7 +26,7 @@ protected CommandLineArgumentReader(MSB.Execution.ProjectInstance project) private static void ValidateName(string name) { - if (RoslynString.IsNullOrEmpty(name) || name.Contains(char.IsWhiteSpace)) + if (string.IsNullOrEmpty(name) || name.Any(char.IsWhiteSpace)) { throw new ArgumentException(WorkspaceMSBuildBuildHostResources.Parameter_cannot_be_null_empty_or_contain_whitespace, nameof(name)); } @@ -43,7 +43,7 @@ protected void Add(string name, string? value, bool addQuoteIfValueContainsWhite { ValidateName(name); - if (RoslynString.IsNullOrEmpty(value) || (addQuoteIfValueContainsWhitespace && value.Contains(char.IsWhiteSpace))) + if (string.IsNullOrEmpty(value) || (addQuoteIfValueContainsWhitespace && value.Any(char.IsWhiteSpace))) { _builder.Add($"/{name}:\"{value}\""); } diff --git a/src/Workspaces/Core/MSBuild.BuildHost/MSBuild/ProjectFile/Extensions.cs b/src/Workspaces/Core/MSBuild.BuildHost/MSBuild/ProjectFile/Extensions.cs index 13e65ac97f128..08defaa3c81f4 100644 --- a/src/Workspaces/Core/MSBuild.BuildHost/MSBuild/ProjectFile/Extensions.cs +++ b/src/Workspaces/Core/MSBuild.BuildHost/MSBuild/ProjectFile/Extensions.cs @@ -60,7 +60,7 @@ public static ImmutableArray GetAliases(this MSB.Framework.ITaskItem ite { var aliasesText = item.GetMetadata(MetadataNames.Aliases); - return !RoslynString.IsNullOrWhiteSpace(aliasesText) + return !string.IsNullOrWhiteSpace(aliasesText) ? ImmutableArray.CreateRange(aliasesText.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries).Select(a => a.Trim())) : []; } @@ -69,7 +69,7 @@ public static bool ReferenceOutputAssemblyIsTrue(this MSB.Framework.ITaskItem it { var referenceOutputAssemblyText = item.GetMetadata(MetadataNames.ReferenceOutputAssembly); - return RoslynString.IsNullOrWhiteSpace(referenceOutputAssemblyText) || + return string.IsNullOrWhiteSpace(referenceOutputAssemblyText) || !string.Equals(referenceOutputAssemblyText, bool.FalseString, StringComparison.OrdinalIgnoreCase); } diff --git a/src/Workspaces/Core/MSBuild.BuildHost/MSBuild/ProjectFile/ProjectFile.cs b/src/Workspaces/Core/MSBuild.BuildHost/MSBuild/ProjectFile/ProjectFile.cs index a506b6ece89a8..51ed9b9e74da7 100644 --- a/src/Workspaces/Core/MSBuild.BuildHost/MSBuild/ProjectFile/ProjectFile.cs +++ b/src/Workspaces/Core/MSBuild.BuildHost/MSBuild/ProjectFile/ProjectFile.cs @@ -9,7 +9,6 @@ using System.Linq; using System.Threading; using System.Threading.Tasks; -using Microsoft.CodeAnalysis; using Roslyn.Utilities; using MSB = Microsoft.Build; diff --git a/src/Workspaces/Core/MSBuild.BuildHost/Microsoft.CodeAnalysis.Workspaces.MSBuild.BuildHost.csproj b/src/Workspaces/Core/MSBuild.BuildHost/Microsoft.CodeAnalysis.Workspaces.MSBuild.BuildHost.csproj index c895b665da4dc..b41c677a1dddd 100644 --- a/src/Workspaces/Core/MSBuild.BuildHost/Microsoft.CodeAnalysis.Workspaces.MSBuild.BuildHost.csproj +++ b/src/Workspaces/Core/MSBuild.BuildHost/Microsoft.CodeAnalysis.Workspaces.MSBuild.BuildHost.csproj @@ -20,6 +20,7 @@ a RuntimeIdentifier given to us, since we really don't want to accidentally pick up platform specific binaries since we also have to run on Mono. --> AnyCPU + true