From df9e0beccd83835ecc5e32d0574f6bf08f861cb4 Mon Sep 17 00:00:00 2001 From: "dotnet-maestro[bot]" <42748379+dotnet-maestro[bot]@users.noreply.github.com> Date: Thu, 15 May 2025 10:09:27 +0000 Subject: [PATCH 01/11] [main] Source code updates from dotnet/diagnostics (#559) Co-authored-by: dotnet-maestro[bot] Co-authored-by: Viktor Hofer --- prereqs/git-info/diagnostics.props | 6 +++--- .../Runtime.cs | 11 +++++++--- .../Host/CommandFormatHelpers.cs | 9 ++++++++ .../Host/RuntimesCommand.cs | 4 +--- .../Host/StatusCommand.cs | 1 + .../src/SOS/SOS.Extensions/HostServices.cs | 4 ++++ .../src/SOS/SOS.Hosting/RuntimeWrapper.cs | 21 +++++++++++-------- src/source-manifest.json | 6 +++--- 8 files changed, 41 insertions(+), 21 deletions(-) diff --git a/prereqs/git-info/diagnostics.props b/prereqs/git-info/diagnostics.props index 9123991a484..82b0400284c 100644 --- a/prereqs/git-info/diagnostics.props +++ b/prereqs/git-info/diagnostics.props @@ -1,8 +1,8 @@  - 3a08702ea8e0083a74e10556c60c0bccd868b64a - 20250512.2 - 9.0.626202 + a3c354f4ea00123f55276619455569d53c4c402d + 20250513.2 + 9.0.626302 \ No newline at end of file diff --git a/src/diagnostics/src/Microsoft.Diagnostics.DebugServices.Implementation/Runtime.cs b/src/diagnostics/src/Microsoft.Diagnostics.DebugServices.Implementation/Runtime.cs index 7e02dcaf0f5..f3eeb4aa957 100644 --- a/src/diagnostics/src/Microsoft.Diagnostics.DebugServices.Implementation/Runtime.cs +++ b/src/diagnostics/src/Microsoft.Diagnostics.DebugServices.Implementation/Runtime.cs @@ -25,6 +25,7 @@ public class Runtime : IRuntime, IDisposable private Version _runtimeVersion; private ClrRuntime _clrRuntime; private string _dacFilePath; + private bool _verifySignature; // This only applies to the regular DAC, not the CDAC private string _cdacFilePath; private string _dbiFilePath; @@ -113,9 +114,11 @@ public string GetCDacFilePath() public string GetDacFilePath(out bool verifySignature) { - verifySignature = false; if (_settingsService.ForceUseContractReader) { + // Don't verify signature when using the CDAC and don't change the cached value + // because it only applies to the regular DAC in _dacFilePath. + verifySignature = false; return GetCDacFilePath(); } if (_dacFilePath is null) @@ -123,9 +126,10 @@ public string GetDacFilePath(out bool verifySignature) _dacFilePath = GetLibraryPath(DebugLibraryKind.Dac); if (_dacFilePath is not null) { - verifySignature = _settingsService.DacSignatureVerificationEnabled; + _verifySignature = _settingsService.DacSignatureVerificationEnabled; } } + verifySignature = _verifySignature; return _dacFilePath; } @@ -339,7 +343,8 @@ public override string ToString() if (_dacFilePath is not null) { sb.AppendLine(); - sb.Append($" DAC: {_dacFilePath}"); + string verify = _verifySignature ? "(verify)" : "(don't verify)"; + sb.Append($" DAC: {_dacFilePath} {verify}"); } if (_cdacFilePath is not null) { diff --git a/src/diagnostics/src/Microsoft.Diagnostics.ExtensionCommands/Host/CommandFormatHelpers.cs b/src/diagnostics/src/Microsoft.Diagnostics.ExtensionCommands/Host/CommandFormatHelpers.cs index 9b490156e43..8a7e2f69efc 100644 --- a/src/diagnostics/src/Microsoft.Diagnostics.ExtensionCommands/Host/CommandFormatHelpers.cs +++ b/src/diagnostics/src/Microsoft.Diagnostics.ExtensionCommands/Host/CommandFormatHelpers.cs @@ -16,6 +16,15 @@ public static class CommandFormatHelpers public const string DebugHeaderExport = "DotNetRuntimeDebugHeader"; public const string ContractDescriptorExport = "DotNetRuntimeContractDescriptor"; + public static void DisplaySettingService(this CommandBase command) + { + ISettingsService settingsService = command.Services.GetService() ?? throw new DiagnosticsException("Settings service required"); + command.Console.WriteLine("Settings:"); + command.Console.WriteLine($"-> Use CDAC contract reader: {settingsService.UseContractReader}"); + command.Console.WriteLine($"-> Force use CDAC contract reader: {settingsService.ForceUseContractReader}"); + command.Console.WriteLine($"-> DAC signature verification check enabled: {settingsService.DacSignatureVerificationEnabled}"); + } + /// /// Displays the special diagnostics info header memory block (.NET Core 8 or later on Linux/MacOS) /// diff --git a/src/diagnostics/src/Microsoft.Diagnostics.ExtensionCommands/Host/RuntimesCommand.cs b/src/diagnostics/src/Microsoft.Diagnostics.ExtensionCommands/Host/RuntimesCommand.cs index 95c93e8cef2..83c70cef29f 100644 --- a/src/diagnostics/src/Microsoft.Diagnostics.ExtensionCommands/Host/RuntimesCommand.cs +++ b/src/diagnostics/src/Microsoft.Diagnostics.ExtensionCommands/Host/RuntimesCommand.cs @@ -128,10 +128,8 @@ public override void Invoke() } this.DisplayResources(runtime.RuntimeModule, all: false, indent: " "); this.DisplayRuntimeExports(runtime.RuntimeModule, error: true, indent: " "); - WriteLine($"Use CDAC contract reader: {SettingsService.UseContractReader}"); - WriteLine($"Force use CDAC contract reader: {SettingsService.ForceUseContractReader}"); - WriteLine($"DAC signature verification check enabled: {SettingsService.DacSignatureVerificationEnabled}"); } + this.DisplaySettingService(); } } } diff --git a/src/diagnostics/src/Microsoft.Diagnostics.ExtensionCommands/Host/StatusCommand.cs b/src/diagnostics/src/Microsoft.Diagnostics.ExtensionCommands/Host/StatusCommand.cs index aa960e9d31f..3c425e251d2 100644 --- a/src/diagnostics/src/Microsoft.Diagnostics.ExtensionCommands/Host/StatusCommand.cs +++ b/src/diagnostics/src/Microsoft.Diagnostics.ExtensionCommands/Host/StatusCommand.cs @@ -63,6 +63,7 @@ public override void Invoke() } } this.DisplaySpecialInfo(); + this.DisplaySettingService(); Write(SymbolService.ToString()); List extensions = new(ServiceManager.ExtensionsLoaded); diff --git a/src/diagnostics/src/SOS/SOS.Extensions/HostServices.cs b/src/diagnostics/src/SOS/SOS.Extensions/HostServices.cs index 114d4d2b96c..04b401c647a 100644 --- a/src/diagnostics/src/SOS/SOS.Extensions/HostServices.cs +++ b/src/diagnostics/src/SOS/SOS.Extensions/HostServices.cs @@ -356,6 +356,10 @@ private int DispatchCommand( { return HResult.E_INVALIDARG; } + if (_commandService is null) + { + return HResult.E_FAIL; + } try { _commandService.Execute(commandName, commandArguments, string.Equals(commandName, "help", StringComparison.OrdinalIgnoreCase) ? _contextServiceFromDebuggerServices.Services : _servicesWithManagedOnlyFilter); diff --git a/src/diagnostics/src/SOS/SOS.Hosting/RuntimeWrapper.cs b/src/diagnostics/src/SOS/SOS.Hosting/RuntimeWrapper.cs index 98d223def6a..bfca28db91b 100644 --- a/src/diagnostics/src/SOS/SOS.Hosting/RuntimeWrapper.cs +++ b/src/diagnostics/src/SOS/SOS.Hosting/RuntimeWrapper.cs @@ -383,10 +383,9 @@ private IntPtr CreateClrDataProcess(IntPtr dacHandle) private IntPtr CreateCorDebugProcess() { string dbiFilePath = _runtime.GetDbiFilePath(); - string dacFilePath = _runtime.GetDacFilePath(out bool verifySignature); - if (dbiFilePath == null || dacFilePath == null) + if (dbiFilePath == null) { - Trace.TraceError($"Could not find matching DBI {dbiFilePath ?? ""} or DAC {dacFilePath ?? ""} for this runtime: {_runtime.RuntimeModule.FileName}"); + Trace.TraceError($"Could not find matching DBI {dbiFilePath ?? ""} for this runtime: {_runtime.RuntimeModule.FileName}"); return IntPtr.Zero; } if (_dbiHandle == IntPtr.Zero) @@ -415,6 +414,16 @@ private IntPtr CreateCorDebugProcess() int hresult = 0; try { + // This will verify the DAC signature if needed before DBI is passed the DAC path or handle + IntPtr dacHandle = GetDacHandle(); + if (dacHandle == IntPtr.Zero) + { + return IntPtr.Zero; + } + + // The DAC was verified in the GetDacHandle call above. Ignore the verifySignature parameter here. + string dacFilePath = _runtime.GetDacFilePath(out bool _); + OpenVirtualProcessImpl2Delegate openVirtualProcessImpl2 = SOSHost.GetDelegateFunction(_dbiHandle, "OpenVirtualProcessImpl2"); if (openVirtualProcessImpl2 != null) { @@ -436,12 +445,6 @@ private IntPtr CreateCorDebugProcess() return corDebugProcess; } - IntPtr dacHandle = GetDacHandle(); - if (dacHandle == IntPtr.Zero) - { - return IntPtr.Zero; - } - // On Linux/MacOS the DAC module handle needs to be re-created using the DAC PAL instance // before being passed to DBI's OpenVirtualProcess* implementation. The DBI and DAC share // the same PAL where dbgshim has it's own. diff --git a/src/source-manifest.json b/src/source-manifest.json index e9d95bc088c..451fe04c406 100644 --- a/src/source-manifest.json +++ b/src/source-manifest.json @@ -43,11 +43,11 @@ "commitSha": "e49e231fca51db9fad01d36efdd230d3307640cc" }, { - "packageVersion": "9.0.626202", - "barId": 267916, + "packageVersion": "9.0.626302", + "barId": 268091, "path": "diagnostics", "remoteUri": "https://github.com/dotnet/diagnostics", - "commitSha": "3a08702ea8e0083a74e10556c60c0bccd868b64a" + "commitSha": "a3c354f4ea00123f55276619455569d53c4c402d" }, { "packageVersion": "10.0.0-preview.4.25262.1", From f7f67237c93069471e81e0d0badf0101a9662755 Mon Sep 17 00:00:00 2001 From: Nikola Milosavljevic Date: Thu, 15 May 2025 03:26:09 -0700 Subject: [PATCH 02/11] Fix malformed NuGet.config file (#550) Co-authored-by: Viktor Hofer --- src/msbuild/NuGet.config | 36 ++++++++++++++++++++++++++++++------ 1 file changed, 30 insertions(+), 6 deletions(-) diff --git a/src/msbuild/NuGet.config b/src/msbuild/NuGet.config index a11137a9563..c39ceddacb7 100644 --- a/src/msbuild/NuGet.config +++ b/src/msbuild/NuGet.config @@ -15,13 +15,37 @@ - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + From 5d25cffcda9b2218fc91c59dfebef50cdd9c3f26 Mon Sep 17 00:00:00 2001 From: "dotnet-maestro[bot]" <42748379+dotnet-maestro[bot]@users.noreply.github.com> Date: Thu, 15 May 2025 10:28:30 +0000 Subject: [PATCH 03/11] [main] Update dependencies from dotnet/arcade-services (#555) Co-authored-by: dotnet-maestro[bot] Co-authored-by: Viktor Hofer --- .config/dotnet-tools.json | 2 +- eng/Version.Details.xml | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/.config/dotnet-tools.json b/.config/dotnet-tools.json index 73eb5d1d02d..f6232cee7e0 100644 --- a/.config/dotnet-tools.json +++ b/.config/dotnet-tools.json @@ -3,7 +3,7 @@ "isRoot": true, "tools": { "microsoft.dotnet.darc": { - "version": "1.1.0-beta.25263.3", + "version": "1.1.0-beta.25264.3", "commands": [ "darc" ] diff --git a/eng/Version.Details.xml b/eng/Version.Details.xml index dba5c7c0cb3..88649a1e361 100644 --- a/eng/Version.Details.xml +++ b/eng/Version.Details.xml @@ -10,9 +10,9 @@ https://github.com/dotnet/arcade e46d1266547513110e67a3e4709fe8ecdfb20849 - + https://github.com/dotnet/arcade-services - 4db7c74da4dcd71e2a5b4f5a65cc871dc06288d2 + 7126d7cb6f801691b0dfcc4e8357471f8dc750a9 From 939b700967fe234e8c465478ee59ea6258e49de5 Mon Sep 17 00:00:00 2001 From: "dotnet-maestro[bot]" <42748379+dotnet-maestro[bot]@users.noreply.github.com> Date: Thu, 15 May 2025 10:43:25 +0000 Subject: [PATCH 04/11] [main] Source code updates from dotnet/efcore (#563) Co-authored-by: dotnet-maestro[bot] Co-authored-by: Viktor Hofer --- prereqs/git-info/efcore.props | 6 +++--- .../Storage/RelationalDatabaseCreator.cs | 8 ++++++-- .../Storage/RelationalDatabaseCreatorDependencies.cs | 9 ++++++++- .../src/EFCore/Metadata/Builders/ConventionSetBuilder.cs | 8 ++++---- src/source-manifest.json | 6 +++--- 5 files changed, 24 insertions(+), 13 deletions(-) diff --git a/prereqs/git-info/efcore.props b/prereqs/git-info/efcore.props index 26e9db422d8..85db6ab251f 100644 --- a/prereqs/git-info/efcore.props +++ b/prereqs/git-info/efcore.props @@ -1,8 +1,8 @@  - 7a87abf268190f3a0d5f218e9b0b595360701af3 - 20250512.1 - 10.0.0-preview.4.25262.1 + 79501924853a69442628f286fb3fc3e165d370d3 + 20250514.1 + 10.0.0-preview.4.25264.1 \ No newline at end of file diff --git a/src/efcore/src/EFCore.Relational/Storage/RelationalDatabaseCreator.cs b/src/efcore/src/EFCore.Relational/Storage/RelationalDatabaseCreator.cs index 96f5ca0f76a..7ba78522385 100644 --- a/src/efcore/src/EFCore.Relational/Storage/RelationalDatabaseCreator.cs +++ b/src/efcore/src/EFCore.Relational/Storage/RelationalDatabaseCreator.cs @@ -373,7 +373,8 @@ public virtual bool CanConnect() /// /// /// - /// Any exceptions thrown when attempting to connect are caught and not propagated to the application. + /// Any exceptions thrown when attempting to connect are caught and not propagated to the application, + /// except for the ones indicating cancellation. /// /// /// The configured connection string is used to create the connection in the normal way, so all @@ -386,13 +387,16 @@ public virtual bool CanConnect() /// /// A to observe while waiting for the task to complete. /// if the database is available; otherwise. - /// If the is canceled. public virtual async Task CanConnectAsync(CancellationToken cancellationToken = default) { try { return await ExistsAsync(cancellationToken).ConfigureAwait(false); } + catch (Exception exception) when (Dependencies.ExceptionDetector.IsCancellation(exception, cancellationToken)) + { + throw; + } catch { return false; diff --git a/src/efcore/src/EFCore.Relational/Storage/RelationalDatabaseCreatorDependencies.cs b/src/efcore/src/EFCore.Relational/Storage/RelationalDatabaseCreatorDependencies.cs index 8343a802486..46966b3538b 100644 --- a/src/efcore/src/EFCore.Relational/Storage/RelationalDatabaseCreatorDependencies.cs +++ b/src/efcore/src/EFCore.Relational/Storage/RelationalDatabaseCreatorDependencies.cs @@ -54,7 +54,8 @@ public RelationalDatabaseCreatorDependencies( IExecutionStrategy executionStrategy, ICurrentDbContext currentContext, IDbContextOptions contextOptions, - IRelationalCommandDiagnosticsLogger commandLogger) + IRelationalCommandDiagnosticsLogger commandLogger, + IExceptionDetector exceptionDetector) { Connection = connection; ModelDiffer = modelDiffer; @@ -65,6 +66,7 @@ public RelationalDatabaseCreatorDependencies( CurrentContext = currentContext; ContextOptions = contextOptions; CommandLogger = commandLogger; + ExceptionDetector = exceptionDetector; } /// @@ -111,4 +113,9 @@ public RelationalDatabaseCreatorDependencies( /// Contains the currently in use. /// public ICurrentDbContext CurrentContext { get; init; } + + /// + /// Gets the exception detector. + /// + public IExceptionDetector ExceptionDetector { get; init; } } diff --git a/src/efcore/src/EFCore/Metadata/Builders/ConventionSetBuilder.cs b/src/efcore/src/EFCore/Metadata/Builders/ConventionSetBuilder.cs index a79c5f41313..ae3531c137c 100644 --- a/src/efcore/src/EFCore/Metadata/Builders/ConventionSetBuilder.cs +++ b/src/efcore/src/EFCore/Metadata/Builders/ConventionSetBuilder.cs @@ -68,10 +68,10 @@ public virtual void Remove(Type conventionType) /// /// Remove the convention of the given type. /// - /// The type of convention to remove - public virtual void Remove() - where TImplementaion : IConvention - => Remove(typeof(TImplementaion)); + /// The type of convention to remove + public virtual void Remove() + where TImplementation : IConvention + => Remove(typeof(TImplementation)); #region Hidden System.Object members diff --git a/src/source-manifest.json b/src/source-manifest.json index 451fe04c406..852588cfe24 100644 --- a/src/source-manifest.json +++ b/src/source-manifest.json @@ -50,11 +50,11 @@ "commitSha": "a3c354f4ea00123f55276619455569d53c4c402d" }, { - "packageVersion": "10.0.0-preview.4.25262.1", - "barId": 267844, + "packageVersion": "10.0.0-preview.4.25264.1", + "barId": 268185, "path": "efcore", "remoteUri": "https://github.com/dotnet/efcore", - "commitSha": "7a87abf268190f3a0d5f218e9b0b595360701af3" + "commitSha": "79501924853a69442628f286fb3fc3e165d370d3" }, { "packageVersion": "10.0.0-preview.5.25262.1", From e08668d780db5a5f88cb8505f321c9f31d775662 Mon Sep 17 00:00:00 2001 From: "dotnet-maestro[bot]" <42748379+dotnet-maestro[bot]@users.noreply.github.com> Date: Thu, 15 May 2025 10:50:15 +0000 Subject: [PATCH 05/11] [main] Source code updates from dotnet/aspnetcore (#567) Co-authored-by: dotnet-maestro[bot] Co-authored-by: Viktor Hofer --- prereqs/git-info/aspnetcore.props | 6 +- src/aspnetcore/eng/Versions.props | 4 +- .../src/PublicAPI.Unshipped.txt | 2 +- .../Validation/ValidatableParameterInfo.cs | 3 - .../src/Validation/ValidatablePropertyInfo.cs | 3 - .../src/Validation/ValidatableTypeInfo.cs | 2 - .../src/Validation/ValidateContext.cs | 19 ++- .../Validation/ValidatableTypeInfoTests.cs | 133 ++++++++---------- .../Emitters/ValidationsGenerator.Emitter.cs | 4 +- .../Extensions/ITypeSymbolExtensions.cs | 14 ++ .../ValidationsGenerator.TypesParser.cs | 13 ++ ...ValidationsGenerator.IValidatableObject.cs | 15 +- .../ValidationsGenerator.Parameters.cs | 17 ++- ...ypes#ValidatableInfoResolver.g.verified.cs | 4 +- ...ject#ValidatableInfoResolver.g.verified.cs | 4 +- ...ters#ValidatableInfoResolver.g.verified.cs | 23 ++- ...ypes#ValidatableInfoResolver.g.verified.cs | 4 +- ...ypes#ValidatableInfoResolver.g.verified.cs | 4 +- ...ypes#ValidatableInfoResolver.g.verified.cs | 4 +- ...ties#ValidatableInfoResolver.g.verified.cs | 4 +- ...bute#ValidatableInfoResolver.g.verified.cs | 4 +- ...ypes#ValidatableInfoResolver.g.verified.cs | 4 +- .../src/ValidationEndpointFilterFactory.cs | 40 +++++- .../test/EF.Test/UserStoreTest.cs | 3 + .../Extensions.Stores/src/UserStoreBase.cs | 2 +- .../gen/XmlCommentGenerator.Emitter.cs | 1 - .../Microbenchmarks/TransformersBenchmark.cs | 10 +- ...ApiXmlCommentSupport.generated.verified.cs | 1 - ...ApiXmlCommentSupport.generated.verified.cs | 1 - ...ApiXmlCommentSupport.generated.verified.cs | 1 - ...ApiXmlCommentSupport.generated.verified.cs | 1 - ...ApiXmlCommentSupport.generated.verified.cs | 1 - ...ApiXmlCommentSupport.generated.verified.cs | 1 - ...OpenApiSchemaService.PolymorphicSchemas.cs | 2 +- ...OpenApiSchemaService.RequestBodySchemas.cs | 2 +- .../OpenApiSchemaService.ResponseSchemas.cs | 2 +- .../CustomSchemaTransformerTests.cs | 4 +- .../OpenApiSchemaReferenceTransformerTests.cs | 6 +- .../Transformers/SchemaTransformerTests.cs | 74 +++++----- .../TypeBasedTransformerLifetimeTests.cs | 4 +- .../ThrowHelpers/ArgumentNullThrowHelper.cs | 23 +++ src/source-manifest.json | 6 +- 42 files changed, 308 insertions(+), 167 deletions(-) diff --git a/prereqs/git-info/aspnetcore.props b/prereqs/git-info/aspnetcore.props index ba97b21e61f..f095ff93c61 100644 --- a/prereqs/git-info/aspnetcore.props +++ b/prereqs/git-info/aspnetcore.props @@ -1,8 +1,8 @@  - 92072c79ed8c2c86b093ebd676d531f5e5bf406b - 20250513.4 - 10.0.0-preview.5.25263.4 + 343594eb69a5aa15377465351bb4381d9cee30c5 + 20250514.4 + 10.0.0-preview.5.25264.4 \ No newline at end of file diff --git a/src/aspnetcore/eng/Versions.props b/src/aspnetcore/eng/Versions.props index 5cef785a625..ed056a7a6f7 100644 --- a/src/aspnetcore/eng/Versions.props +++ b/src/aspnetcore/eng/Versions.props @@ -325,8 +325,8 @@ $(XunitVersion) 2.8.2 5.2.2 - 2.0.0-preview.17 - 2.0.0-preview.17 + 2.0.0-preview.18 + 2.0.0-preview.18 6.0.322601 1.10.93 diff --git a/src/aspnetcore/src/Http/Http.Abstractions/src/PublicAPI.Unshipped.txt b/src/aspnetcore/src/Http/Http.Abstractions/src/PublicAPI.Unshipped.txt index 2524b5a9cef..8cb332fa9f2 100644 --- a/src/aspnetcore/src/Http/Http.Abstractions/src/PublicAPI.Unshipped.txt +++ b/src/aspnetcore/src/Http/Http.Abstractions/src/PublicAPI.Unshipped.txt @@ -24,7 +24,7 @@ Microsoft.AspNetCore.Http.Validation.ValidateContext.CurrentDepth.set -> void Microsoft.AspNetCore.Http.Validation.ValidateContext.CurrentValidationPath.get -> string! Microsoft.AspNetCore.Http.Validation.ValidateContext.CurrentValidationPath.set -> void Microsoft.AspNetCore.Http.Validation.ValidateContext.ValidateContext() -> void -Microsoft.AspNetCore.Http.Validation.ValidateContext.ValidationContext.get -> System.ComponentModel.DataAnnotations.ValidationContext? +Microsoft.AspNetCore.Http.Validation.ValidateContext.ValidationContext.get -> System.ComponentModel.DataAnnotations.ValidationContext! Microsoft.AspNetCore.Http.Validation.ValidateContext.ValidationContext.set -> void Microsoft.AspNetCore.Http.Validation.ValidateContext.ValidationErrors.get -> System.Collections.Generic.Dictionary? Microsoft.AspNetCore.Http.Validation.ValidateContext.ValidationErrors.set -> void diff --git a/src/aspnetcore/src/Http/Http.Abstractions/src/Validation/ValidatableParameterInfo.cs b/src/aspnetcore/src/Http/Http.Abstractions/src/Validation/ValidatableParameterInfo.cs index 9fba8ab854b..48de32c0daf 100644 --- a/src/aspnetcore/src/Http/Http.Abstractions/src/Validation/ValidatableParameterInfo.cs +++ b/src/aspnetcore/src/Http/Http.Abstractions/src/Validation/ValidatableParameterInfo.cs @@ -3,7 +3,6 @@ using System.Collections; using System.ComponentModel.DataAnnotations; -using System.Diagnostics; using System.Diagnostics.CodeAnalysis; namespace Microsoft.AspNetCore.Http.Validation; @@ -60,8 +59,6 @@ protected ValidatableParameterInfo( /// public virtual async Task ValidateAsync(object? value, ValidateContext context, CancellationToken cancellationToken) { - Debug.Assert(context.ValidationContext is not null); - // Skip validation if value is null and parameter is optional if (value == null && ParameterType.IsNullable()) { diff --git a/src/aspnetcore/src/Http/Http.Abstractions/src/Validation/ValidatablePropertyInfo.cs b/src/aspnetcore/src/Http/Http.Abstractions/src/Validation/ValidatablePropertyInfo.cs index 167d5450046..0b16e34d1dc 100644 --- a/src/aspnetcore/src/Http/Http.Abstractions/src/Validation/ValidatablePropertyInfo.cs +++ b/src/aspnetcore/src/Http/Http.Abstractions/src/Validation/ValidatablePropertyInfo.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. using System.ComponentModel.DataAnnotations; -using System.Diagnostics; using System.Diagnostics.CodeAnalysis; namespace Microsoft.AspNetCore.Http.Validation; @@ -61,8 +60,6 @@ protected ValidatablePropertyInfo( /// public virtual async Task ValidateAsync(object? value, ValidateContext context, CancellationToken cancellationToken) { - Debug.Assert(context.ValidationContext is not null); - var property = DeclaringType.GetProperty(Name) ?? throw new InvalidOperationException($"Property '{Name}' not found on type '{DeclaringType.Name}'."); var propertyValue = property.GetValue(value); var validationAttributes = GetValidationAttributes(); diff --git a/src/aspnetcore/src/Http/Http.Abstractions/src/Validation/ValidatableTypeInfo.cs b/src/aspnetcore/src/Http/Http.Abstractions/src/Validation/ValidatableTypeInfo.cs index 82ae03465f9..6245c43c1b6 100644 --- a/src/aspnetcore/src/Http/Http.Abstractions/src/Validation/ValidatableTypeInfo.cs +++ b/src/aspnetcore/src/Http/Http.Abstractions/src/Validation/ValidatableTypeInfo.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. using System.ComponentModel.DataAnnotations; -using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; @@ -45,7 +44,6 @@ protected ValidatableTypeInfo( /// public virtual async Task ValidateAsync(object? value, ValidateContext context, CancellationToken cancellationToken) { - Debug.Assert(context.ValidationContext is not null); if (value == null) { return; diff --git a/src/aspnetcore/src/Http/Http.Abstractions/src/Validation/ValidateContext.cs b/src/aspnetcore/src/Http/Http.Abstractions/src/Validation/ValidateContext.cs index 3e02c35a472..d38ada2ddeb 100644 --- a/src/aspnetcore/src/Http/Http.Abstractions/src/Validation/ValidateContext.cs +++ b/src/aspnetcore/src/Http/Http.Abstractions/src/Validation/ValidateContext.cs @@ -16,7 +16,24 @@ public sealed class ValidateContext /// Gets or sets the validation context used for validating objects that implement or have . /// This context provides access to service provider and other validation metadata. /// - public ValidationContext? ValidationContext { get; set; } + /// + /// This property should be set by the consumer of the + /// interface to provide the necessary context for validation. The object should be initialized + /// with the current object being validated, the display name, and the service provider to support + /// the complete set of validation scenarios. + /// + /// + /// + /// var validationContext = new ValidationContext(objectToValidate, serviceProvider, items); + /// var validationOptions = serviceProvider.GetService<IOptions<ValidationOptions>>()?.Value; + /// var validateContext = new ValidateContext + /// { + /// ValidationContext = validationContext, + /// ValidationOptions = validationOptions + /// }; + /// + /// + public required ValidationContext ValidationContext { get; set; } /// /// Gets or sets the prefix used to identify the current object being validated in a complex object graph. diff --git a/src/aspnetcore/src/Http/Http.Abstractions/test/Validation/ValidatableTypeInfoTests.cs b/src/aspnetcore/src/Http/Http.Abstractions/test/Validation/ValidatableTypeInfoTests.cs index 98e74bd9d32..a6123bb11c6 100644 --- a/src/aspnetcore/src/Http/Http.Abstractions/test/Validation/ValidatableTypeInfoTests.cs +++ b/src/aspnetcore/src/Http/Http.Abstractions/test/Validation/ValidatableTypeInfoTests.cs @@ -41,17 +41,16 @@ [new RequiredAttribute()]) { typeof(Address), addressType } }); - var context = new ValidateContext - { - ValidationOptions = validationOptions, - }; - var personWithMissingRequiredFields = new Person { Age = 150, // Invalid age Address = new Address() // Missing required City and Street }; - context.ValidationContext = new ValidationContext(personWithMissingRequiredFields); + var context = new ValidateContext + { + ValidationOptions = validationOptions, + ValidationContext = new ValidationContext(personWithMissingRequiredFields) + }; // Act await personType.ValidateAsync(personWithMissingRequiredFields, context, default); @@ -96,21 +95,20 @@ [new RequiredAttribute()]), []) ]); - var context = new ValidateContext - { - ValidationOptions = new TestValidationOptions(new Dictionary - { - { typeof(Employee), employeeType } - }) - }; - var employee = new Employee { Name = "John Doe", Department = "IT", Salary = -5000 // Negative salary will trigger IValidatableObject validation }; - context.ValidationContext = new ValidationContext(employee); + var context = new ValidateContext + { + ValidationOptions = new TestValidationOptions(new Dictionary + { + { typeof(Employee), employeeType } + }), + ValidationContext = new ValidationContext(employee) + }; // Act await employeeType.ValidateAsync(employee, context, default); @@ -142,22 +140,21 @@ [new RequiredAttribute()]) [new RangeAttribute(2, 5)]) ]); + var car = new Car + { + // Missing Make and Model (required in base type) + Doors = 7 // Invalid number of doors + }; var context = new ValidateContext { ValidationOptions = new TestValidationOptions(new Dictionary { { typeof(Vehicle), baseType }, { typeof(Car), derivedType } - }) + }), + ValidationContext = new ValidationContext(car) }; - var car = new Car - { - // Missing Make and Model (required in base type) - Doors = 7 // Invalid number of doors - }; - context.ValidationContext = new ValidationContext(car); - // Act await derivedType.ValidateAsync(car, context, default); @@ -203,15 +200,6 @@ [new RequiredAttribute()]), []) ]); - var context = new ValidateContext - { - ValidationOptions = new TestValidationOptions(new Dictionary - { - { typeof(OrderItem), itemType }, - { typeof(Order), orderType } - }) - }; - var order = new Order { OrderNumber = "ORD-12345", @@ -222,7 +210,15 @@ [new RequiredAttribute()]), new OrderItem { ProductName = "Another Product", Quantity = 200 /* Invalid quantity */ } ] }; - context.ValidationContext = new ValidationContext(order); + var context = new ValidateContext + { + ValidationOptions = new TestValidationOptions(new Dictionary + { + { typeof(OrderItem), itemType }, + { typeof(Order), orderType } + }), + ValidationContext = new ValidationContext(order) + }; // Act await orderType.ValidateAsync(order, context, default); @@ -260,20 +256,19 @@ public async Task Validate_HandlesNullValues_Appropriately() []) ]); + var person = new Person + { + Name = null, + Address = null + }; var context = new ValidateContext { ValidationOptions = new TestValidationOptions(new Dictionary { { typeof(Person), personType } - }) - }; - - var person = new Person - { - Name = null, - Address = null + }), + ValidationContext = new ValidationContext(person) }; - context.ValidationContext = new ValidationContext(person); // Act await personType.ValidateAsync(person, context, default); @@ -305,12 +300,6 @@ [new RequiredAttribute()]), }); validationOptions.MaxDepth = 3; // Set a small max depth to trigger the limit - var context = new ValidateContext - { - ValidationOptions = validationOptions, - ValidationErrors = [] - }; - // Create a deep tree with circular references var rootNode = new TreeNode { Name = "Root" }; var level1 = new TreeNode { Name = "Level1", Parent = rootNode }; @@ -328,7 +317,12 @@ [new RequiredAttribute()]), // Add a circular reference level5.Children.Add(rootNode); - context.ValidationContext = new ValidationContext(rootNode); + var context = new ValidateContext + { + ValidationOptions = validationOptions, + ValidationErrors = [], + ValidationContext = new ValidationContext(rootNode) + }; // Act + Assert var exception = await Assert.ThrowsAsync( @@ -349,17 +343,16 @@ public async Task Validate_HandlesCustomValidationAttributes() CreatePropertyInfo(typeof(Product), typeof(string), "SKU", "SKU", [new RequiredAttribute(), new CustomSkuValidationAttribute()]), ]); + var product = new Product { SKU = "INVALID-SKU" }; var context = new ValidateContext { ValidationOptions = new TestValidationOptions(new Dictionary { { typeof(Product), productType } - }) + }), + ValidationContext = new ValidationContext(product) }; - var product = new Product { SKU = "INVALID-SKU" }; - context.ValidationContext = new ValidationContext(product); - // Act await productType.ValidateAsync(product, context, default); @@ -385,17 +378,16 @@ public async Task Validate_HandlesMultipleErrorsOnSameProperty() ]) ]); + var user = new User { Password = "abc" }; // Too short and not complex enough var context = new ValidateContext { ValidationOptions = new TestValidationOptions(new Dictionary { { typeof(User), userType } - }) + }), + ValidationContext = new ValidationContext(user) }; - var user = new User { Password = "abc" }; // Too short and not complex enough - context.ValidationContext = new ValidationContext(user); - // Act await userType.ValidateAsync(user, context, default); @@ -429,6 +421,11 @@ public async Task Validate_HandlesMultiLevelInheritance() CreatePropertyInfo(typeof(DerivedEntity), typeof(string), "Name", "Name", [new RequiredAttribute()]) ]); + var entity = new DerivedEntity + { + Name = "", // Invalid: required + CreatedAt = DateTime.Now.AddDays(1) // Invalid: future date + }; var context = new ValidateContext { ValidationOptions = new TestValidationOptions(new Dictionary @@ -436,16 +433,10 @@ public async Task Validate_HandlesMultiLevelInheritance() { typeof(BaseEntity), baseType }, { typeof(IntermediateEntity), intermediateType }, { typeof(DerivedEntity), derivedType } - }) + }), + ValidationContext = new ValidationContext(entity) }; - var entity = new DerivedEntity - { - Name = "", // Invalid: required - CreatedAt = DateTime.Now.AddDays(1) // Invalid: future date - }; - context.ValidationContext = new ValidationContext(entity); - // Act await derivedType.ValidateAsync(entity, context, default); @@ -475,17 +466,16 @@ public async Task Validate_RequiredOnPropertyShortCircuitsOtherValidations() [new RequiredAttribute(), new PasswordComplexityAttribute()]) ]); + var user = new User { Password = null }; // Invalid: required var context = new ValidateContext { ValidationOptions = new TestValidationOptions(new Dictionary { { typeof(User), userType } - }) + }), + ValidationContext = new ValidationContext(user) // Invalid: required }; - var user = new User { Password = null }; // Invalid: required - context.ValidationContext = new ValidationContext(user); - // Act await userType.ValidateAsync(user, context, default); @@ -503,18 +493,17 @@ public async Task Validate_IValidatableObject_WithZeroAndMultipleMemberNames_Beh var globalType = new TestValidatableTypeInfo( typeof(GlobalErrorObject), []); // no properties – nothing sets MemberName + var globalErrorInstance = new GlobalErrorObject { Data = -1 }; var context = new ValidateContext { ValidationOptions = new TestValidationOptions(new Dictionary { { typeof(GlobalErrorObject), globalType } - }) + }), + ValidationContext = new ValidationContext(globalErrorInstance) }; - var globalErrorInstance = new GlobalErrorObject { Data = -1 }; - context.ValidationContext = new ValidationContext(globalErrorInstance); - await globalType.ValidateAsync(globalErrorInstance, context, default); Assert.NotNull(context.ValidationErrors); diff --git a/src/aspnetcore/src/Http/Http.Extensions/gen/Microsoft.AspNetCore.Http.ValidationsGenerator/Emitters/ValidationsGenerator.Emitter.cs b/src/aspnetcore/src/Http/Http.Extensions/gen/Microsoft.AspNetCore.Http.ValidationsGenerator/Emitters/ValidationsGenerator.Emitter.cs index b929819c591..5d4e9fdaba5 100644 --- a/src/aspnetcore/src/Http/Http.Extensions/gen/Microsoft.AspNetCore.Http.ValidationsGenerator/Emitters/ValidationsGenerator.Emitter.cs +++ b/src/aspnetcore/src/Http/Http.Extensions/gen/Microsoft.AspNetCore.Http.ValidationsGenerator/Emitters/ValidationsGenerator.Emitter.cs @@ -67,6 +67,7 @@ public GeneratedValidatablePropertyInfo( Name = name; } + [global::System.Diagnostics.CodeAnalysis.DynamicallyAccessedMembers(global::System.Diagnostics.CodeAnalysis.DynamicallyAccessedMemberTypes.PublicProperties)] internal global::System.Type ContainingType { get; } internal string Name { get; } @@ -124,10 +125,11 @@ file static class GeneratedServiceCollectionExtensions {{GeneratedCodeAttribute}} file static class ValidationAttributeCache { - private sealed record CacheKey(global::System.Type ContainingType, string PropertyName); + private sealed record CacheKey([property: global::System.Diagnostics.CodeAnalysis.DynamicallyAccessedMembers(global::System.Diagnostics.CodeAnalysis.DynamicallyAccessedMemberTypes.PublicProperties)] global::System.Type ContainingType, string PropertyName); private static readonly global::System.Collections.Concurrent.ConcurrentDictionary _cache = new(); public static global::System.ComponentModel.DataAnnotations.ValidationAttribute[] GetValidationAttributes( + [global::System.Diagnostics.CodeAnalysis.DynamicallyAccessedMembers(global::System.Diagnostics.CodeAnalysis.DynamicallyAccessedMemberTypes.PublicProperties)] global::System.Type containingType, string propertyName) { diff --git a/src/aspnetcore/src/Http/Http.Extensions/gen/Microsoft.AspNetCore.Http.ValidationsGenerator/Extensions/ITypeSymbolExtensions.cs b/src/aspnetcore/src/Http/Http.Extensions/gen/Microsoft.AspNetCore.Http.ValidationsGenerator/Extensions/ITypeSymbolExtensions.cs index 89392a93849..0cd85d9df75 100644 --- a/src/aspnetcore/src/Http/Http.Extensions/gen/Microsoft.AspNetCore.Http.ValidationsGenerator/Extensions/ITypeSymbolExtensions.cs +++ b/src/aspnetcore/src/Http/Http.Extensions/gen/Microsoft.AspNetCore.Http.ValidationsGenerator/Extensions/ITypeSymbolExtensions.cs @@ -124,4 +124,18 @@ internal static bool IsExemptType(this ITypeSymbol type, WellKnownTypes wellKnow return null; } + + /// + /// Checks if the parameter is marked with [FromService] or [FromKeyedService] attributes. + /// + /// The parameter to check. + /// The symbol representing the [FromService] attribute. + /// The symbol representing the [FromKeyedService] attribute. + internal static bool IsServiceParameter(this IParameterSymbol parameter, INamedTypeSymbol fromServiceMetadataSymbol, INamedTypeSymbol fromKeyedServiceAttributeSymbol) + { + return parameter.GetAttributes().Any(attr => + attr.AttributeClass is not null && + (attr.AttributeClass.ImplementsInterface(fromServiceMetadataSymbol) || + SymbolEqualityComparer.Default.Equals(attr.AttributeClass, fromKeyedServiceAttributeSymbol))); + } } diff --git a/src/aspnetcore/src/Http/Http.Extensions/gen/Microsoft.AspNetCore.Http.ValidationsGenerator/Parsers/ValidationsGenerator.TypesParser.cs b/src/aspnetcore/src/Http/Http.Extensions/gen/Microsoft.AspNetCore.Http.ValidationsGenerator/Parsers/ValidationsGenerator.TypesParser.cs index dd0092f31fd..482a90c334b 100644 --- a/src/aspnetcore/src/Http/Http.Extensions/gen/Microsoft.AspNetCore.Http.ValidationsGenerator/Parsers/ValidationsGenerator.TypesParser.cs +++ b/src/aspnetcore/src/Http/Http.Extensions/gen/Microsoft.AspNetCore.Http.ValidationsGenerator/Parsers/ValidationsGenerator.TypesParser.cs @@ -25,10 +25,23 @@ internal ImmutableArray ExtractValidatableTypes(IInvocationOper var parameters = operation.TryGetRouteHandlerMethod(operation.SemanticModel, out var method) ? method.Parameters : []; + + var fromServiceMetadataSymbol = wellKnownTypes.Get( + WellKnownTypeData.WellKnownType.Microsoft_AspNetCore_Http_Metadata_IFromServiceMetadata); + var fromKeyedServiceAttributeSymbol = wellKnownTypes.Get( + WellKnownTypeData.WellKnownType.Microsoft_Extensions_DependencyInjection_FromKeyedServicesAttribute); + var validatableTypes = new HashSet(ValidatableTypeComparer.Instance); List visitedTypes = []; + foreach (var parameter in parameters) { + // Skip parameters that are injected as services + if (parameter.IsServiceParameter(fromServiceMetadataSymbol, fromKeyedServiceAttributeSymbol)) + { + continue; + } + _ = TryExtractValidatableType(parameter.Type, wellKnownTypes, ref validatableTypes, ref visitedTypes); } return [.. validatableTypes]; diff --git a/src/aspnetcore/src/Http/Http.Extensions/test/ValidationsGenerator/ValidationsGenerator.IValidatableObject.cs b/src/aspnetcore/src/Http/Http.Extensions/test/ValidationsGenerator/ValidationsGenerator.IValidatableObject.cs index d50498d4a99..70f1d725bc7 100644 --- a/src/aspnetcore/src/Http/Http.Extensions/test/ValidationsGenerator/ValidationsGenerator.IValidatableObject.cs +++ b/src/aspnetcore/src/Http/Http.Extensions/test/ValidationsGenerator/ValidationsGenerator.IValidatableObject.cs @@ -15,16 +15,23 @@ public async Task CanValidateIValidatableObject() using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http.Validation; +using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Routing; using Microsoft.Extensions.DependencyInjection; var builder = WebApplication.CreateBuilder(); builder.Services.AddSingleton(); +builder.Services.AddKeyedSingleton("serviceKey"); builder.Services.AddValidation(); var app = builder.Build(); -app.MapPost("/validatable-object", (ComplexValidatableType model) => Results.Ok()); +app.MapPost("/validatable-object", ( + ComplexValidatableType model, + // Demonstrates that parameters that are annotated with [FromService] are not processed + // by the source generator and not emitted as ValidatableTypes in the generated code. + [FromServices] IRangeService rangeService, + [FromKeyedServices("serviceKey")] TestService testService) => Results.Ok(rangeService.GetMinimum())); app.Run(); @@ -86,6 +93,12 @@ public class RangeService : IRangeService public int GetMinimum() => 10; public int GetMaximum() => 100; } + +public class TestService +{ + [Range(10, 100)] + public int Value { get; set; } = 4; +} """; await Verify(source, out var compilation); diff --git a/src/aspnetcore/src/Http/Http.Extensions/test/ValidationsGenerator/ValidationsGenerator.Parameters.cs b/src/aspnetcore/src/Http/Http.Extensions/test/ValidationsGenerator/ValidationsGenerator.Parameters.cs index 3be6e96fe7a..7494e27efa2 100644 --- a/src/aspnetcore/src/Http/Http.Extensions/test/ValidationsGenerator/ValidationsGenerator.Parameters.cs +++ b/src/aspnetcore/src/Http/Http.Extensions/test/ValidationsGenerator/ValidationsGenerator.Parameters.cs @@ -16,21 +16,30 @@ public async Task CanValidateParameters() using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http.Validation; +using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Routing; using Microsoft.Extensions.DependencyInjection; var builder = WebApplication.CreateBuilder(); builder.Services.AddValidation(); +builder.Services.AddSingleton(); +builder.Services.AddKeyedSingleton("serviceKey"); var app = builder.Build(); app.MapGet("/params", ( + // Skipped from validation because it is resolved as a service by IServiceProviderIsService + TestService testService, + // Skipped from validation because it is marked as a [FromKeyedService] parameter + [FromKeyedServices("serviceKey")] TestService testService2, [Range(10, 100)] int value1, [Range(10, 100), Display(Name = "Valid identifier")] int value2, [Required] string value3 = "some-value", [CustomValidation(ErrorMessage = "Value must be an even number")] int value4 = 4, - [CustomValidation, Range(10, 100)] int value5 = 10) => "OK"); + [CustomValidation, Range(10, 100)] int value5 = 10, + // Skipped from validation because it is marked as a [FromService] parameter + [FromServices] [Range(10, 100)] int? value6 = 4) => "OK"); app.Run(); @@ -38,6 +47,12 @@ public class CustomValidationAttribute : ValidationAttribute { public override bool IsValid(object? value) => value is int number && number % 2 == 0; } + +public class TestService +{ + [Range(10, 100)] + public int Value { get; set; } = 4; +} """; await Verify(source, out var compilation); await VerifyEndpoint(compilation, "/params", async (endpoint, serviceProvider) => diff --git a/src/aspnetcore/src/Http/Http.Extensions/test/ValidationsGenerator/snapshots/ValidationsGeneratorTests.CanValidateComplexTypes#ValidatableInfoResolver.g.verified.cs b/src/aspnetcore/src/Http/Http.Extensions/test/ValidationsGenerator/snapshots/ValidationsGeneratorTests.CanValidateComplexTypes#ValidatableInfoResolver.g.verified.cs index 046365541ef..74899270ca0 100644 --- a/src/aspnetcore/src/Http/Http.Extensions/test/ValidationsGenerator/snapshots/ValidationsGeneratorTests.CanValidateComplexTypes#ValidatableInfoResolver.g.verified.cs +++ b/src/aspnetcore/src/Http/Http.Extensions/test/ValidationsGenerator/snapshots/ValidationsGeneratorTests.CanValidateComplexTypes#ValidatableInfoResolver.g.verified.cs @@ -39,6 +39,7 @@ public GeneratedValidatablePropertyInfo( Name = name; } + [global::System.Diagnostics.CodeAnalysis.DynamicallyAccessedMembers(global::System.Diagnostics.CodeAnalysis.DynamicallyAccessedMemberTypes.PublicProperties)] internal global::System.Type ContainingType { get; } internal string Name { get; } @@ -207,10 +208,11 @@ file static class GeneratedServiceCollectionExtensions [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.AspNetCore.Http.ValidationsGenerator, Version=42.42.42.42, Culture=neutral, PublicKeyToken=adb9793829ddae60", "42.42.42.42")] file static class ValidationAttributeCache { - private sealed record CacheKey(global::System.Type ContainingType, string PropertyName); + private sealed record CacheKey([property: global::System.Diagnostics.CodeAnalysis.DynamicallyAccessedMembers(global::System.Diagnostics.CodeAnalysis.DynamicallyAccessedMemberTypes.PublicProperties)] global::System.Type ContainingType, string PropertyName); private static readonly global::System.Collections.Concurrent.ConcurrentDictionary _cache = new(); public static global::System.ComponentModel.DataAnnotations.ValidationAttribute[] GetValidationAttributes( + [global::System.Diagnostics.CodeAnalysis.DynamicallyAccessedMembers(global::System.Diagnostics.CodeAnalysis.DynamicallyAccessedMemberTypes.PublicProperties)] global::System.Type containingType, string propertyName) { diff --git a/src/aspnetcore/src/Http/Http.Extensions/test/ValidationsGenerator/snapshots/ValidationsGeneratorTests.CanValidateIValidatableObject#ValidatableInfoResolver.g.verified.cs b/src/aspnetcore/src/Http/Http.Extensions/test/ValidationsGenerator/snapshots/ValidationsGeneratorTests.CanValidateIValidatableObject#ValidatableInfoResolver.g.verified.cs index 5babdce85f2..997eecca5ec 100644 --- a/src/aspnetcore/src/Http/Http.Extensions/test/ValidationsGenerator/snapshots/ValidationsGeneratorTests.CanValidateIValidatableObject#ValidatableInfoResolver.g.verified.cs +++ b/src/aspnetcore/src/Http/Http.Extensions/test/ValidationsGenerator/snapshots/ValidationsGeneratorTests.CanValidateIValidatableObject#ValidatableInfoResolver.g.verified.cs @@ -39,6 +39,7 @@ public GeneratedValidatablePropertyInfo( Name = name; } + [global::System.Diagnostics.CodeAnalysis.DynamicallyAccessedMembers(global::System.Diagnostics.CodeAnalysis.DynamicallyAccessedMemberTypes.PublicProperties)] internal global::System.Type ContainingType { get; } internal string Name { get; } @@ -158,10 +159,11 @@ file static class GeneratedServiceCollectionExtensions [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.AspNetCore.Http.ValidationsGenerator, Version=42.42.42.42, Culture=neutral, PublicKeyToken=adb9793829ddae60", "42.42.42.42")] file static class ValidationAttributeCache { - private sealed record CacheKey(global::System.Type ContainingType, string PropertyName); + private sealed record CacheKey([property: global::System.Diagnostics.CodeAnalysis.DynamicallyAccessedMembers(global::System.Diagnostics.CodeAnalysis.DynamicallyAccessedMemberTypes.PublicProperties)] global::System.Type ContainingType, string PropertyName); private static readonly global::System.Collections.Concurrent.ConcurrentDictionary _cache = new(); public static global::System.ComponentModel.DataAnnotations.ValidationAttribute[] GetValidationAttributes( + [global::System.Diagnostics.CodeAnalysis.DynamicallyAccessedMembers(global::System.Diagnostics.CodeAnalysis.DynamicallyAccessedMemberTypes.PublicProperties)] global::System.Type containingType, string propertyName) { diff --git a/src/aspnetcore/src/Http/Http.Extensions/test/ValidationsGenerator/snapshots/ValidationsGeneratorTests.CanValidateParameters#ValidatableInfoResolver.g.verified.cs b/src/aspnetcore/src/Http/Http.Extensions/test/ValidationsGenerator/snapshots/ValidationsGeneratorTests.CanValidateParameters#ValidatableInfoResolver.g.verified.cs index ddd57a0dc8b..2b7c2a0c272 100644 --- a/src/aspnetcore/src/Http/Http.Extensions/test/ValidationsGenerator/snapshots/ValidationsGeneratorTests.CanValidateParameters#ValidatableInfoResolver.g.verified.cs +++ b/src/aspnetcore/src/Http/Http.Extensions/test/ValidationsGenerator/snapshots/ValidationsGeneratorTests.CanValidateParameters#ValidatableInfoResolver.g.verified.cs @@ -39,6 +39,7 @@ public GeneratedValidatablePropertyInfo( Name = name; } + [global::System.Diagnostics.CodeAnalysis.DynamicallyAccessedMembers(global::System.Diagnostics.CodeAnalysis.DynamicallyAccessedMemberTypes.PublicProperties)] internal global::System.Type ContainingType { get; } internal string Name { get; } @@ -61,6 +62,11 @@ public GeneratedValidatableTypeInfo( public bool TryGetValidatableTypeInfo(global::System.Type type, [global::System.Diagnostics.CodeAnalysis.NotNullWhen(true)] out global::Microsoft.AspNetCore.Http.Validation.IValidatableInfo? validatableInfo) { validatableInfo = null; + if (type == typeof(global::TestService)) + { + validatableInfo = CreateTestService(); + return true; + } return false; } @@ -72,6 +78,20 @@ public bool TryGetValidatableParameterInfo(global::System.Reflection.ParameterIn return false; } + private ValidatableTypeInfo CreateTestService() + { + return new GeneratedValidatableTypeInfo( + type: typeof(global::TestService), + members: [ + new GeneratedValidatablePropertyInfo( + containingType: typeof(global::TestService), + propertyType: typeof(int), + name: "Value", + displayName: "Value" + ), + ] + ); + } } @@ -96,10 +116,11 @@ file static class GeneratedServiceCollectionExtensions [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.AspNetCore.Http.ValidationsGenerator, Version=42.42.42.42, Culture=neutral, PublicKeyToken=adb9793829ddae60", "42.42.42.42")] file static class ValidationAttributeCache { - private sealed record CacheKey(global::System.Type ContainingType, string PropertyName); + private sealed record CacheKey([property: global::System.Diagnostics.CodeAnalysis.DynamicallyAccessedMembers(global::System.Diagnostics.CodeAnalysis.DynamicallyAccessedMemberTypes.PublicProperties)] global::System.Type ContainingType, string PropertyName); private static readonly global::System.Collections.Concurrent.ConcurrentDictionary _cache = new(); public static global::System.ComponentModel.DataAnnotations.ValidationAttribute[] GetValidationAttributes( + [global::System.Diagnostics.CodeAnalysis.DynamicallyAccessedMembers(global::System.Diagnostics.CodeAnalysis.DynamicallyAccessedMemberTypes.PublicProperties)] global::System.Type containingType, string propertyName) { diff --git a/src/aspnetcore/src/Http/Http.Extensions/test/ValidationsGenerator/snapshots/ValidationsGeneratorTests.CanValidatePolymorphicTypes#ValidatableInfoResolver.g.verified.cs b/src/aspnetcore/src/Http/Http.Extensions/test/ValidationsGenerator/snapshots/ValidationsGeneratorTests.CanValidatePolymorphicTypes#ValidatableInfoResolver.g.verified.cs index d435bf7996f..b85bdf853f4 100644 --- a/src/aspnetcore/src/Http/Http.Extensions/test/ValidationsGenerator/snapshots/ValidationsGeneratorTests.CanValidatePolymorphicTypes#ValidatableInfoResolver.g.verified.cs +++ b/src/aspnetcore/src/Http/Http.Extensions/test/ValidationsGenerator/snapshots/ValidationsGeneratorTests.CanValidatePolymorphicTypes#ValidatableInfoResolver.g.verified.cs @@ -39,6 +39,7 @@ public GeneratedValidatablePropertyInfo( Name = name; } + [global::System.Diagnostics.CodeAnalysis.DynamicallyAccessedMembers(global::System.Diagnostics.CodeAnalysis.DynamicallyAccessedMemberTypes.PublicProperties)] internal global::System.Type ContainingType { get; } internal string Name { get; } @@ -196,10 +197,11 @@ file static class GeneratedServiceCollectionExtensions [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.AspNetCore.Http.ValidationsGenerator, Version=42.42.42.42, Culture=neutral, PublicKeyToken=adb9793829ddae60", "42.42.42.42")] file static class ValidationAttributeCache { - private sealed record CacheKey(global::System.Type ContainingType, string PropertyName); + private sealed record CacheKey([property: global::System.Diagnostics.CodeAnalysis.DynamicallyAccessedMembers(global::System.Diagnostics.CodeAnalysis.DynamicallyAccessedMemberTypes.PublicProperties)] global::System.Type ContainingType, string PropertyName); private static readonly global::System.Collections.Concurrent.ConcurrentDictionary _cache = new(); public static global::System.ComponentModel.DataAnnotations.ValidationAttribute[] GetValidationAttributes( + [global::System.Diagnostics.CodeAnalysis.DynamicallyAccessedMembers(global::System.Diagnostics.CodeAnalysis.DynamicallyAccessedMemberTypes.PublicProperties)] global::System.Type containingType, string propertyName) { diff --git a/src/aspnetcore/src/Http/Http.Extensions/test/ValidationsGenerator/snapshots/ValidationsGeneratorTests.CanValidateRecordTypes#ValidatableInfoResolver.g.verified.cs b/src/aspnetcore/src/Http/Http.Extensions/test/ValidationsGenerator/snapshots/ValidationsGeneratorTests.CanValidateRecordTypes#ValidatableInfoResolver.g.verified.cs index 2a5085a534a..03a4b0af066 100644 --- a/src/aspnetcore/src/Http/Http.Extensions/test/ValidationsGenerator/snapshots/ValidationsGeneratorTests.CanValidateRecordTypes#ValidatableInfoResolver.g.verified.cs +++ b/src/aspnetcore/src/Http/Http.Extensions/test/ValidationsGenerator/snapshots/ValidationsGeneratorTests.CanValidateRecordTypes#ValidatableInfoResolver.g.verified.cs @@ -39,6 +39,7 @@ public GeneratedValidatablePropertyInfo( Name = name; } + [global::System.Diagnostics.CodeAnalysis.DynamicallyAccessedMembers(global::System.Diagnostics.CodeAnalysis.DynamicallyAccessedMemberTypes.PublicProperties)] internal global::System.Type ContainingType { get; } internal string Name { get; } @@ -238,10 +239,11 @@ file static class GeneratedServiceCollectionExtensions [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.AspNetCore.Http.ValidationsGenerator, Version=42.42.42.42, Culture=neutral, PublicKeyToken=adb9793829ddae60", "42.42.42.42")] file static class ValidationAttributeCache { - private sealed record CacheKey(global::System.Type ContainingType, string PropertyName); + private sealed record CacheKey([property: global::System.Diagnostics.CodeAnalysis.DynamicallyAccessedMembers(global::System.Diagnostics.CodeAnalysis.DynamicallyAccessedMemberTypes.PublicProperties)] global::System.Type ContainingType, string PropertyName); private static readonly global::System.Collections.Concurrent.ConcurrentDictionary _cache = new(); public static global::System.ComponentModel.DataAnnotations.ValidationAttribute[] GetValidationAttributes( + [global::System.Diagnostics.CodeAnalysis.DynamicallyAccessedMembers(global::System.Diagnostics.CodeAnalysis.DynamicallyAccessedMemberTypes.PublicProperties)] global::System.Type containingType, string propertyName) { diff --git a/src/aspnetcore/src/Http/Http.Extensions/test/ValidationsGenerator/snapshots/ValidationsGeneratorTests.CanValidateRecursiveTypes#ValidatableInfoResolver.g.verified.cs b/src/aspnetcore/src/Http/Http.Extensions/test/ValidationsGenerator/snapshots/ValidationsGeneratorTests.CanValidateRecursiveTypes#ValidatableInfoResolver.g.verified.cs index 7fb61484070..65848f1ab71 100644 --- a/src/aspnetcore/src/Http/Http.Extensions/test/ValidationsGenerator/snapshots/ValidationsGeneratorTests.CanValidateRecursiveTypes#ValidatableInfoResolver.g.verified.cs +++ b/src/aspnetcore/src/Http/Http.Extensions/test/ValidationsGenerator/snapshots/ValidationsGeneratorTests.CanValidateRecursiveTypes#ValidatableInfoResolver.g.verified.cs @@ -39,6 +39,7 @@ public GeneratedValidatablePropertyInfo( Name = name; } + [global::System.Diagnostics.CodeAnalysis.DynamicallyAccessedMembers(global::System.Diagnostics.CodeAnalysis.DynamicallyAccessedMemberTypes.PublicProperties)] internal global::System.Type ContainingType { get; } internal string Name { get; } @@ -121,10 +122,11 @@ file static class GeneratedServiceCollectionExtensions [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.AspNetCore.Http.ValidationsGenerator, Version=42.42.42.42, Culture=neutral, PublicKeyToken=adb9793829ddae60", "42.42.42.42")] file static class ValidationAttributeCache { - private sealed record CacheKey(global::System.Type ContainingType, string PropertyName); + private sealed record CacheKey([property: global::System.Diagnostics.CodeAnalysis.DynamicallyAccessedMembers(global::System.Diagnostics.CodeAnalysis.DynamicallyAccessedMemberTypes.PublicProperties)] global::System.Type ContainingType, string PropertyName); private static readonly global::System.Collections.Concurrent.ConcurrentDictionary _cache = new(); public static global::System.ComponentModel.DataAnnotations.ValidationAttribute[] GetValidationAttributes( + [global::System.Diagnostics.CodeAnalysis.DynamicallyAccessedMembers(global::System.Diagnostics.CodeAnalysis.DynamicallyAccessedMemberTypes.PublicProperties)] global::System.Type containingType, string propertyName) { diff --git a/src/aspnetcore/src/Http/Http.Extensions/test/ValidationsGenerator/snapshots/ValidationsGeneratorTests.CanValidateTypeWithParsableProperties#ValidatableInfoResolver.g.verified.cs b/src/aspnetcore/src/Http/Http.Extensions/test/ValidationsGenerator/snapshots/ValidationsGeneratorTests.CanValidateTypeWithParsableProperties#ValidatableInfoResolver.g.verified.cs index 03f94852185..716e738ec5b 100644 --- a/src/aspnetcore/src/Http/Http.Extensions/test/ValidationsGenerator/snapshots/ValidationsGeneratorTests.CanValidateTypeWithParsableProperties#ValidatableInfoResolver.g.verified.cs +++ b/src/aspnetcore/src/Http/Http.Extensions/test/ValidationsGenerator/snapshots/ValidationsGeneratorTests.CanValidateTypeWithParsableProperties#ValidatableInfoResolver.g.verified.cs @@ -39,6 +39,7 @@ public GeneratedValidatablePropertyInfo( Name = name; } + [global::System.Diagnostics.CodeAnalysis.DynamicallyAccessedMembers(global::System.Diagnostics.CodeAnalysis.DynamicallyAccessedMemberTypes.PublicProperties)] internal global::System.Type ContainingType { get; } internal string Name { get; } @@ -163,10 +164,11 @@ file static class GeneratedServiceCollectionExtensions [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.AspNetCore.Http.ValidationsGenerator, Version=42.42.42.42, Culture=neutral, PublicKeyToken=adb9793829ddae60", "42.42.42.42")] file static class ValidationAttributeCache { - private sealed record CacheKey(global::System.Type ContainingType, string PropertyName); + private sealed record CacheKey([property: global::System.Diagnostics.CodeAnalysis.DynamicallyAccessedMembers(global::System.Diagnostics.CodeAnalysis.DynamicallyAccessedMemberTypes.PublicProperties)] global::System.Type ContainingType, string PropertyName); private static readonly global::System.Collections.Concurrent.ConcurrentDictionary _cache = new(); public static global::System.ComponentModel.DataAnnotations.ValidationAttribute[] GetValidationAttributes( + [global::System.Diagnostics.CodeAnalysis.DynamicallyAccessedMembers(global::System.Diagnostics.CodeAnalysis.DynamicallyAccessedMemberTypes.PublicProperties)] global::System.Type containingType, string propertyName) { diff --git a/src/aspnetcore/src/Http/Http.Extensions/test/ValidationsGenerator/snapshots/ValidationsGeneratorTests.CanValidateTypesWithAttribute#ValidatableInfoResolver.g.verified.cs b/src/aspnetcore/src/Http/Http.Extensions/test/ValidationsGenerator/snapshots/ValidationsGeneratorTests.CanValidateTypesWithAttribute#ValidatableInfoResolver.g.verified.cs index 75c87732a0d..34c77a5cb5f 100644 --- a/src/aspnetcore/src/Http/Http.Extensions/test/ValidationsGenerator/snapshots/ValidationsGeneratorTests.CanValidateTypesWithAttribute#ValidatableInfoResolver.g.verified.cs +++ b/src/aspnetcore/src/Http/Http.Extensions/test/ValidationsGenerator/snapshots/ValidationsGeneratorTests.CanValidateTypesWithAttribute#ValidatableInfoResolver.g.verified.cs @@ -39,6 +39,7 @@ public GeneratedValidatablePropertyInfo( Name = name; } + [global::System.Diagnostics.CodeAnalysis.DynamicallyAccessedMembers(global::System.Diagnostics.CodeAnalysis.DynamicallyAccessedMemberTypes.PublicProperties)] internal global::System.Type ContainingType { get; } internal string Name { get; } @@ -201,10 +202,11 @@ file static class GeneratedServiceCollectionExtensions [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.AspNetCore.Http.ValidationsGenerator, Version=42.42.42.42, Culture=neutral, PublicKeyToken=adb9793829ddae60", "42.42.42.42")] file static class ValidationAttributeCache { - private sealed record CacheKey(global::System.Type ContainingType, string PropertyName); + private sealed record CacheKey([property: global::System.Diagnostics.CodeAnalysis.DynamicallyAccessedMembers(global::System.Diagnostics.CodeAnalysis.DynamicallyAccessedMemberTypes.PublicProperties)] global::System.Type ContainingType, string PropertyName); private static readonly global::System.Collections.Concurrent.ConcurrentDictionary _cache = new(); public static global::System.ComponentModel.DataAnnotations.ValidationAttribute[] GetValidationAttributes( + [global::System.Diagnostics.CodeAnalysis.DynamicallyAccessedMembers(global::System.Diagnostics.CodeAnalysis.DynamicallyAccessedMemberTypes.PublicProperties)] global::System.Type containingType, string propertyName) { diff --git a/src/aspnetcore/src/Http/Http.Extensions/test/ValidationsGenerator/snapshots/ValidationsGeneratorTests.DoesNotEmitForExemptTypes#ValidatableInfoResolver.g.verified.cs b/src/aspnetcore/src/Http/Http.Extensions/test/ValidationsGenerator/snapshots/ValidationsGeneratorTests.DoesNotEmitForExemptTypes#ValidatableInfoResolver.g.verified.cs index c5a4eb4152b..fba31434401 100644 --- a/src/aspnetcore/src/Http/Http.Extensions/test/ValidationsGenerator/snapshots/ValidationsGeneratorTests.DoesNotEmitForExemptTypes#ValidatableInfoResolver.g.verified.cs +++ b/src/aspnetcore/src/Http/Http.Extensions/test/ValidationsGenerator/snapshots/ValidationsGeneratorTests.DoesNotEmitForExemptTypes#ValidatableInfoResolver.g.verified.cs @@ -39,6 +39,7 @@ public GeneratedValidatablePropertyInfo( Name = name; } + [global::System.Diagnostics.CodeAnalysis.DynamicallyAccessedMembers(global::System.Diagnostics.CodeAnalysis.DynamicallyAccessedMemberTypes.PublicProperties)] internal global::System.Type ContainingType { get; } internal string Name { get; } @@ -115,10 +116,11 @@ file static class GeneratedServiceCollectionExtensions [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.AspNetCore.Http.ValidationsGenerator, Version=42.42.42.42, Culture=neutral, PublicKeyToken=adb9793829ddae60", "42.42.42.42")] file static class ValidationAttributeCache { - private sealed record CacheKey(global::System.Type ContainingType, string PropertyName); + private sealed record CacheKey([property: global::System.Diagnostics.CodeAnalysis.DynamicallyAccessedMembers(global::System.Diagnostics.CodeAnalysis.DynamicallyAccessedMemberTypes.PublicProperties)] global::System.Type ContainingType, string PropertyName); private static readonly global::System.Collections.Concurrent.ConcurrentDictionary _cache = new(); public static global::System.ComponentModel.DataAnnotations.ValidationAttribute[] GetValidationAttributes( + [global::System.Diagnostics.CodeAnalysis.DynamicallyAccessedMembers(global::System.Diagnostics.CodeAnalysis.DynamicallyAccessedMemberTypes.PublicProperties)] global::System.Type containingType, string propertyName) { diff --git a/src/aspnetcore/src/Http/Routing/src/ValidationEndpointFilterFactory.cs b/src/aspnetcore/src/Http/Routing/src/ValidationEndpointFilterFactory.cs index bd9b841fd55..73a41f0f8d5 100644 --- a/src/aspnetcore/src/Http/Routing/src/ValidationEndpointFilterFactory.cs +++ b/src/aspnetcore/src/Http/Routing/src/ValidationEndpointFilterFactory.cs @@ -4,7 +4,9 @@ // The .NET Foundation licenses this file to you under the MIT license. using System.ComponentModel.DataAnnotations; +using System.Linq; using System.Reflection; +using Microsoft.AspNetCore.Http.Metadata; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Options; @@ -21,6 +23,8 @@ public static EndpointFilterDelegate Create(EndpointFilterFactoryContext context return next; } + var serviceProviderIsService = context.ApplicationServices.GetService(); + var parameterCount = parameters.Length; var validatableParameters = new IValidatableInfo[parameterCount]; var parameterDisplayNames = new string[parameterCount]; @@ -28,6 +32,12 @@ public static EndpointFilterDelegate Create(EndpointFilterFactoryContext context for (var i = 0; i < parameterCount; i++) { + // Ignore parameters that are resolved from the DI container. + if (IsServiceParameter(parameters[i], serviceProviderIsService)) + { + continue; + } + if (options.TryGetValidatableParameterInfo(parameters[i], out var validatableParameter)) { validatableParameters[i] = validatableParameter; @@ -43,7 +53,7 @@ public static EndpointFilterDelegate Create(EndpointFilterFactoryContext context return async (context) => { - var validatableContext = new ValidateContext { ValidationOptions = options }; + ValidateContext? validateContext = null; for (var i = 0; i < context.Arguments.Count; i++) { @@ -57,21 +67,41 @@ public static EndpointFilterDelegate Create(EndpointFilterFactoryContext context } var validationContext = new ValidationContext(argument, displayName, context.HttpContext.RequestServices, items: null); - validatableContext.ValidationContext = validationContext; - await validatableParameter.ValidateAsync(argument, validatableContext, context.HttpContext.RequestAborted); + + if (validateContext == null) + { + validateContext = new ValidateContext + { + ValidationOptions = options, + ValidationContext = validationContext + }; + } + else + { + validateContext.ValidationContext = validationContext; + } + + await validatableParameter.ValidateAsync(argument, validateContext, context.HttpContext.RequestAborted); } - if (validatableContext.ValidationErrors is { Count: > 0 }) + if (validateContext is { ValidationErrors.Count: > 0 }) { context.HttpContext.Response.StatusCode = StatusCodes.Status400BadRequest; context.HttpContext.Response.ContentType = "application/problem+json"; - return await ValueTask.FromResult(new HttpValidationProblemDetails(validatableContext.ValidationErrors)); + return await ValueTask.FromResult(new HttpValidationProblemDetails(validateContext.ValidationErrors)); } return await next(context); }; } + private static bool IsServiceParameter(ParameterInfo parameterInfo, IServiceProviderIsService? isService) + => HasFromServicesAttribute(parameterInfo) || + (isService?.IsService(parameterInfo.ParameterType) == true); + + private static bool HasFromServicesAttribute(ParameterInfo parameterInfo) + => parameterInfo.CustomAttributes.OfType().Any(); + private static string GetDisplayName(ParameterInfo parameterInfo) { var displayAttribute = parameterInfo.GetCustomAttribute(); diff --git a/src/aspnetcore/src/Identity/EntityFrameworkCore/test/EF.Test/UserStoreTest.cs b/src/aspnetcore/src/Identity/EntityFrameworkCore/test/EF.Test/UserStoreTest.cs index f55c2b48340..fe7eb5ee900 100644 --- a/src/aspnetcore/src/Identity/EntityFrameworkCore/test/EF.Test/UserStoreTest.cs +++ b/src/aspnetcore/src/Identity/EntityFrameworkCore/test/EF.Test/UserStoreTest.cs @@ -144,6 +144,9 @@ await Assert.ThrowsAsync("user", await Assert.ThrowsAsync("user", async () => await store.GetTwoFactorEnabledAsync(null)); await Assert.ThrowsAsync("user", async () => await store.SetTwoFactorEnabledAsync(null, true)); + await Assert.ThrowsAsync("user", async () => await store.RedeemCodeAsync(user: null, code: "fake", default)); + await Assert.ThrowsAsync("code", async () => await store.RedeemCodeAsync(new IdentityUser("fake"), code: null, default)); + await Assert.ThrowsAsync("code", async () => await store.RedeemCodeAsync(new IdentityUser("fake"), code: "", default)); await Assert.ThrowsAsync("user", async () => await store.GetAccessFailedCountAsync(null)); await Assert.ThrowsAsync("user", async () => await store.GetLockoutEnabledAsync(null)); await Assert.ThrowsAsync("user", async () => await store.SetLockoutEnabledAsync(null, false)); diff --git a/src/aspnetcore/src/Identity/Extensions.Stores/src/UserStoreBase.cs b/src/aspnetcore/src/Identity/Extensions.Stores/src/UserStoreBase.cs index c45dd197e4a..804ebcbad7d 100644 --- a/src/aspnetcore/src/Identity/Extensions.Stores/src/UserStoreBase.cs +++ b/src/aspnetcore/src/Identity/Extensions.Stores/src/UserStoreBase.cs @@ -969,7 +969,7 @@ public virtual async Task RedeemCodeAsync(TUser user, string code, Cancell ThrowIfDisposed(); ArgumentNullThrowHelper.ThrowIfNull(user); - ArgumentNullThrowHelper.ThrowIfNull(code); + ArgumentNullThrowHelper.ThrowIfNullOrEmpty(code); var mergedCodes = await GetTokenAsync(user, InternalLoginProvider, RecoveryCodeTokenName, cancellationToken).ConfigureAwait(false) ?? ""; var splitCodes = mergedCodes.Split(';'); diff --git a/src/aspnetcore/src/OpenApi/gen/XmlCommentGenerator.Emitter.cs b/src/aspnetcore/src/OpenApi/gen/XmlCommentGenerator.Emitter.cs index 6b6e7139e37..9dca2b99100 100644 --- a/src/aspnetcore/src/OpenApi/gen/XmlCommentGenerator.Emitter.cs +++ b/src/aspnetcore/src/OpenApi/gen/XmlCommentGenerator.Emitter.cs @@ -61,7 +61,6 @@ namespace Microsoft.AspNetCore.OpenApi.Generated using Microsoft.OpenApi.Models; using Microsoft.OpenApi.Models.Interfaces; using Microsoft.OpenApi.Models.References; - using Microsoft.OpenApi.Any; {{GeneratedCodeAttribute}} file record XmlComment( diff --git a/src/aspnetcore/src/OpenApi/perf/Microbenchmarks/TransformersBenchmark.cs b/src/aspnetcore/src/OpenApi/perf/Microbenchmarks/TransformersBenchmark.cs index b9c3267ca07..dc7a78d517d 100644 --- a/src/aspnetcore/src/OpenApi/perf/Microbenchmarks/TransformersBenchmark.cs +++ b/src/aspnetcore/src/OpenApi/perf/Microbenchmarks/TransformersBenchmark.cs @@ -5,7 +5,7 @@ using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Routing; using Microsoft.Extensions.DependencyInjection; -using Microsoft.OpenApi.Any; +using Microsoft.OpenApi.Extensions; using Microsoft.OpenApi.Models; namespace Microsoft.AspNetCore.OpenApi.Microbenchmarks; @@ -105,11 +105,11 @@ public void SchemaTransformer_Setup() schema.Extensions ??= []; if (context.JsonTypeInfo.Type == typeof(Todo) && context.ParameterDescription != null) { - schema.Extensions["x-my-extension"] = new OpenApiAny(context.ParameterDescription.Name); + schema.Extensions["x-my-extension"] = new JsonNodeExtension(context.ParameterDescription.Name); } else { - schema.Extensions["x-my-extension"] = new OpenApiAny("response"); + schema.Extensions["x-my-extension"] = new JsonNodeExtension("response"); } return Task.CompletedTask; }); @@ -179,11 +179,11 @@ public Task TransformAsync(OpenApiSchema schema, OpenApiSchemaTransformerContext schema.Extensions ??= []; if (context.JsonTypeInfo.Type == typeof(Todo) && context.ParameterDescription != null) { - schema.Extensions["x-my-extension"] = new OpenApiAny(context.ParameterDescription.Name); + schema.Extensions["x-my-extension"] = new JsonNodeExtension(context.ParameterDescription.Name); } else { - schema.Extensions["x-my-extension"] = new OpenApiAny("response"); + schema.Extensions["x-my-extension"] = new JsonNodeExtension("response"); } return Task.CompletedTask; } diff --git a/src/aspnetcore/src/OpenApi/test/Microsoft.AspNetCore.OpenApi.SourceGenerators.Tests/snapshots/AddOpenApiTests.CanInterceptAddOpenApi#OpenApiXmlCommentSupport.generated.verified.cs b/src/aspnetcore/src/OpenApi/test/Microsoft.AspNetCore.OpenApi.SourceGenerators.Tests/snapshots/AddOpenApiTests.CanInterceptAddOpenApi#OpenApiXmlCommentSupport.generated.verified.cs index 3d2702fbe1f..0d3d206fec8 100644 --- a/src/aspnetcore/src/OpenApi/test/Microsoft.AspNetCore.OpenApi.SourceGenerators.Tests/snapshots/AddOpenApiTests.CanInterceptAddOpenApi#OpenApiXmlCommentSupport.generated.verified.cs +++ b/src/aspnetcore/src/OpenApi/test/Microsoft.AspNetCore.OpenApi.SourceGenerators.Tests/snapshots/AddOpenApiTests.CanInterceptAddOpenApi#OpenApiXmlCommentSupport.generated.verified.cs @@ -43,7 +43,6 @@ namespace Microsoft.AspNetCore.OpenApi.Generated using Microsoft.OpenApi.Models; using Microsoft.OpenApi.Models.Interfaces; using Microsoft.OpenApi.Models.References; - using Microsoft.OpenApi.Any; [System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.AspNetCore.OpenApi.SourceGenerators, Version=42.42.42.42, Culture=neutral, PublicKeyToken=adb9793829ddae60", "42.42.42.42")] file record XmlComment( diff --git a/src/aspnetcore/src/OpenApi/test/Microsoft.AspNetCore.OpenApi.SourceGenerators.Tests/snapshots/AdditionalTextsTests.CanHandleXmlForSchemasInAdditionalTexts#OpenApiXmlCommentSupport.generated.verified.cs b/src/aspnetcore/src/OpenApi/test/Microsoft.AspNetCore.OpenApi.SourceGenerators.Tests/snapshots/AdditionalTextsTests.CanHandleXmlForSchemasInAdditionalTexts#OpenApiXmlCommentSupport.generated.verified.cs index 945ae11f52c..b876791c810 100644 --- a/src/aspnetcore/src/OpenApi/test/Microsoft.AspNetCore.OpenApi.SourceGenerators.Tests/snapshots/AdditionalTextsTests.CanHandleXmlForSchemasInAdditionalTexts#OpenApiXmlCommentSupport.generated.verified.cs +++ b/src/aspnetcore/src/OpenApi/test/Microsoft.AspNetCore.OpenApi.SourceGenerators.Tests/snapshots/AdditionalTextsTests.CanHandleXmlForSchemasInAdditionalTexts#OpenApiXmlCommentSupport.generated.verified.cs @@ -43,7 +43,6 @@ namespace Microsoft.AspNetCore.OpenApi.Generated using Microsoft.OpenApi.Models; using Microsoft.OpenApi.Models.Interfaces; using Microsoft.OpenApi.Models.References; - using Microsoft.OpenApi.Any; [System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.AspNetCore.OpenApi.SourceGenerators, Version=42.42.42.42, Culture=neutral, PublicKeyToken=adb9793829ddae60", "42.42.42.42")] file record XmlComment( diff --git a/src/aspnetcore/src/OpenApi/test/Microsoft.AspNetCore.OpenApi.SourceGenerators.Tests/snapshots/CompletenessTests.SupportsAllXmlTagsOnSchemas#OpenApiXmlCommentSupport.generated.verified.cs b/src/aspnetcore/src/OpenApi/test/Microsoft.AspNetCore.OpenApi.SourceGenerators.Tests/snapshots/CompletenessTests.SupportsAllXmlTagsOnSchemas#OpenApiXmlCommentSupport.generated.verified.cs index 391c9872505..a9b36cb7dae 100644 --- a/src/aspnetcore/src/OpenApi/test/Microsoft.AspNetCore.OpenApi.SourceGenerators.Tests/snapshots/CompletenessTests.SupportsAllXmlTagsOnSchemas#OpenApiXmlCommentSupport.generated.verified.cs +++ b/src/aspnetcore/src/OpenApi/test/Microsoft.AspNetCore.OpenApi.SourceGenerators.Tests/snapshots/CompletenessTests.SupportsAllXmlTagsOnSchemas#OpenApiXmlCommentSupport.generated.verified.cs @@ -43,7 +43,6 @@ namespace Microsoft.AspNetCore.OpenApi.Generated using Microsoft.OpenApi.Models; using Microsoft.OpenApi.Models.Interfaces; using Microsoft.OpenApi.Models.References; - using Microsoft.OpenApi.Any; [System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.AspNetCore.OpenApi.SourceGenerators, Version=42.42.42.42, Culture=neutral, PublicKeyToken=adb9793829ddae60", "42.42.42.42")] file record XmlComment( diff --git a/src/aspnetcore/src/OpenApi/test/Microsoft.AspNetCore.OpenApi.SourceGenerators.Tests/snapshots/OperationTests.SupportsXmlCommentsOnOperationsFromControllers#OpenApiXmlCommentSupport.generated.verified.cs b/src/aspnetcore/src/OpenApi/test/Microsoft.AspNetCore.OpenApi.SourceGenerators.Tests/snapshots/OperationTests.SupportsXmlCommentsOnOperationsFromControllers#OpenApiXmlCommentSupport.generated.verified.cs index 2b2e1e1d01f..7905cbba951 100644 --- a/src/aspnetcore/src/OpenApi/test/Microsoft.AspNetCore.OpenApi.SourceGenerators.Tests/snapshots/OperationTests.SupportsXmlCommentsOnOperationsFromControllers#OpenApiXmlCommentSupport.generated.verified.cs +++ b/src/aspnetcore/src/OpenApi/test/Microsoft.AspNetCore.OpenApi.SourceGenerators.Tests/snapshots/OperationTests.SupportsXmlCommentsOnOperationsFromControllers#OpenApiXmlCommentSupport.generated.verified.cs @@ -43,7 +43,6 @@ namespace Microsoft.AspNetCore.OpenApi.Generated using Microsoft.OpenApi.Models; using Microsoft.OpenApi.Models.Interfaces; using Microsoft.OpenApi.Models.References; - using Microsoft.OpenApi.Any; [System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.AspNetCore.OpenApi.SourceGenerators, Version=42.42.42.42, Culture=neutral, PublicKeyToken=adb9793829ddae60", "42.42.42.42")] file record XmlComment( diff --git a/src/aspnetcore/src/OpenApi/test/Microsoft.AspNetCore.OpenApi.SourceGenerators.Tests/snapshots/OperationTests.SupportsXmlCommentsOnOperationsFromMinimalApis#OpenApiXmlCommentSupport.generated.verified.cs b/src/aspnetcore/src/OpenApi/test/Microsoft.AspNetCore.OpenApi.SourceGenerators.Tests/snapshots/OperationTests.SupportsXmlCommentsOnOperationsFromMinimalApis#OpenApiXmlCommentSupport.generated.verified.cs index 3ee9ad39a98..301db6afae0 100644 --- a/src/aspnetcore/src/OpenApi/test/Microsoft.AspNetCore.OpenApi.SourceGenerators.Tests/snapshots/OperationTests.SupportsXmlCommentsOnOperationsFromMinimalApis#OpenApiXmlCommentSupport.generated.verified.cs +++ b/src/aspnetcore/src/OpenApi/test/Microsoft.AspNetCore.OpenApi.SourceGenerators.Tests/snapshots/OperationTests.SupportsXmlCommentsOnOperationsFromMinimalApis#OpenApiXmlCommentSupport.generated.verified.cs @@ -43,7 +43,6 @@ namespace Microsoft.AspNetCore.OpenApi.Generated using Microsoft.OpenApi.Models; using Microsoft.OpenApi.Models.Interfaces; using Microsoft.OpenApi.Models.References; - using Microsoft.OpenApi.Any; [System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.AspNetCore.OpenApi.SourceGenerators, Version=42.42.42.42, Culture=neutral, PublicKeyToken=adb9793829ddae60", "42.42.42.42")] file record XmlComment( diff --git a/src/aspnetcore/src/OpenApi/test/Microsoft.AspNetCore.OpenApi.SourceGenerators.Tests/snapshots/SchemaTests.SupportsXmlCommentsOnSchemas#OpenApiXmlCommentSupport.generated.verified.cs b/src/aspnetcore/src/OpenApi/test/Microsoft.AspNetCore.OpenApi.SourceGenerators.Tests/snapshots/SchemaTests.SupportsXmlCommentsOnSchemas#OpenApiXmlCommentSupport.generated.verified.cs index ae28560f635..8f57fda92e1 100644 --- a/src/aspnetcore/src/OpenApi/test/Microsoft.AspNetCore.OpenApi.SourceGenerators.Tests/snapshots/SchemaTests.SupportsXmlCommentsOnSchemas#OpenApiXmlCommentSupport.generated.verified.cs +++ b/src/aspnetcore/src/OpenApi/test/Microsoft.AspNetCore.OpenApi.SourceGenerators.Tests/snapshots/SchemaTests.SupportsXmlCommentsOnSchemas#OpenApiXmlCommentSupport.generated.verified.cs @@ -43,7 +43,6 @@ namespace Microsoft.AspNetCore.OpenApi.Generated using Microsoft.OpenApi.Models; using Microsoft.OpenApi.Models.Interfaces; using Microsoft.OpenApi.Models.References; - using Microsoft.OpenApi.Any; [System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.AspNetCore.OpenApi.SourceGenerators, Version=42.42.42.42, Culture=neutral, PublicKeyToken=adb9793829ddae60", "42.42.42.42")] file record XmlComment( diff --git a/src/aspnetcore/src/OpenApi/test/Microsoft.AspNetCore.OpenApi.Tests/Services/OpenApiSchemaService/OpenApiSchemaService.PolymorphicSchemas.cs b/src/aspnetcore/src/OpenApi/test/Microsoft.AspNetCore.OpenApi.Tests/Services/OpenApiSchemaService/OpenApiSchemaService.PolymorphicSchemas.cs index a222c5e3083..ab21291453a 100644 --- a/src/aspnetcore/src/OpenApi/test/Microsoft.AspNetCore.OpenApi.Tests/Services/OpenApiSchemaService/OpenApiSchemaService.PolymorphicSchemas.cs +++ b/src/aspnetcore/src/OpenApi/test/Microsoft.AspNetCore.OpenApi.Tests/Services/OpenApiSchemaService/OpenApiSchemaService.PolymorphicSchemas.cs @@ -3,7 +3,7 @@ using System.Net.Http; using Microsoft.AspNetCore.Builder; -using Microsoft.OpenApi.Any; +using Microsoft.OpenApi.Extensions; using Microsoft.OpenApi.Models; using Microsoft.OpenApi.Models.References; diff --git a/src/aspnetcore/src/OpenApi/test/Microsoft.AspNetCore.OpenApi.Tests/Services/OpenApiSchemaService/OpenApiSchemaService.RequestBodySchemas.cs b/src/aspnetcore/src/OpenApi/test/Microsoft.AspNetCore.OpenApi.Tests/Services/OpenApiSchemaService/OpenApiSchemaService.RequestBodySchemas.cs index 9d2576b8cbf..5eb02fb1274 100644 --- a/src/aspnetcore/src/OpenApi/test/Microsoft.AspNetCore.OpenApi.Tests/Services/OpenApiSchemaService/OpenApiSchemaService.RequestBodySchemas.cs +++ b/src/aspnetcore/src/OpenApi/test/Microsoft.AspNetCore.OpenApi.Tests/Services/OpenApiSchemaService/OpenApiSchemaService.RequestBodySchemas.cs @@ -10,7 +10,7 @@ using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.DependencyInjection; -using Microsoft.OpenApi.Any; +using Microsoft.OpenApi.Extensions; using Microsoft.OpenApi.Models; using Microsoft.OpenApi.Models.References; diff --git a/src/aspnetcore/src/OpenApi/test/Microsoft.AspNetCore.OpenApi.Tests/Services/OpenApiSchemaService/OpenApiSchemaService.ResponseSchemas.cs b/src/aspnetcore/src/OpenApi/test/Microsoft.AspNetCore.OpenApi.Tests/Services/OpenApiSchemaService/OpenApiSchemaService.ResponseSchemas.cs index a59bfb28d1d..ac92e52bce0 100644 --- a/src/aspnetcore/src/OpenApi/test/Microsoft.AspNetCore.OpenApi.Tests/Services/OpenApiSchemaService/OpenApiSchemaService.ResponseSchemas.cs +++ b/src/aspnetcore/src/OpenApi/test/Microsoft.AspNetCore.OpenApi.Tests/Services/OpenApiSchemaService/OpenApiSchemaService.ResponseSchemas.cs @@ -7,7 +7,7 @@ using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; -using Microsoft.OpenApi.Any; +using Microsoft.OpenApi.Extensions; using Microsoft.OpenApi.Models; public partial class OpenApiSchemaServiceTests : OpenApiDocumentServiceTestBase diff --git a/src/aspnetcore/src/OpenApi/test/Microsoft.AspNetCore.OpenApi.Tests/Transformers/CustomSchemaTransformerTests.cs b/src/aspnetcore/src/OpenApi/test/Microsoft.AspNetCore.OpenApi.Tests/Transformers/CustomSchemaTransformerTests.cs index 9a98cd71ec0..aff3182bd2e 100644 --- a/src/aspnetcore/src/OpenApi/test/Microsoft.AspNetCore.OpenApi.Tests/Transformers/CustomSchemaTransformerTests.cs +++ b/src/aspnetcore/src/OpenApi/test/Microsoft.AspNetCore.OpenApi.Tests/Transformers/CustomSchemaTransformerTests.cs @@ -9,7 +9,7 @@ using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.OpenApi; using Microsoft.Extensions.DependencyInjection; -using Microsoft.OpenApi.Any; +using Microsoft.OpenApi.Extensions; using Microsoft.OpenApi.Models; using Microsoft.OpenApi.Models.References; @@ -159,7 +159,7 @@ public async Task GetOrCreateSchema_CanBeUsedInSchemaTransformer() // Add a reference to the example in the shape schema schema.Extensions ??= []; - schema.Extensions["x-example-component"] = new OpenApiAny("#/components/schemas/TriangleExample"); + schema.Extensions["x-example-component"] = new JsonNodeExtension("#/components/schemas/TriangleExample"); schema.Description = "A shape with an example reference"; } }); diff --git a/src/aspnetcore/src/OpenApi/test/Microsoft.AspNetCore.OpenApi.Tests/Transformers/Implementations/OpenApiSchemaReferenceTransformerTests.cs b/src/aspnetcore/src/OpenApi/test/Microsoft.AspNetCore.OpenApi.Tests/Transformers/Implementations/OpenApiSchemaReferenceTransformerTests.cs index 2fa5cce2989..603007c0a08 100644 --- a/src/aspnetcore/src/OpenApi/test/Microsoft.AspNetCore.OpenApi.Tests/Transformers/Implementations/OpenApiSchemaReferenceTransformerTests.cs +++ b/src/aspnetcore/src/OpenApi/test/Microsoft.AspNetCore.OpenApi.Tests/Transformers/Implementations/OpenApiSchemaReferenceTransformerTests.cs @@ -8,7 +8,7 @@ using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.OpenApi; using Microsoft.Extensions.DependencyInjection; -using Microsoft.OpenApi.Any; +using Microsoft.OpenApi.Extensions; using Microsoft.OpenApi.Models; using Microsoft.OpenApi.Models.References; using Microsoft.OpenApi.Writers; @@ -287,7 +287,7 @@ public async Task TypeModifiedWithSchemaTransformerMapsToDifferentReferenceId() if (context.JsonTypeInfo.Type == typeof(Todo) && context.ParameterDescription is not null) { schema.Extensions ??= []; - schema.Extensions["x-my-extension"] = new OpenApiAny(context.ParameterDescription.Name); + schema.Extensions["x-my-extension"] = new JsonNodeExtension(context.ParameterDescription.Name); } return Task.CompletedTask; }); @@ -301,7 +301,7 @@ await VerifyOpenApiDocument(builder, options, document => var responseSchema = getOperation.Responses["200"].Content["application/json"].Schema; // Schemas are distinct because of applied transformer so no reference is used. Assert.NotEqual(((OpenApiSchemaReference)requestSchema).Reference.Id, ((OpenApiSchemaReference)responseSchema).Reference.Id); - Assert.Equal("todo", ((OpenApiAny)requestSchema.Extensions["x-my-extension"]).Node.GetValue()); + Assert.Equal("todo", ((JsonNodeExtension)requestSchema.Extensions["x-my-extension"]).Node.GetValue()); Assert.False(responseSchema.Extensions.TryGetValue("x-my-extension", out var _)); }); } diff --git a/src/aspnetcore/src/OpenApi/test/Microsoft.AspNetCore.OpenApi.Tests/Transformers/SchemaTransformerTests.cs b/src/aspnetcore/src/OpenApi/test/Microsoft.AspNetCore.OpenApi.Tests/Transformers/SchemaTransformerTests.cs index 6cc281bf6b9..bed6a02e50f 100644 --- a/src/aspnetcore/src/OpenApi/test/Microsoft.AspNetCore.OpenApi.Tests/Transformers/SchemaTransformerTests.cs +++ b/src/aspnetcore/src/OpenApi/test/Microsoft.AspNetCore.OpenApi.Tests/Transformers/SchemaTransformerTests.cs @@ -8,7 +8,7 @@ using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.OpenApi; using Microsoft.Extensions.DependencyInjection; -using Microsoft.OpenApi.Any; +using Microsoft.OpenApi.Extensions; using Microsoft.OpenApi.Models; using Microsoft.OpenApi.Models.References; @@ -156,15 +156,15 @@ public async Task SchemaTransformer_RunsInRegisteredOrder() options.AddSchemaTransformer((schema, context, cancellationToken) => { schema.Extensions ??= []; - schema.Extensions["x-my-extension"] = new OpenApiAny("1"); + schema.Extensions["x-my-extension"] = new JsonNodeExtension("1"); schema.Format = "1"; return Task.CompletedTask; }); options.AddSchemaTransformer((schema, context, cancellationToken) => { schema.Extensions ??= []; - Assert.Equal("1", ((OpenApiAny)schema.Extensions["x-my-extension"]).Node.GetValue()); - schema.Extensions["x-my-extension"] = new OpenApiAny("2"); + Assert.Equal("1", ((JsonNodeExtension)schema.Extensions["x-my-extension"]).Node.GetValue()); + schema.Extensions["x-my-extension"] = new JsonNodeExtension("2"); return Task.CompletedTask; }); @@ -172,7 +172,7 @@ await VerifyOpenApiDocument(builder, options, document => { var operation = Assert.Single(document.Paths.Values).Operations.Values.Single(); var schema = operation.RequestBody.Content["application/json"].Schema; - Assert.Equal("2", ((OpenApiAny)schema.Extensions["x-my-extension"]).Node.GetValue()); + Assert.Equal("2", ((JsonNodeExtension)schema.Extensions["x-my-extension"]).Node.GetValue()); }); } @@ -190,7 +190,7 @@ public async Task SchemaTransformer_OnTypeModifiesBothRequestAndResponse() if (context.JsonTypeInfo.Type == typeof(Todo)) { schema.Extensions ??= []; - schema.Extensions["x-my-extension"] = new OpenApiAny("1"); + schema.Extensions["x-my-extension"] = new JsonNodeExtension("1"); } return Task.CompletedTask; }); @@ -200,10 +200,10 @@ await VerifyOpenApiDocument(builder, options, document => var path = Assert.Single(document.Paths.Values); var postOperation = path.Operations[HttpMethod.Post]; var requestSchema = postOperation.RequestBody.Content["application/json"].Schema; - Assert.Equal("1", ((OpenApiAny)requestSchema.Extensions["x-my-extension"]).Node.GetValue()); + Assert.Equal("1", ((JsonNodeExtension)requestSchema.Extensions["x-my-extension"]).Node.GetValue()); var getOperation = path.Operations[HttpMethod.Get]; var responseSchema = getOperation.Responses["200"].Content["application/json"].Schema; - Assert.Equal("1", ((OpenApiAny)responseSchema.Extensions["x-my-extension"]).Node.GetValue()); + Assert.Equal("1", ((JsonNodeExtension)responseSchema.Extensions["x-my-extension"]).Node.GetValue()); }); } @@ -220,7 +220,7 @@ public async Task SchemaTransformer_WithDescriptionOnlyModifiesParameter() { if (context.JsonTypeInfo.Type == typeof(Todo) && context.ParameterDescription is not null) { - schema.Extensions["x-my-extension"] = new OpenApiAny(context.ParameterDescription.Name); + schema.Extensions["x-my-extension"] = new JsonNodeExtension(context.ParameterDescription.Name); } return Task.CompletedTask; }); @@ -230,7 +230,7 @@ await VerifyOpenApiDocument(builder, options, document => var path = Assert.Single(document.Paths.Values); var postOperation = path.Operations[HttpMethod.Post]; var requestSchema = postOperation.RequestBody.Content["application/json"].Schema; - Assert.Equal("todo", ((OpenApiAny)requestSchema.Extensions["x-my-extension"]).Node.GetValue()); + Assert.Equal("todo", ((JsonNodeExtension)requestSchema.Extensions["x-my-extension"]).Node.GetValue()); var getOperation = path.Operations[HttpMethod.Get]; var responseSchema = getOperation.Responses["200"].Content["application/json"].Schema; Assert.False(responseSchema.Extensions.TryGetValue("x-my-extension", out var _)); @@ -253,10 +253,10 @@ await VerifyOpenApiDocument(builder, options, document => var path = Assert.Single(document.Paths.Values); var postOperation = path.Operations[HttpMethod.Post]; var requestSchema = postOperation.RequestBody.Content["application/json"].Schema; - Assert.Equal("1", ((OpenApiAny)requestSchema.Extensions["x-my-extension"]).Node.GetValue()); + Assert.Equal("1", ((JsonNodeExtension)requestSchema.Extensions["x-my-extension"]).Node.GetValue()); var getOperation = path.Operations[HttpMethod.Get]; var responseSchema = getOperation.Responses["200"].Content["application/json"].Schema; - Assert.Equal("1", ((OpenApiAny)responseSchema.Extensions["x-my-extension"]).Node.GetValue()); + Assert.Equal("1", ((JsonNodeExtension)responseSchema.Extensions["x-my-extension"]).Node.GetValue()); }); } @@ -276,10 +276,10 @@ await VerifyOpenApiDocument(builder, options, document => var path = Assert.Single(document.Paths.Values); var postOperation = path.Operations[HttpMethod.Post]; var requestSchema = postOperation.RequestBody.Content["application/json"].Schema; - Assert.Equal("1", ((OpenApiAny)requestSchema.Extensions["x-my-extension"]).Node.GetValue()); + Assert.Equal("1", ((JsonNodeExtension)requestSchema.Extensions["x-my-extension"]).Node.GetValue()); var getOperation = path.Operations[HttpMethod.Get]; var responseSchema = getOperation.Responses["200"].Content["application/json"].Schema; - Assert.Equal("1", ((OpenApiAny)responseSchema.Extensions["x-my-extension"]).Node.GetValue()); + Assert.Equal("1", ((JsonNodeExtension)responseSchema.Extensions["x-my-extension"]).Node.GetValue()); }); } @@ -303,21 +303,21 @@ await VerifyOpenApiDocument(builder, options, document => var path = Assert.Single(document.Paths.Values); var postOperation = path.Operations[HttpMethod.Post]; var requestSchema = postOperation.RequestBody.Content["application/json"].Schema; - value = ((OpenApiAny)requestSchema.Extensions["x-my-extension"]).Node.GetValue(); + value = ((JsonNodeExtension)requestSchema.Extensions["x-my-extension"]).Node.GetValue(); Assert.Equal(Dependency.InstantiationCount.ToString(CultureInfo.InvariantCulture), value); var getOperation = path.Operations[HttpMethod.Get]; var responseSchema = getOperation.Responses["200"].Content["application/json"].Schema; - Assert.Equal(value, ((OpenApiAny)responseSchema.Extensions["x-my-extension"]).Node.GetValue()); + Assert.Equal(value, ((JsonNodeExtension)responseSchema.Extensions["x-my-extension"]).Node.GetValue()); }); await VerifyOpenApiDocument(builder, options, document => { var path = Assert.Single(document.Paths.Values); var postOperation = path.Operations[HttpMethod.Post]; var requestSchema = postOperation.RequestBody.Content["application/json"].Schema; - Assert.Equal(value, ((OpenApiAny)requestSchema.Extensions["x-my-extension"]).Node.GetValue()); + Assert.Equal(value, ((JsonNodeExtension)requestSchema.Extensions["x-my-extension"]).Node.GetValue()); var getOperation = path.Operations[HttpMethod.Get]; var responseSchema = getOperation.Responses["200"].Content["application/json"].Schema; - Assert.Equal(value, ((OpenApiAny)responseSchema.Extensions["x-my-extension"]).Node.GetValue()); + Assert.Equal(value, ((JsonNodeExtension)responseSchema.Extensions["x-my-extension"]).Node.GetValue()); }); } @@ -500,7 +500,7 @@ public async Task SchemaTransformer_CanModifyPolymorphicChildSchemas() if (context.JsonTypeInfo.Type == typeof(Triangle)) { schema.Extensions ??= []; - schema.Extensions["x-my-extension"] = new OpenApiAny("this-is-a-triangle"); + schema.Extensions["x-my-extension"] = new JsonNodeExtension("this-is-a-triangle"); } return Task.CompletedTask; }); @@ -518,7 +518,7 @@ await VerifyOpenApiDocument(builder, options, document => path = document.Paths["/triangle"]; postOperation = path.Operations[HttpMethod.Post]; requestSchema = postOperation.RequestBody.Content["application/json"].Schema; - Assert.Equal("this-is-a-triangle", ((OpenApiAny)requestSchema.Extensions["x-my-extension"]).Node.GetValue()); + Assert.Equal("this-is-a-triangle", ((JsonNodeExtension)requestSchema.Extensions["x-my-extension"]).Node.GetValue()); }); } @@ -571,11 +571,11 @@ public async Task SchemaTransformer_CanModifyListOfPolymorphicTypes() schema.Extensions ??= []; if (context.JsonTypeInfo.Type == typeof(Triangle)) { - schema.Extensions["x-my-extension"] = new OpenApiAny("this-is-a-triangle"); + schema.Extensions["x-my-extension"] = new JsonNodeExtension("this-is-a-triangle"); } if (context.JsonTypeInfo.Type == typeof(Square)) { - schema.Extensions["x-my-extension"] = new OpenApiAny("this-is-a-square"); + schema.Extensions["x-my-extension"] = new JsonNodeExtension("this-is-a-square"); } return Task.CompletedTask; }); @@ -590,13 +590,13 @@ await VerifyOpenApiDocument(builder, options, document => var triangleSubschema = Assert.Single(itemSchema.AnyOf.Where(s => ((OpenApiSchemaReference)s).Reference.Id == "ShapeTriangle")); // Assert that the x-my-extension type is set to this-is-a-triangle Assert.True(triangleSubschema.Extensions.TryGetValue("x-my-extension", out var triangleExtension)); - Assert.Equal("this-is-a-triangle", ((OpenApiAny)triangleExtension).Node.GetValue()); + Assert.Equal("this-is-a-triangle", ((JsonNodeExtension)triangleExtension).Node.GetValue()); // Assert that the `Square` type within the polymorphic type list has been updated var squareSubschema = Assert.Single(itemSchema.AnyOf.Where(s => ((OpenApiSchemaReference)s).Reference.Id == "ShapeSquare")); // Assert that the x-my-extension type is set to this-is-a-square Assert.True(squareSubschema.Extensions.TryGetValue("x-my-extension", out var squareExtension)); - Assert.Equal("this-is-a-square", ((OpenApiAny)squareExtension).Node.GetValue()); + Assert.Equal("this-is-a-square", ((JsonNodeExtension)squareExtension).Node.GetValue()); }); } @@ -613,11 +613,11 @@ public async Task SchemaTransformer_CanModifyPolymorphicTypesInProperties() schema.Extensions ??= []; if (context.JsonTypeInfo.Type == typeof(Triangle)) { - schema.Extensions["x-my-extension"] = new OpenApiAny("this-is-a-triangle"); + schema.Extensions["x-my-extension"] = new JsonNodeExtension("this-is-a-triangle"); } if (context.JsonTypeInfo.Type == typeof(Square)) { - schema.Extensions["x-my-extension"] = new OpenApiAny("this-is-a-square"); + schema.Extensions["x-my-extension"] = new JsonNodeExtension("this-is-a-square"); } return Task.CompletedTask; }); @@ -632,13 +632,13 @@ await VerifyOpenApiDocument(builder, options, document => var triangleSubschema = Assert.Single(someShapeSchema.AnyOf.Where(s => ((OpenApiSchemaReference)s).Reference.Id == "ShapeTriangle")); // Assert that the x-my-extension type is set to this-is-a-triangle Assert.True(triangleSubschema.Extensions.TryGetValue("x-my-extension", out var triangleExtension)); - Assert.Equal("this-is-a-triangle", ((OpenApiAny)triangleExtension).Node.GetValue()); + Assert.Equal("this-is-a-triangle", ((JsonNodeExtension)triangleExtension).Node.GetValue()); // Assert that the `Square` type within the polymorphic type list has been updated var squareSubschema = Assert.Single(someShapeSchema.AnyOf.Where(s => ((OpenApiSchemaReference)s).Reference.Id == "ShapeSquare")); // Assert that the x-my-extension type is set to this-is-a-square Assert.True(squareSubschema.Extensions.TryGetValue("x-my-extension", out var squareExtension)); - Assert.Equal("this-is-a-square", ((OpenApiAny)squareExtension).Node.GetValue()); + Assert.Equal("this-is-a-square", ((JsonNodeExtension)squareExtension).Node.GetValue()); }); } @@ -655,11 +655,11 @@ public async Task SchemaTransformer_CanModifyDeeplyNestedPolymorphicTypesInPrope schema.Extensions ??= []; if (context.JsonTypeInfo.Type == typeof(Triangle)) { - schema.Extensions["x-my-extension"] = new OpenApiAny("this-is-a-triangle"); + schema.Extensions["x-my-extension"] = new JsonNodeExtension("this-is-a-triangle"); } if (context.JsonTypeInfo.Type == typeof(Square)) { - schema.Extensions["x-my-extension"] = new OpenApiAny("this-is-a-square"); + schema.Extensions["x-my-extension"] = new JsonNodeExtension("this-is-a-square"); } return Task.CompletedTask; }); @@ -674,13 +674,13 @@ await VerifyOpenApiDocument(builder, options, document => var triangleSubschema = Assert.Single(someShapeSchema.AnyOf.Where(s => ((OpenApiSchemaReference)s).Reference.Id == "ShapeTriangle")); // Assert that the x-my-extension type is set to this-is-a-triangle Assert.True(triangleSubschema.Extensions.TryGetValue("x-my-extension", out var triangleExtension)); - Assert.Equal("this-is-a-triangle", ((OpenApiAny)triangleExtension).Node.GetValue()); + Assert.Equal("this-is-a-triangle", ((JsonNodeExtension)triangleExtension).Node.GetValue()); // Assert that the `Square` type within the polymorphic type list has been updated var squareSubschema = Assert.Single(someShapeSchema.AnyOf.Where(s => ((OpenApiSchemaReference)s).Reference.Id == "ShapeSquare")); // Assert that the x-my-extension type is set to this-is-a-square Assert.True(squareSubschema.Extensions.TryGetValue("x-my-extension", out var squareExtension)); - Assert.Equal("this-is-a-square", ((OpenApiAny)squareExtension).Node.GetValue()); + Assert.Equal("this-is-a-square", ((JsonNodeExtension)squareExtension).Node.GetValue()); }); } @@ -742,7 +742,7 @@ public async Task SchemaTransformers_CanImplementNotSchemaIndependently() UseNotSchemaTransformer(options, (schema, context, cancellationToken) => { schema.Extensions ??= []; - schema.Extensions["modified-by-not-schema-transformer"] = new OpenApiAny(true); + schema.Extensions["modified-by-not-schema-transformer"] = new JsonNodeExtension(true); return Task.CompletedTask; }); @@ -752,13 +752,13 @@ await VerifyOpenApiDocument(builder, options, document => var path = document.Paths["/todo"]; var getOperation = path.Operations[HttpMethod.Get]; var responseSchema = getOperation.Responses["200"].Content["application/json"].Schema; - Assert.True(((OpenApiAny)responseSchema.Not.Extensions["modified-by-not-schema-transformer"]).Node.GetValue()); + Assert.True(((JsonNodeExtension)responseSchema.Not.Extensions["modified-by-not-schema-transformer"]).Node.GetValue()); var shapePath = document.Paths["/shape"]; var shapeOperation = shapePath.Operations[HttpMethod.Post]; var shapeRequestSchema = shapeOperation.RequestBody.Content["application/json"].Schema; var triangleSchema = Assert.Single(shapeRequestSchema.AnyOf.Where(s => ((OpenApiSchemaReference)s).Reference.Id == "ShapeTriangle")); - Assert.True(((OpenApiAny)triangleSchema.Not.Extensions["modified-by-not-schema-transformer"]).Node.GetValue()); + Assert.True(((JsonNodeExtension)triangleSchema.Not.Extensions["modified-by-not-schema-transformer"]).Node.GetValue()); }); static void UseNotSchemaTransformer(OpenApiOptions options, Func func) @@ -958,7 +958,7 @@ public Task TransformAsync(OpenApiSchema schema, OpenApiSchemaTransformerContext if (context.JsonTypeInfo.Type == typeof(Todo)) { schema.Extensions ??= []; - schema.Extensions["x-my-extension"] = new OpenApiAny("1"); + schema.Extensions["x-my-extension"] = new JsonNodeExtension("1"); } return Task.CompletedTask; } @@ -1007,7 +1007,7 @@ public Task TransformAsync(OpenApiSchema schema, OpenApiSchemaTransformerContext { dependency.TestMethod(); schema.Extensions ??= []; - schema.Extensions["x-my-extension"] = new OpenApiAny(Dependency.InstantiationCount.ToString(CultureInfo.InvariantCulture)); + schema.Extensions["x-my-extension"] = new JsonNodeExtension(Dependency.InstantiationCount.ToString(CultureInfo.InvariantCulture)); return Task.CompletedTask; } } diff --git a/src/aspnetcore/src/OpenApi/test/Microsoft.AspNetCore.OpenApi.Tests/Transformers/TypeBasedTransformerLifetimeTests.cs b/src/aspnetcore/src/OpenApi/test/Microsoft.AspNetCore.OpenApi.Tests/Transformers/TypeBasedTransformerLifetimeTests.cs index 0a4c6708797..8f343a95d51 100644 --- a/src/aspnetcore/src/OpenApi/test/Microsoft.AspNetCore.OpenApi.Tests/Transformers/TypeBasedTransformerLifetimeTests.cs +++ b/src/aspnetcore/src/OpenApi/test/Microsoft.AspNetCore.OpenApi.Tests/Transformers/TypeBasedTransformerLifetimeTests.cs @@ -4,7 +4,7 @@ using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.OpenApi; using Microsoft.Extensions.DependencyInjection; -using Microsoft.OpenApi.Any; +using Microsoft.OpenApi.Extensions; using Microsoft.OpenApi.Models; public class TypeBasedTransformerLifetimeTests : OpenApiDocumentServiceTestBase @@ -349,7 +349,7 @@ public Task TransformAsync(OpenApiSchema schema, OpenApiSchemaTransformerContext if (context.JsonTypeInfo.Type == typeof(Todo)) { schema.Extensions ??= []; - schema.Extensions["x-my-extension"] = new OpenApiAny("1"); + schema.Extensions["x-my-extension"] = new JsonNodeExtension("1"); } return Task.CompletedTask; } diff --git a/src/aspnetcore/src/Shared/ThrowHelpers/ArgumentNullThrowHelper.cs b/src/aspnetcore/src/Shared/ThrowHelpers/ArgumentNullThrowHelper.cs index 630651cecc0..1c44975d5a3 100644 --- a/src/aspnetcore/src/Shared/ThrowHelpers/ArgumentNullThrowHelper.cs +++ b/src/aspnetcore/src/Shared/ThrowHelpers/ArgumentNullThrowHelper.cs @@ -30,6 +30,29 @@ public static void ThrowIfNull( #endif } + /// Throws an if is null or empty. + /// The argument to validate as non-null and non-empty. + /// The name of the parameter with which corresponds. + public static void ThrowIfNullOrEmpty( +#if INTERNAL_NULLABLE_ATTRIBUTES || NETSTANDARD2_1_OR_GREATER || NET5_0_OR_GREATER + [NotNull] +#endif + string? argument, [CallerArgumentExpression(nameof(argument))] string? paramName = null) + { +#if !NET7_0_OR_GREATER || NETSTANDARD || NETFRAMEWORK + if (argument is null) + { + Throw(paramName); + } + else if (argument.Length == 0) + { + throw new ArgumentException("Must not be null or empty", paramName); + } +#else + ArgumentException.ThrowIfNullOrEmpty(argument, paramName); +#endif + } + #if !NET7_0_OR_GREATER || NETSTANDARD || NETFRAMEWORK #if INTERNAL_NULLABLE_ATTRIBUTES || NETSTANDARD2_1_OR_GREATER || NET5_0_OR_GREATER [DoesNotReturn] diff --git a/src/source-manifest.json b/src/source-manifest.json index 852588cfe24..4818fd60105 100644 --- a/src/source-manifest.json +++ b/src/source-manifest.json @@ -15,11 +15,11 @@ "commitSha": "5fa9337a84a52e9bd185d04d156eccbdcf592f74" }, { - "packageVersion": "10.0.0-preview.5.25263.4", - "barId": 267999, + "packageVersion": "10.0.0-preview.5.25264.4", + "barId": 268304, "path": "aspnetcore", "remoteUri": "https://github.com/dotnet/aspnetcore", - "commitSha": "92072c79ed8c2c86b093ebd676d531f5e5bf406b" + "commitSha": "343594eb69a5aa15377465351bb4381d9cee30c5" }, { "packageVersion": "0.11.5-alpha.25261.1", From b78736dd02d0c252cb87d7dfe901f1c4be5eb84a Mon Sep 17 00:00:00 2001 From: "dotnet-maestro[bot]" <42748379+dotnet-maestro[bot]@users.noreply.github.com> Date: Thu, 15 May 2025 11:05:41 +0000 Subject: [PATCH 06/11] [main] Source code updates from dotnet/roslyn (#565) Co-authored-by: dotnet-maestro[bot] Co-authored-by: Viktor Hofer --- prereqs/git-info/roslyn.props | 6 +- src/roslyn/.vscode/tasks.json | 2 +- src/roslyn/Roslyn.sln | 16 + .../features/file-based-programs-vscode.md | 59 + src/roslyn/eng/Version.Details.xml | 12 +- src/roslyn/eng/config/BannedSymbols.txt | 1 + src/roslyn/eng/config/PublishData.json | 1 + src/roslyn/eng/test-rebuild.ps1 | 1 + src/roslyn/global.json | 4 +- .../MakeFieldReadonlyTests.cs | 4 +- .../UseAutoProperty/UseAutoPropertyTests.cs | 16 +- .../Formatting/AbstractFormattingAnalyzer.cs | 1 + .../AbstractGenerateConstructorService.cs | 1 + ...oveUnnecessaryImportsDiagnosticAnalyzer.vb | 1 + .../UseAutoProperty/UseAutoPropertyTests.vb | 16 +- .../Microsoft.CodeAnalysis.CodeStyle.csproj | 1 + .../CSharpDeclarationComputer.cs | 1 + .../Binder/Binder.CapturedParametersFinder.cs | 1 + .../Portable/Binder/Binder_Deconstruct.cs | 2 +- .../Binder/Binder_InterpolatedString.cs | 2 +- .../Portable/Binder/Binder_Invocation.cs | 13 +- .../CSharp/Portable/Binder/Binder_Patterns.cs | 2 +- .../Portable/Binder/RefSafetyAnalysis.cs | 10 +- .../OverloadResolution/MethodTypeInference.cs | 2 +- .../CSharp/Portable/CSharpResources.resx | 2 +- .../Portable/Declarations/DeclarationTable.cs | 1 + .../Emitter/EditAndContinue/EmitHelpers.cs | 1 + .../Emitter/Model/AssemblyReference.cs | 5 +- .../Model/FunctionPointerTypeSymbolAdapter.cs | 1 + .../Portable/Emitter/Model/ModuleReference.cs | 1 + .../Emitter/Model/NamedTypeReference.cs | 1 + .../Emitter/Model/NamedTypeSymbolAdapter.cs | 1 + .../Portable/Emitter/Model/PEModuleBuilder.cs | 1 + .../Emitter/Model/PENetModuleBuilder.cs | 1 + .../Portable/Emitter/Model/SymbolAdapter.cs | 1 + .../Emitter/Model/TypeMemberReference.cs | 1 + .../Portable/Errors/CSDiagnosticInfo.cs | 1 + .../FlowAnalysis/AlwaysAssignedWalker.cs | 1 + .../FlowAnalysis/EmptyStructTypeCache.cs | 1 + .../FlowAnalysis/EntryPointsWalker.cs | 1 + .../FlowAnalysis/VariablesDeclaredWalker.cs | 3 +- .../SynthesizedClosureEnvironment.cs | 1 + .../LocalRewriter.PatternLocalRewriter.cs | 4 +- .../LocalRewriter_FixedStatement.cs | 1 + ...ObjectOrCollectionInitializerExpression.cs | 2 + .../Lowering/SynthesizedMethodBaseSymbol.cs | 1 + .../Lowering/SyntheticBoundNodeFactory.cs | 18 + .../SymbolDisplayVisitor_Minimal.cs | 1 + ...ymousManager.TypeOrDelegatePublicSymbol.cs | 1 + .../AnonymousType.DelegateTemplateSymbol.cs | 1 + ...nymousType.TypeOrDelegateTemplateSymbol.cs | 1 + .../Portable/Symbols/ArrayTypeSymbol.cs | 1 + .../Portable/Symbols/DynamicTypeSymbol.cs | 1 + .../Portable/Symbols/ErrorTypeSymbol.cs | 1 + .../FunctionPointerTypeSymbol.cs | 1 + .../Metadata/PE/PEGlobalNamespaceSymbol.cs | 11 +- .../Portable/Symbols/MissingAssemblySymbol.cs | 1 + .../Portable/Symbols/MissingModuleSymbol.cs | 1 + .../Portable/Symbols/NamespaceOrTypeSymbol.cs | 1 + .../Symbols/NativeIntegerTypeSymbol.cs | 1 + .../Portable/Symbols/PointerTypeSymbol.cs | 3 +- .../PropertyOrEventSymbolExtensions.cs | 1 + .../Symbols/Source/SourceAssemblySymbol.cs | 1 + .../Symbols/Source/SourceFixedFieldSymbol.cs | 1 + .../SourceMethodSymbolWithAttributes.cs | 1 + ...hesizedReadOnlyListEnumeratorTypeSymbol.cs | 1 + .../SynthesizedReadOnlyListTypeSymbol.cs | 1 + .../Records/SynthesizedPrimaryConstructor.cs | 1 + .../Synthesized/SynthesizedContainer.cs | 3 +- .../SynthesizedEmbeddedAttributeSymbol.cs | 7 +- .../SynthesizedInlineArrayTypeSymbol.cs | 1 + .../SynthesizedIntrinsicOperatorSymbol.cs | 3 +- ...hesizedPrivateImplementationDetailsType.cs | 1 + .../Portable/Symbols/TypeParameterSymbol.cs | 1 + .../Portable/Syntax/CSharpSyntaxTree.cs | 1 + .../Portable/Syntax/CompilationUnitSyntax.cs | 1 + .../Syntax/InternalSyntax/CSharpSyntaxNode.cs | 1 + .../Portable/xlf/CSharpResources.cs.xlf | 4 +- .../Portable/xlf/CSharpResources.de.xlf | 4 +- .../Portable/xlf/CSharpResources.es.xlf | 4 +- .../Portable/xlf/CSharpResources.fr.xlf | 4 +- .../Portable/xlf/CSharpResources.it.xlf | 4 +- .../Portable/xlf/CSharpResources.ja.xlf | 4 +- .../Portable/xlf/CSharpResources.ko.xlf | 4 +- .../Portable/xlf/CSharpResources.pl.xlf | 4 +- .../Portable/xlf/CSharpResources.pt-BR.xlf | 4 +- .../Portable/xlf/CSharpResources.ru.xlf | 4 +- .../Portable/xlf/CSharpResources.tr.xlf | 4 +- .../Portable/xlf/CSharpResources.zh-Hans.xlf | 4 +- .../Portable/xlf/CSharpResources.zh-Hant.xlf | 4 +- .../Test/CommandLine/CommandLineTests.cs | 5 +- .../Emit/CodeGen/CodeGenExprLambdaTests.cs | 356 -- .../Test/Emit/Emit/CompilationEmitTests.cs | 3 +- .../Test/Emit/Emit/EmitMetadataTests.cs | 1 + .../Test/Emit3/Semantics/ExtensionTests.cs | 4536 +++++++++++++---- .../Test/Emit3/Semantics/ExtensionTests2.cs | 636 +++ .../Test/Symbol/Symbols/IndexerTests.cs | 3 +- .../Symbol/Symbols/MockNamedTypeSymbol.cs | 1 + .../Symbol/Symbols/Source/BaseClassTests.cs | 3 +- .../Test/Symbol/Symbols/Source/MethodTests.cs | 1 + .../Symbol/Symbols/Source/PropertyTests.cs | 5 +- .../Syntax/Parsing/ExtensionsParsingTests.cs | 1 - .../AnalyzerDriver/DeclarationComputer.cs | 1 + .../Collections/EnumerableExtensionsTests.cs | 1 + .../SpecializedCollectionsTests.cs | 3 +- .../Core/MSBuildTask/ManagedCompiler.cs | 5 +- .../MSBuildTask/Microsoft.CSharp.Core.targets | 1 - .../Microsoft.VisualBasic.Core.targets | 1 - .../Core/Portable/AdditionalTextFile.cs | 1 + .../Core/Portable/CodeGen/ArrayMembers.cs | 5 +- .../Portable/Collections/TopologicalSort.cs | 1 + .../Portable/Collections/UnionCollection.cs | 5 +- .../Portable/CommandLine/CommandLineParser.cs | 1 + .../Core/Portable/Diagnostic/Diagnostic.cs | 1 + .../Core/Portable/Diagnostic/DiagnosticBag.cs | 3 +- .../Portable/Diagnostic/DiagnosticInfo.cs | 3 +- .../Diagnostic/Diagnostic_SimpleDiagnostic.cs | 1 + .../DiagnosticAnalyzer/AnalysisResult.cs | 1 + .../DiagnosticAnalyzer/AnalyzerManager.cs | 1 + .../Portable/Emit/CommonPEModuleBuilder.cs | 1 + .../Compilers/Core/Portable/Emit/ErrorType.cs | 1 + .../Emit/NoPia/CommonEmbeddedMethod.cs | 3 +- .../Portable/Emit/NoPia/CommonEmbeddedType.cs | 7 +- .../Emit/NoPia/CommonEmbeddedTypeParameter.cs | 3 +- .../Core/Portable/Emit/NoPia/VtblGap.cs | 3 +- .../Portable/MetadataReader/PEAssembly.cs | 1 + .../Core/Portable/MetadataReader/PEModule.cs | 1 + .../IOperation.OperationList.Reversed.cs | 3 +- .../Operations/IOperation.OperationList.cs | 1 + .../Core/Portable/PEWriter/ManagedResource.cs | 1 + .../Portable/PEWriter/MethodDefinitionBase.cs | 1 + .../PEWriter/ModifiedTypeReference.cs | 1 + .../Core/Portable/PEWriter/RootModuleType.cs | 1 + .../CommonReferenceManager.Resolution.cs | 1 + .../Core/Portable/SpecialTypeExtensions.cs | 3 - .../Syntax/ChildSyntaxList.Reversed.cs | 1 + .../Core/Portable/Syntax/ChildSyntaxList.cs | 1 + .../Core/Portable/Syntax/GreenNode.cs | 1 + .../Portable/Syntax/SeparatedSyntaxList.cs | 1 + .../Core/Portable/Syntax/SyntaxDiffer.cs | 1 + .../Core/Portable/Syntax/SyntaxList`1.cs | 1 + .../Core/Portable/Syntax/SyntaxNode.cs | 1 + .../Core/Portable/Syntax/SyntaxNodeOrToken.cs | 1 + .../Portable/Syntax/SyntaxNodeOrTokenList.cs | 1 + .../Core/Portable/Syntax/SyntaxToken.cs | 1 + .../Syntax/SyntaxTokenList.Reversed.cs | 1 + .../Core/Portable/Syntax/SyntaxTokenList.cs | 1 + .../Core/Portable/Syntax/SyntaxTrivia.cs | 1 + .../Syntax/SyntaxTriviaList.Reversed.cs | 1 + .../Core/Portable/Syntax/SyntaxTriviaList.cs | 1 + .../Core/Portable/Text/TextChange.cs | 1 + .../Core/Portable/Text/TextChangeRange.cs | 1 + .../src/Compilers/Core/Portable/TreeDumper.cs | 3 +- .../AnalyzerConsistencyChecker.cs | 5 +- .../ClrGlobalAssemblyCache.cs | 1 + .../MonoGlobalAssemblyCache.cs | 1 + .../Core/Compilation/TestOperationVisitor.cs | 1 + .../Test/Core/CompilationVerifier.cs | 1 + .../Test/Utilities/CSharp/CSharpTestBase.cs | 362 +- .../Test/Utilities/VisualBasic/MockSymbols.vb | 1 + .../VisualBasicDeclarationComputer.vb | 1 + .../FlowAnalysis/AlwaysAssignedWalker.vb | 1 + .../FlowAnalysis/EntryPointsWalker.vb | 1 + .../Analysis/FlowAnalysis/ExitPointsWalker.vb | 1 + .../FlowAnalysis/VariablesDeclaredWalker.vb | 1 + .../VisualBasicCommandLineParser.vb | 1 + .../Compilation/VisualBasicCompilation.vb | 1 + .../Portable/Emit/AssemblyReference.vb | 1 + .../Emit/EditAndContinue/EmitHelpers.vb | 1 + .../Portable/Emit/ModuleReference.vb | 1 + .../Portable/Emit/NamedTypeReference.vb | 1 + .../Portable/Emit/NamedTypeSymbolAdapter.vb | 1 + .../Portable/Emit/PEModuleBuilder.vb | 1 + .../Portable/Emit/PENetModuleBuilder.vb | 1 + .../Portable/Emit/SymbolAdapter.vb | 1 + .../Portable/Emit/TypeMemberReference.vb | 1 + .../Lowering/LambdaRewriter/LambdaFrame.vb | 1 + .../Lowering/LocalRewriter/LocalRewriter.vb | 1 + .../VisualBasic/Portable/Lowering/Rewriter.vb | 1 + .../AnonymousTypeOrDelegatePublicSymbol.vb | 1 + .../AnonymousDelegate_TemplateSymbol.vb | 1 + .../AnonymousTypeOrDelegateTemplateSymbol.vb | 1 + .../Portable/Symbols/ErrorMethodSymbol.vb | 1 + .../Portable/Symbols/ErrorTypeSymbol.vb | 1 + .../Metadata/PE/PEGlobalNamespaceSymbol.vb | 5 +- .../Symbols/Metadata/PE/PENamedTypeSymbol.vb | 1 + .../Metadata/PE/PEPropertyOrEventHelpers.vb | 1 + .../Portable/Symbols/MissingAssemblySymbol.vb | 1 + .../Portable/Symbols/MissingModuleSymbol.vb | 1 + .../Symbols/Source/ImplicitNamedTypeSymbol.vb | 1 + .../Symbols/Source/SourceAssemblySymbol.vb | 1 + .../Symbols/Source/SourceMethodSymbol.vb | 1 + .../Symbols/Source/SourceNamedTypeSymbol.vb | 1 + .../Source/SourceNamedTypeSymbol_ComClass.vb | 1 + .../SynthesizedEventDelegateSymbol.vb | 1 + .../SynthesizedHotReloadExceptionSymbol.vb | 1 + .../Portable/Symbols/UnboundGenericType.vb | 1 + .../Portable/Syntax/LambdaUtilities.vb | 3 +- .../Portable/Syntax/VisualBasicSyntaxTree.vb | 1 + .../Test/Emit/Emit/CompilationEmitTests.vb | 3 +- .../SymbolsTests/Source/PropertyTests.vb | 5 +- .../Symbol/SymbolsTests/SymbolErrorTests.vb | 1 + .../Extensions/IEnumerableExtensions.cs | 1 + ...SpecializedCollections.Empty.Collection.cs | 2 +- ...SpecializedCollections.Empty.Dictionary.cs | 2 +- ...SpecializedCollections.Empty.Enumerable.cs | 2 +- ...SpecializedCollections.Empty.Enumerator.cs | 2 +- ...ecializedCollections.Empty.Enumerator`1.cs | 2 +- .../SpecializedCollections.Empty.List.cs | 2 +- .../SpecializedCollections.Empty.Set.cs | 9 +- .../SpecializedCollections.Empty.cs | 2 +- ...cializedCollections.ReadOnly.Collection.cs | 2 +- ...alizedCollections.ReadOnly.Enumerable`1.cs | 2 +- ...alizedCollections.ReadOnly.Enumerable`2.cs | 2 +- .../SpecializedCollections.ReadOnly.Set.cs | 2 +- ...lizedCollections.Singleton.Collection`1.cs | 2 +- ...lizedCollections.Singleton.Enumerator`1.cs | 2 +- .../Specialized/SpecializedCollections.cs | 2 +- .../AddParameterTests.Formatting.cs | 4 +- .../ExtractInterface/ExtractInterfaceTests.cs | 2 +- .../NavigateTo/InteractiveNavigateToTests.cs | 2 +- .../CSharpTest/NavigateTo/NavigateToTests.cs | 4 +- .../Rename/CSharpInlineRenameServiceTests.cs | 22 +- .../Options/EditorAnalyzerConfigOptions.cs | 1 + .../Core/Preview/SolutionPreviewResult.cs | 1 + .../RefineUsingCopilotCodeAction.cs | 1 + .../Core/WpfClassificationExtensions.cs | 1 + ...ionOrUserDiagnosticTest_TestAddDocument.cs | 12 +- ...ctUserDiagnosticTest_GenerateTypeDialog.cs | 11 +- .../MoveType/AbstractMoveTypeTest.cs | 21 +- .../Test/CodeFixes/CodeFixServiceTests.cs | 1 + ...stractMetadataAsSourceTests.TestContext.cs | 2 +- .../Test2/CodeFixes/CodeFixServiceTests.vb | 1 + .../Diagnostics/DiagnosticProviderTests.vb | 3 +- .../Diagnostics/DiagnosticServiceTests.vb | 20 +- ...isualBasicCompletionCommandHandlerTests.vb | 1 + .../Test2/NavigationBar/TestHelpers.vb | 4 +- .../VisualBasicNavigationBarTests.vb | 18 +- .../EditorFeatures/Test2/Peek/PeekTests.vb | 6 +- .../Test2/Rename/RenameEngineTests.vb | 4 +- .../Test2/Rename/RenameTagProducerTests.vb | 3 +- .../SyncNamespacesServiceTests.vb | 73 +- .../AbstractGoToAdjacentMemberTests.cs | 1 + .../AutomaticLineEnderCommandHandler.vb | 1 + ...ndConstructStatementVisitor_IfStatement.vb | 1 + ...tractVisualBasicKeywordHighlighterTests.vb | 1 + .../NavigateTo/NavigateToTests.vb | 2 +- ...ionExpressionSignatureHelpProviderTests.vb | 1 + .../Symbols/EENamedTypeSymbol.cs | 1 + .../ExpressionCompiler/AssemblyReference.cs | 5 +- .../Source/ExpressionCompiler/DkmUtilities.cs | 1 + .../ExpressionCompiler/EEAssemblyBuilder.vb | 9 +- .../Symbols/EENamedTypeSymbol.vb | 1 + .../XmlDocCommentCompletionProvider.cs | 1 + .../TupleConstructionSignatureHelpProvider.cs | 1 + .../ExtractLocalFunctionTests.cs | 8 +- ...AbstractGlobalSuppressMessageCodeAction.cs | 5 +- .../AbstractMoveTypeService.Editor.cs | 6 + .../AbstractMoveTypeService.MoveTypeEditor.cs | 6 +- .../EditAndContinue/DeclarationBodyMap.cs | 1 + .../Utilities/BidirectionalMap.cs | 1 + .../ExtractInterfaceCodeAction.cs | 1 + .../AbstractSyntaxTriviaService.cs | 1 + .../AbstractGenerateTypeService.CodeAction.cs | 1 + .../AbstractStructuralTypeDisplayService.cs | 1 + .../AbstractSymbolDisplayService.cs | 1 + .../MoveStaticMembersOptions.cs | 6 +- .../MoveStaticMembersWithDialogCodeAction.cs | 4 +- .../Navigation/NavigableItemFactory.cs | 1 + ...stractReplacePropertyWithMethodsService.cs | 1 + .../AbstractSignatureHelpProvider.cs | 1 + .../Workspace/MiscellaneousFileUtilities.cs | 6 + .../Snippets/AbstractSnippetProviderTests.cs | 15 +- ...orrectFunctionReturnTypeCodeFixProvider.vb | 1 + .../MoveToTopOfFileCodeFixProvider.vb | 1 + .../CrefCompletionProvider.vb | 1 + .../NamedParameterCompletionProvider.vb | 11 +- .../XmlDocCommentCompletionProvider.vb | 1 + ...SwitchCodeRefactoringProvider.Rewriting.vb | 3 +- .../Portable/Debugging/BreakpointResolver.vb | 3 +- .../PropertyWithInitializerDeclarationBody.vb | 1 + .../PropertyWithNewClauseDeclarationBody.vb | 1 + .../VisualBasicEncapsulateFieldService.vb | 1 + ...isualBasicMethodExtractor.PostProcessor.vb | 1 + ...VisualBasicMethodExtractor.TriviaResult.vb | 1 + ...ethodExtractor.VisualBasicCodeGenerator.vb | 1 + .../VisualBasicNavigationBarItemService.vb | 1 + ...tIntrinsicOperatorSignatureHelpProvider.vb | 1 + .../AddRemoveHandlerSignatureHelpProvider.vb | 1 + .../CastExpressionSignatureHelpProvider.vb | 1 + ...unctionAggregationSignatureHelpProvider.vb | 1 + ...ionSignatureHelpProvider.DelegateInvoke.vb | 1 + ...sionSignatureHelpProvider.ElementAccess.vb | 1 + ...essionSignatureHelpProvider.MemberGroup.vb | 1 + ...vocationExpressionSignatureHelpProvider.vb | 1 + ...ssionSignatureHelpProvider.DelegateType.vb | 1 + ...inedCastExpressionSignatureHelpProvider.vb | 1 + .../TelemetryReporterTests.cs | 6 +- .../AbstractLanguageServerHostTests.cs | 4 +- .../LanguageServerTestComposition.cs | 14 +- .../WorkspaceProjectFactoryServiceTests.cs | 9 +- .../FileBasedProgramsProjectSystem.cs | 143 + ...leBasedProgramsWorkspaceProviderFactory.cs | 42 + .../LanguageServerProjectLoader.cs | 292 +- .../LanguageServerProjectSystem.cs | 77 +- .../HostWorkspace/LanguageServerWorkspace.cs | 16 +- .../LanguageServerWorkspaceFactory.cs | 24 +- .../HostWorkspace/LoadedProject.cs | 7 +- .../HostWorkspace/ProjectToLoad.cs | 2 +- .../Razor/RazorDynamicFileInfoProvider.cs | 4 +- .../HostWorkspace/VirtualProject.cs | 80 + .../WorkspaceProjectFactoryService.cs | 6 +- .../TestDiagnosticAnalyzerDriver.cs | 1 + .../AbstractLanguageServerProtocolTests.cs | 20 - .../Extensions/ProtocolConversions.cs | 4 +- ...nguageServerProjectSystemOptionsStorage.cs | 5 + .../Completion/CompletionCapabilityHelper.cs | 1 + ...igurationNotificationHandler_OptionList.cs | 1 + .../AbstractFormatDocumentHandlerBase.cs | 1 + ...ILspMiscellaneousFilesWorkspaceProvider.cs | 17 +- .../LspMiscellaneousFilesWorkspaceProvider.cs | 13 +- .../Workspaces/LspWorkspaceManager.cs | 42 +- ...ngeConfigurationNotificationHandlerTest.cs | 1 + .../Diagnostics/PullDiagnosticTests.cs | 74 +- .../Xaml/External/ConversionHelpers.cs | 5 +- .../External/IResolveCachedDataService.cs | 5 +- .../Xaml/External/ResolveDataConversions.cs | 16 +- .../Xaml/External/XamlRequestContext.cs | 5 +- .../Xaml/External/XamlRequestHandlerBase.cs | 4 +- .../External/XamlRequestHandlerFactoryBase.cs | 5 +- .../Xaml/InternalAPI.Unshipped.txt | 21 +- .../DesignerAttributeServiceTests.cs | 1 + .../DocumentOutlineTestsBase.cs | 34 +- .../CodeLens/ReferenceCodeLensProvider.cs | 1 + .../Utilities/AutomationDelegatingListView.cs | 4 +- .../CodeModel/AbstractCodeModelService.cs | 1 + .../Options/VisualStudioOptionStorageTests.cs | 1 + .../CodeModel/CSharp/RootCodeModelTests.vb | 9 +- .../VisualBasic/RootCodeModelTests.vb | 9 +- .../MoveStaticMembersViewModelTest.vb | 9 +- .../InheritsFromGraphQueryTests.vb | 14 +- .../SnippetCompletionProviderTests.vb | 1 + .../CpsDiagnosticItemSourceTests.vb | 4 +- .../CSharpContainedLanguageSupportTests.vb | 1 + .../Venus/DocumentService_IntegrationTests.vb | 17 +- ...isualBasicContainedLanguageSupportTests.vb | 1 + .../FSharp/Editor/FSharpNavigationBarItem.cs | 1 + .../Editor/FSharpNavigationBarItemService.cs | 1 + .../CodeModel/VisualBasicCodeModelService.vb | 1 + .../ContainedLanguageStaticEventBinding.vb | 1 + .../FindReferences/DependentTypeFinder.cs | 1 + .../Core/Portable/Formatting/Formatter.cs | 1 + .../Microsoft.CodeAnalysis.Workspaces.csproj | 1 + .../AbstractRecommendationService.cs | 1 + .../Workspace/Solution/ProjectInfo.cs | 1 + .../Portable/Workspace/Solution/Solution.cs | 2 + .../Workspace/Solution/SolutionState.cs | 1 + .../CoreTest/CodeCleanup/CodeCleanupTests.cs | 1 + .../CoreTest/SolutionTests/SolutionTests.cs | 5 +- .../UtilityTest/SpecializedTasksTests.cs | 1 + .../CoreTestUtilities/SolutionUtilities.cs | 2 +- .../Workspaces/TestHostDocument.cs | 3 +- .../Workspaces/TestHostProject`1.cs | 1 + .../Workspaces/TestWorkspace.cs | 2 + .../TestWorkspace_XmlConsumption.cs | 9 +- .../Core/CompilerExtensions.projitems | 36 - .../Core/Extensions/CompilationExtensions.cs | 89 - .../Core/Extensions/SpecialTypeExtensions.cs | 35 - .../SymbolUsageAnalysis.DataFlowAnalyzer.cs | 1 + .../SymbolUsageAnalysis.cs | 1 + .../IReadOnlyDictionaryExtensions.cs | 1 + .../Core/Utilities/SpecializedTasks.cs | 1 + .../Compilation/CompilationExtensions.cs} | 85 +- ...oft.CodeAnalysis.Extensions.Package.csproj | 34 + ...icrosoft.CodeAnalysis.Extensions.projitems | 51 + .../Microsoft.CodeAnalysis.Extensions.shproj | 14 + .../Symbols}/AccessibilityUtilities.cs | 0 .../Symbols}/IAssemblySymbolExtensions.cs | 0 .../Symbols}/IMethodSymbolExtensions.cs | 0 .../Symbols}/INamedTypeSymbolExtensions.cs | 0 .../INamespaceOrTypeSymbolExtensions.cs | 0 .../Symbols}/IParameterSymbolExtensions.cs | 0 .../Symbols}/IPropertySymbolExtensions.cs | 0 ...xtensions.RequiresUnsafeModifierVisitor.cs | 0 .../Symbols}/ISymbolExtensions.cs | 0 .../ISymbolExtensions_Accessibility.cs | 0 .../Symbols}/ITypeGenerator.cs | 0 .../ITypeParameterSymbolExtensions.cs | 0 ...peSymbolExtensions.AnonymousTypeRemover.cs | 0 ...ions.CollectTypeParameterSymbolsVisitor.cs | 0 ...mbolExtensions.CompilationTypeGenerator.cs | 0 ...lExtensions.MinimalAccessibilityVisitor.cs | 0 ...SymbolExtensions.SubstituteTypesVisitor.cs | 0 ...ensions.UnavailableTypeParameterRemover.cs | 0 ...ymbolExtensions.UnnamedErrorTypeRemover.cs | 0 .../Symbols}/ITypeSymbolExtensions.cs | 0 .../Symbols}/MethodKindExtensions.cs | 0 .../Symbols}/PredefinedOperator.cs | 0 .../Symbols}/PredefinedType.cs | 0 .../Symbols}/PredefinedTypeExtensions.cs | 25 + .../Symbols}/SignatureComparer.cs | 0 .../Symbols}/SymbolDisplayFormats.cs | 0 ...olEquivalenceComparer.AssemblyComparers.cs | 0 ...lEquivalenceComparer.EquivalenceVisitor.cs | 0 ...lEquivalenceComparer.GetHashCodeVisitor.cs | 0 ...omparer.ParameterSymbolEqualityComparer.cs | 0 ....SignatureTypeSymbolEquivalenceComparer.cs | 0 .../Symbols}/SymbolEquivalenceComparer.cs | 0 .../Symbols}/SymbolVisibility.cs | 0 .../Extensions/SemanticModelExtensions.vb | 1 + .../Extensions/SyntaxNodeExtensions.vb | 1 + .../VisualBasicSmartTokenFormatter.vb | 5 +- .../SemanticFacts/VisualBasicSemanticFacts.vb | 1 + .../SyntaxFacts/VisualBasicSyntaxFacts.vb | 2 + .../ContextQuery/SyntaxTreeExtensions.cs | 1 + .../Extensions/SemanticModelExtensions.cs | 1 + .../Symbols/CodeGenerationNamespaceInfo.cs | 1 + .../Symbols/CodeGenerationNamespaceSymbol.cs | 1 + .../Core/Extensions/DocumentExtensions.cs | 1 + .../Extensions/SemanticModelExtensions.vb | 1 + .../Indentation/SpecialFormattingOperation.vb | 1 + .../VisualBasicSyntaxGeneratorInternal.vb | 1 + ...lBasicTypeInferenceService.TypeInferrer.vb | 1 + .../AddMissingTokensCodeCleanupProvider.vb | 1 + .../FixIncorrectTokensCodeCleanupProvider.vb | 1 + ...ModifiersOrOperatorsCodeCleanupProvider.vb | 1 + .../VisualBasicSyntaxGenerator.vb | 1 + ...iviaDataFactory.AbstractLineBreakTrivia.vb | 1 + .../Rules/ElasticTriviaFormattingRule.vb | 1 + ...isualBasicRenameRewriterLanguageService.vb | 1 + .../VisualBasicFormattingTestBase.vb | 1 + src/source-manifest.json | 6 +- 432 files changed, 6333 insertions(+), 1963 deletions(-) create mode 100644 src/roslyn/docs/features/file-based-programs-vscode.md create mode 100644 src/roslyn/src/Compilers/CSharp/Test/Emit3/Semantics/ExtensionTests2.cs create mode 100644 src/roslyn/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer/HostWorkspace/FileBasedProgramsProjectSystem.cs create mode 100644 src/roslyn/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer/HostWorkspace/FileBasedProgramsWorkspaceProviderFactory.cs create mode 100644 src/roslyn/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer/HostWorkspace/VirtualProject.cs delete mode 100644 src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Extensions/CompilationExtensions.cs delete mode 100644 src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Extensions/SpecialTypeExtensions.cs rename src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/{Core/Extensions/ICompilationExtensions.cs => Extensions/Compilation/CompilationExtensions.cs} (80%) create mode 100644 src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Extensions/Microsoft.CodeAnalysis.Extensions.Package.csproj create mode 100644 src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Extensions/Microsoft.CodeAnalysis.Extensions.projitems create mode 100644 src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Extensions/Microsoft.CodeAnalysis.Extensions.shproj rename src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/{Core/Extensions => Extensions/Symbols}/AccessibilityUtilities.cs (100%) rename src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/{Core/Extensions => Extensions/Symbols}/IAssemblySymbolExtensions.cs (100%) rename src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/{Core/Extensions => Extensions/Symbols}/IMethodSymbolExtensions.cs (100%) rename src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/{Core/Extensions => Extensions/Symbols}/INamedTypeSymbolExtensions.cs (100%) rename src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/{Core/Extensions => Extensions/Symbols}/INamespaceOrTypeSymbolExtensions.cs (100%) rename src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/{Core/Extensions => Extensions/Symbols}/IParameterSymbolExtensions.cs (100%) rename src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/{Core/Extensions => Extensions/Symbols}/IPropertySymbolExtensions.cs (100%) rename src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/{Core/Extensions => Extensions/Symbols}/ISymbolExtensions.RequiresUnsafeModifierVisitor.cs (100%) rename src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/{Core/Extensions => Extensions/Symbols}/ISymbolExtensions.cs (100%) rename src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/{Core/Extensions => Extensions/Symbols}/ISymbolExtensions_Accessibility.cs (100%) rename src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/{Core/Extensions => Extensions/Symbols}/ITypeGenerator.cs (100%) rename src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/{Core/Extensions => Extensions/Symbols}/ITypeParameterSymbolExtensions.cs (100%) rename src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/{Core/Extensions => Extensions/Symbols}/ITypeSymbolExtensions.AnonymousTypeRemover.cs (100%) rename src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/{Core/Extensions => Extensions/Symbols}/ITypeSymbolExtensions.CollectTypeParameterSymbolsVisitor.cs (100%) rename src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/{Core/Extensions => Extensions/Symbols}/ITypeSymbolExtensions.CompilationTypeGenerator.cs (100%) rename src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/{Core/Extensions => Extensions/Symbols}/ITypeSymbolExtensions.MinimalAccessibilityVisitor.cs (100%) rename src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/{Core/Extensions => Extensions/Symbols}/ITypeSymbolExtensions.SubstituteTypesVisitor.cs (100%) rename src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/{Core/Extensions => Extensions/Symbols}/ITypeSymbolExtensions.UnavailableTypeParameterRemover.cs (100%) rename src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/{Core/Extensions => Extensions/Symbols}/ITypeSymbolExtensions.UnnamedErrorTypeRemover.cs (100%) rename src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/{Core/Extensions => Extensions/Symbols}/ITypeSymbolExtensions.cs (100%) rename src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/{Core/Extensions => Extensions/Symbols}/MethodKindExtensions.cs (100%) rename src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/{Core/Utilities => Extensions/Symbols}/PredefinedOperator.cs (100%) rename src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/{Core/Utilities => Extensions/Symbols}/PredefinedType.cs (100%) rename src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/{Core/Extensions => Extensions/Symbols}/PredefinedTypeExtensions.cs (55%) rename src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/{Core/Utilities => Extensions/Symbols}/SignatureComparer.cs (100%) rename src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/{Core/Utilities => Extensions/Symbols}/SymbolDisplayFormats.cs (100%) rename src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/{Core/Utilities => Extensions/Symbols}/SymbolEquivalenceComparer.AssemblyComparers.cs (100%) rename src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/{Core/Utilities => Extensions/Symbols}/SymbolEquivalenceComparer.EquivalenceVisitor.cs (100%) rename src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/{Core/Utilities => Extensions/Symbols}/SymbolEquivalenceComparer.GetHashCodeVisitor.cs (100%) rename src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/{Core/Utilities => Extensions/Symbols}/SymbolEquivalenceComparer.ParameterSymbolEqualityComparer.cs (100%) rename src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/{Core/Utilities => Extensions/Symbols}/SymbolEquivalenceComparer.SignatureTypeSymbolEquivalenceComparer.cs (100%) rename src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/{Core/Utilities => Extensions/Symbols}/SymbolEquivalenceComparer.cs (100%) rename src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/{Core/Utilities => Extensions/Symbols}/SymbolVisibility.cs (100%) diff --git a/prereqs/git-info/roslyn.props b/prereqs/git-info/roslyn.props index c7d2e942eeb..209afcda117 100644 --- a/prereqs/git-info/roslyn.props +++ b/prereqs/git-info/roslyn.props @@ -1,8 +1,8 @@  - 4215d71efbdb059bbb092fe9d385c11aba1c8969 - 20250512.9 - 5.0.0-1.25262.9 + 4358d1222f26078b302f1f79c18dee05a5f2766b + 20250514.5 + 5.0.0-1.25264.5 \ No newline at end of file diff --git a/src/roslyn/.vscode/tasks.json b/src/roslyn/.vscode/tasks.json index ea68cf0efae..78745a3ada3 100644 --- a/src/roslyn/.vscode/tasks.json +++ b/src/roslyn/.vscode/tasks.json @@ -169,7 +169,7 @@ "type": "process", "options": { "env": { - "DOTNET_ROSLYN_SERVER_PATH": "${workspaceRoot}/artifacts/bin/Microsoft.CodeAnalysis.LanguageServer/Debug/net8.0/Microsoft.CodeAnalysis.LanguageServer.dll" + "DOTNET_ROSLYN_SERVER_PATH": "${workspaceRoot}/artifacts/bin/Microsoft.CodeAnalysis.LanguageServer/Debug/net9.0/Microsoft.CodeAnalysis.LanguageServer.dll" } }, "dependsOn": [ "build language server" ] diff --git a/src/roslyn/Roslyn.sln b/src/roslyn/Roslyn.sln index fcfe71c1f73..683605cf978 100644 --- a/src/roslyn/Roslyn.sln +++ b/src/roslyn/Roslyn.sln @@ -725,6 +725,10 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "TestReferenceAssembly", "sr EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.CodeAnalysis.ExternalAccess.Extensions", "src\Tools\ExternalAccess\Extensions\Microsoft.CodeAnalysis.ExternalAccess.Extensions.csproj", "{6C816C16-D563-884A-D65B-5E68C6FB6659}" EndProject +Project("{D954291E-2A0B-460D-934E-DC6B0785DB48}") = "Microsoft.CodeAnalysis.Extensions", "src\Workspaces\SharedUtilitiesAndExtensions\Compiler\Extensions\Microsoft.CodeAnalysis.Extensions.shproj", "{02BCC112-0A29-43AA-84FA-C71C18A9486C}" +EndProject +Project("{9a19103f-16f7-4668-be54-9a1e7a4f7556}") = "Microsoft.CodeAnalysis.Extensions.Package", "src\Workspaces\SharedUtilitiesAndExtensions\Compiler\Extensions\Microsoft.CodeAnalysis.Extensions.Package.csproj", "{EEFAB994-3778-9C0D-1E88-C0ABB1D3DE43}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -1787,6 +1791,10 @@ Global {6C816C16-D563-884A-D65B-5E68C6FB6659}.Debug|Any CPU.Build.0 = Debug|Any CPU {6C816C16-D563-884A-D65B-5E68C6FB6659}.Release|Any CPU.ActiveCfg = Release|Any CPU {6C816C16-D563-884A-D65B-5E68C6FB6659}.Release|Any CPU.Build.0 = Release|Any CPU + {EEFAB994-3778-9C0D-1E88-C0ABB1D3DE43}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {EEFAB994-3778-9C0D-1E88-C0ABB1D3DE43}.Debug|Any CPU.Build.0 = Debug|Any CPU + {EEFAB994-3778-9C0D-1E88-C0ABB1D3DE43}.Release|Any CPU.ActiveCfg = Release|Any CPU + {EEFAB994-3778-9C0D-1E88-C0ABB1D3DE43}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE @@ -2126,6 +2134,8 @@ Global {29080628-23A6-1DCB-F15E-93F1D1682CC1} = {482C1FC7-4FD6-4381-8078-73BEBFAF4349} {31EB654C-B562-73B4-2456-78FA875515D2} = {0DDCFE67-7D4E-4709-9882-EC032A031789} {6C816C16-D563-884A-D65B-5E68C6FB6659} = {8977A560-45C2-4EC2-A849-97335B382C74} + {02BCC112-0A29-43AA-84FA-C71C18A9486C} = {7A69EA65-4411-4CD0-B439-035E720C1BD3} + {EEFAB994-3778-9C0D-1E88-C0ABB1D3DE43} = {7A69EA65-4411-4CD0-B439-035E720C1BD3} EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution SolutionGuid = {604E6B91-7BC0-4126-AE07-D4D2FEFC3D29} @@ -2134,6 +2144,7 @@ Global src\Analyzers\VisualBasic\CodeFixes\VisualBasicCodeFixes.projitems*{0141285d-8f6c-42c7-baf3-3c0ccd61c716}*SharedItemsImports = 5 src\Workspaces\SharedUtilitiesAndExtensions\Workspace\VisualBasic\VisualBasicWorkspaceExtensions.projitems*{0141285d-8f6c-42c7-baf3-3c0ccd61c716}*SharedItemsImports = 5 src\Compilers\CSharp\csc\CscCommandLine.projitems*{0161e25c-918a-4dc8-9648-30fdcc8e31e9}*SharedItemsImports = 5 + src\Workspaces\SharedUtilitiesAndExtensions\Compiler\Extensions\Microsoft.CodeAnalysis.Extensions.projitems*{02bcc112-0a29-43aa-84fa-c71c18a9486c}*SharedItemsImports = 13 src\RoslynAnalyzers\Utilities\Compiler\Analyzer.Utilities.projitems*{08735294-3e6b-4420-9916-e7b8c4eb874d}*SharedItemsImports = 13 src\RoslynAnalyzers\Utilities\Compiler\Analyzer.Utilities.projitems*{0a1267e9-52ff-b8de-8522-802be55f41da}*SharedItemsImports = 5 src\RoslynAnalyzers\Utilities\FlowAnalysis\FlowAnalysis.Utilities.projitems*{0a1267e9-52ff-b8de-8522-802be55f41da}*SharedItemsImports = 5 @@ -2160,6 +2171,7 @@ Global src\Dependencies\PooledObjects\Microsoft.CodeAnalysis.PooledObjects.projitems*{275812ee-dedb-4232-9439-91c9757d2ae4}*SharedItemsImports = 5 src\Dependencies\Threading\Microsoft.CodeAnalysis.Threading.projitems*{275812ee-dedb-4232-9439-91c9757d2ae4}*SharedItemsImports = 5 src\Workspaces\SharedUtilitiesAndExtensions\Compiler\Core\CompilerExtensions.projitems*{275812ee-dedb-4232-9439-91c9757d2ae4}*SharedItemsImports = 5 + src\Workspaces\SharedUtilitiesAndExtensions\Compiler\Extensions\Microsoft.CodeAnalysis.Extensions.projitems*{275812ee-dedb-4232-9439-91c9757d2ae4}*SharedItemsImports = 5 src\Dependencies\Contracts\Microsoft.CodeAnalysis.Contracts.projitems*{2801f82b-78ce-4bae-b06f-537574751e2e}*SharedItemsImports = 5 src\RoslynAnalyzers\Utilities\Refactoring.CSharp\Refactoring.CSharp.Utilities.projitems*{3055f932-0d1e-4823-a03a-7b62c7639bda}*SharedItemsImports = 13 src\ExpressionEvaluator\VisualBasic\Source\ResultProvider\BasicResultProvider.projitems*{3140fe61-0856-4367-9aa3-8081b9a80e35}*SharedItemsImports = 13 @@ -2184,6 +2196,7 @@ Global src\Dependencies\PooledObjects\Microsoft.CodeAnalysis.PooledObjects.projitems*{5f8d2414-064a-4b3a-9b42-8e2a04246be5}*SharedItemsImports = 5 src\Dependencies\Threading\Microsoft.CodeAnalysis.Threading.projitems*{5f8d2414-064a-4b3a-9b42-8e2a04246be5}*SharedItemsImports = 5 src\Workspaces\SharedUtilitiesAndExtensions\Compiler\Core\CompilerExtensions.projitems*{5f8d2414-064a-4b3a-9b42-8e2a04246be5}*SharedItemsImports = 5 + src\Workspaces\SharedUtilitiesAndExtensions\Compiler\Extensions\Microsoft.CodeAnalysis.Extensions.projitems*{5f8d2414-064a-4b3a-9b42-8e2a04246be5}*SharedItemsImports = 5 src\Workspaces\SharedUtilitiesAndExtensions\Workspace\Core\WorkspaceExtensions.projitems*{5f8d2414-064a-4b3a-9b42-8e2a04246be5}*SharedItemsImports = 5 src\Analyzers\Core\CodeFixes\CodeFixes.projitems*{5ff1e493-69cc-4d0b-83f2-039f469a04e1}*SharedItemsImports = 5 src\Workspaces\SharedUtilitiesAndExtensions\Workspace\Core\WorkspaceExtensions.projitems*{5ff1e493-69cc-4d0b-83f2-039f469a04e1}*SharedItemsImports = 5 @@ -2267,6 +2280,9 @@ Global src\Analyzers\Core\CodeFixes\CodeFixes.projitems*{edc68a0e-c68d-4a74-91b7-bf38ec909888}*SharedItemsImports = 5 src\Compilers\Core\AnalyzerDriver\AnalyzerDriver.projitems*{edc68a0e-c68d-4a74-91b7-bf38ec909888}*SharedItemsImports = 5 src\Dependencies\CodeAnalysis.Debugging\Microsoft.CodeAnalysis.Debugging.projitems*{edc68a0e-c68d-4a74-91b7-bf38ec909888}*SharedItemsImports = 5 + src\Dependencies\Collections\Microsoft.CodeAnalysis.Collections.projitems*{eefab994-3778-9c0d-1e88-c0abb1d3de43}*SharedItemsImports = 5 + src\Dependencies\Contracts\Microsoft.CodeAnalysis.Contracts.projitems*{eefab994-3778-9c0d-1e88-c0abb1d3de43}*SharedItemsImports = 5 + src\Dependencies\PooledObjects\Microsoft.CodeAnalysis.PooledObjects.projitems*{eefab994-3778-9c0d-1e88-c0abb1d3de43}*SharedItemsImports = 5 src\Dependencies\Contracts\Microsoft.CodeAnalysis.Contracts.projitems*{fa0e905d-ec46-466d-b7b2-3b5557f9428c}*SharedItemsImports = 5 src\ExpressionEvaluator\Core\Source\ResultProvider\ResultProvider.projitems*{fa0e905d-ec46-466d-b7b2-3b5557f9428c}*SharedItemsImports = 5 src\Dependencies\Contracts\Microsoft.CodeAnalysis.Contracts.projitems*{fc2ae90b-2e4b-4045-9fdd-73d4f5ed6c89}*SharedItemsImports = 5 diff --git a/src/roslyn/docs/features/file-based-programs-vscode.md b/src/roslyn/docs/features/file-based-programs-vscode.md new file mode 100644 index 00000000000..dddaa13667d --- /dev/null +++ b/src/roslyn/docs/features/file-based-programs-vscode.md @@ -0,0 +1,59 @@ +# File-based programs VS Code support + +See also [dotnet-run-file.md](https://github.com/dotnet/sdk/blob/main/documentation/general/dotnet-run-file.md). + +## Feature overview + +A file-based program embeds a subset of MSBuild project capabilities into C# code, allowing single files to stand alone as ordinary projects. + +The following is a file-based program: + +```cs +Console.WriteLine("Hello World!"); +``` + +So is the following: + +```cs +#!/usr/bin/env dotnet run +#:sdk Microsoft.Net.Sdk +#:package Newtonsoft.Json@13.0.3 +#:property LangVersion=preview + +using Newtonsoft.Json; + +Main(); + +void Main() +{ + if (args is not [_, var jsonPath, ..]) + { + Console.Error.WriteLine("Usage: app "); + return; + } + + var json = File.ReadAllText(jsonPath); + var data = JsonConvert.DeserializeObject(json); + // ... +} + +record Data(string field1, int field2); +``` + +This basically works by having the `dotnet` command line interpret the `#:` directives in source files, produce a C# project XML document in memory, and pass it off to MSBuild. The in-memory project is sometimes called a "virtual project". + +## Miscellaneous files changes + +There is a long-standing backlog item to enhance the experience of working with miscellaneous files ("loose files" not associated with any project). We think that as part of the "file-based program" work, we can enable the following in such files without substantial issues: +- Syntax diagnostics. +- Intellisense for the "default" set of references. e.g. those references which are included in the project created by `dotnet new console` with the current SDK. + +### Heuristic +The IDE considers a file to be a file-based program, if: +- It has any `#:` directives which configure the file-based program project, or, +- It has any top-level statements. +Any of the above is met, and, the file is not included in an ordinary `.csproj` project (i.e. it is not part of any ordinary project's list of `Compile` items). + +### Opt-out + +We added an opt-out flag with option name `dotnet.projects.enableFileBasedPrograms`. If issues arise with the file-based program experience, then VS Code users should set the corresponding setting `"dotnet.projects.enableFileBasedPrograms": false` to revert back to the old miscellaneous files experience. diff --git a/src/roslyn/eng/Version.Details.xml b/src/roslyn/eng/Version.Details.xml index 711efd18b94..9af6ee4e621 100644 --- a/src/roslyn/eng/Version.Details.xml +++ b/src/roslyn/eng/Version.Details.xml @@ -110,13 +110,13 @@ - + https://github.com/dotnet/arcade - 1cfa39f82d00b3659a3d367bc344241946e10681 + ac63dcf2791c32bf2102fd2b5ebb46479bd48a83 - + https://github.com/dotnet/arcade - 1cfa39f82d00b3659a3d367bc344241946e10681 + ac63dcf2791c32bf2102fd2b5ebb46479bd48a83 https://github.com/dotnet/symreader @@ -126,9 +126,9 @@ https://github.com/dotnet/roslyn 5d10d428050c0d6afef30a072c4ae68776621877 - + https://github.com/dotnet/arcade - 1cfa39f82d00b3659a3d367bc344241946e10681 + ac63dcf2791c32bf2102fd2b5ebb46479bd48a83 https://github.com/dotnet/roslyn-analyzers diff --git a/src/roslyn/eng/config/BannedSymbols.txt b/src/roslyn/eng/config/BannedSymbols.txt index d8c18b513fd..8558e121b5d 100644 --- a/src/roslyn/eng/config/BannedSymbols.txt +++ b/src/roslyn/eng/config/BannedSymbols.txt @@ -59,6 +59,7 @@ M:Microsoft.CodeAnalysis.VisualBasic.VisualBasicSyntaxTree.Create(Microsoft.Code M:Microsoft.CodeAnalysis.VisualBasic.VisualBasicSyntaxTree.Create(Microsoft.CodeAnalysis.VisualBasic.VisualBasicSyntaxNode,Microsoft.CodeAnalysis.VisualBasic.VisualBasicParseOptions,System.String,System.Text.Encoding); Use VisualBasicSyntaxTree sublass that takes checksum algorithm M:Microsoft.CodeAnalysis.VisualBasic.VisualBasicSyntaxTree.ParseText(System.String,Microsoft.CodeAnalysis.VisualBasic.VisualBasicParseOptions,System.String,System.Text.Encoding,System.Collections.Immutable.ImmutableDictionary{System.String,Microsoft.CodeAnalysis.ReportDiagnostic},System.Threading.CancellationToken); Use overload with SourceText M:Microsoft.CodeAnalysis.Workspaces.Workspace.SetCurrentSolution(Microsoft.CodeAnalysis.Solution); Use SetCurrentSolutionEx instead. +M:Microsoft.CodeAnalysis.Project.AddDocument(System.String,System.String,System.Collections.Generic.IEnumerable{System.String},System.String); Use overload that takes SourceText. Make sure SourceText is created with encoding and checksum algorithm. M:System.Enum.GetHashCode(); Cast to integral type to avoid boxing on .NET Framework M:Microsoft.CodeAnalysis.CodeActions.CodeAction.PostProcessAsync(System.Collections.Generic.IEnumerable{Microsoft.CodeAnalysis.CodeActions.CodeActionOperation},System.Threading.CancellationToken); Use overload that takes a solution M:Microsoft.CodeAnalysis.CodeActions.CodeAction.PostProcessChangesAsync(Microsoft.CodeAnalysis.Solution,System.Threading.CancellationToken); Use overload that takes a solution diff --git a/src/roslyn/eng/config/PublishData.json b/src/roslyn/eng/config/PublishData.json index 44e979e154e..1d494eeb3f5 100644 --- a/src/roslyn/eng/config/PublishData.json +++ b/src/roslyn/eng/config/PublishData.json @@ -36,6 +36,7 @@ "Microsoft.CodeAnalysis.PooledObjects": "arcade", "Microsoft.CodeAnalysis.Collections": "arcade", "Microsoft.CodeAnalysis.Threading": "arcade", + "Microsoft.CodeAnalysis.Extensions": "vs-impl", "Microsoft.CodeAnalysis.Features": "arcade", "Microsoft.CodeAnalysis.EditorFeatures": "vssdk", "Microsoft.CodeAnalysis.EditorFeatures.Common": "vssdk", diff --git a/src/roslyn/eng/test-rebuild.ps1 b/src/roslyn/eng/test-rebuild.ps1 index d58e2a4f1e2..8f6e6d33a8c 100644 --- a/src/roslyn/eng/test-rebuild.ps1 +++ b/src/roslyn/eng/test-rebuild.ps1 @@ -65,6 +65,7 @@ try { " --exclude netstandard2.0\Microsoft.CodeAnalysis.Debugging.Package.dll" + " --exclude netstandard2.0\Microsoft.CodeAnalysis.PooledObjects.Package.dll" + " --exclude netstandard2.0\Microsoft.CodeAnalysis.Threading.Package.dll" + + " --exclude netstandard2.0\Microsoft.CodeAnalysis.Extensions.Package.dll" + " --exclude netcoreapp3.1\Microsoft.CodeAnalysis.Workspaces.UnitTests.dll" + " --exclude net472\Zip\tools\vsixexpinstaller\System.ValueTuple.dll" + " --exclude net472\Zip\tools\vsixexpinstaller\VSIXExpInstaller.exe" + diff --git a/src/roslyn/global.json b/src/roslyn/global.json index d966053a94b..c3f433c9da3 100644 --- a/src/roslyn/global.json +++ b/src/roslyn/global.json @@ -11,8 +11,8 @@ } }, "msbuild-sdks": { - "Microsoft.DotNet.Arcade.Sdk": "9.0.0-beta.25255.5", - "Microsoft.DotNet.Helix.Sdk": "9.0.0-beta.25255.5", + "Microsoft.DotNet.Arcade.Sdk": "9.0.0-beta.25263.2", + "Microsoft.DotNet.Helix.Sdk": "9.0.0-beta.25263.2", "Microsoft.Build.Traversal": "3.4.0" } } diff --git a/src/roslyn/src/Analyzers/CSharp/Tests/MakeFieldReadonly/MakeFieldReadonlyTests.cs b/src/roslyn/src/Analyzers/CSharp/Tests/MakeFieldReadonly/MakeFieldReadonlyTests.cs index 64900d236f1..19047d5507c 100644 --- a/src/roslyn/src/Analyzers/CSharp/Tests/MakeFieldReadonly/MakeFieldReadonlyTests.cs +++ b/src/roslyn/src/Analyzers/CSharp/Tests/MakeFieldReadonly/MakeFieldReadonlyTests.cs @@ -2012,7 +2012,7 @@ await TestMissingInRegularAndScriptAsync( """ - + public sealed partial class Test { private int [|_value|]; @@ -2021,7 +2021,7 @@ public static void M() => _ = new Test { Value = 1 }; } - + using System.CodeDom.Compiler; [GeneratedCode(null, null)] diff --git a/src/roslyn/src/Analyzers/CSharp/Tests/UseAutoProperty/UseAutoPropertyTests.cs b/src/roslyn/src/Analyzers/CSharp/Tests/UseAutoProperty/UseAutoPropertyTests.cs index dee40acd9b0..600dd05a4ac 100644 --- a/src/roslyn/src/Analyzers/CSharp/Tests/UseAutoProperty/UseAutoPropertyTests.cs +++ b/src/roslyn/src/Analyzers/CSharp/Tests/UseAutoProperty/UseAutoPropertyTests.cs @@ -2751,7 +2751,7 @@ await TestInRegularAndScript1Async( """ - + public class Foo { private readonly object o; @@ -2759,7 +2759,7 @@ public class Foo [||]public object O => o; } - + [*] indent_style = tab @@ -2769,13 +2769,13 @@ public class Foo """ - + public class Foo { public object O { get; } } - + [*] indent_style = tab @@ -2791,7 +2791,7 @@ await TestInRegularAndScript1Async( """ - + public class Foo { private readonly object o; @@ -2799,7 +2799,7 @@ public class Foo [||]public object O => o; } - + [*] indent_style = space @@ -2809,13 +2809,13 @@ public class Foo """ - + public class Foo { public object O { get; } } - + [*] indent_style = space diff --git a/src/roslyn/src/Analyzers/Core/Analyzers/Formatting/AbstractFormattingAnalyzer.cs b/src/roslyn/src/Analyzers/Core/Analyzers/Formatting/AbstractFormattingAnalyzer.cs index 7d4f8392dff..4d168bbc826 100644 --- a/src/roslyn/src/Analyzers/Core/Analyzers/Formatting/AbstractFormattingAnalyzer.cs +++ b/src/roslyn/src/Analyzers/Core/Analyzers/Formatting/AbstractFormattingAnalyzer.cs @@ -2,6 +2,7 @@ // 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.Collections; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Text; diff --git a/src/roslyn/src/Analyzers/Core/CodeFixes/GenerateConstructor/AbstractGenerateConstructorService.cs b/src/roslyn/src/Analyzers/Core/CodeFixes/GenerateConstructor/AbstractGenerateConstructorService.cs index 587e31e3c10..cf95b95ade7 100644 --- a/src/roslyn/src/Analyzers/Core/CodeFixes/GenerateConstructor/AbstractGenerateConstructorService.cs +++ b/src/roslyn/src/Analyzers/Core/CodeFixes/GenerateConstructor/AbstractGenerateConstructorService.cs @@ -10,6 +10,7 @@ using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeGeneration; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.Diagnostics.Analyzers.NamingStyles; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.LanguageService; diff --git a/src/roslyn/src/Analyzers/VisualBasic/Analyzers/RemoveUnnecessaryImports/VisualBasicRemoveUnnecessaryImportsDiagnosticAnalyzer.vb b/src/roslyn/src/Analyzers/VisualBasic/Analyzers/RemoveUnnecessaryImports/VisualBasicRemoveUnnecessaryImportsDiagnosticAnalyzer.vb index 2352fc3b1e0..4351838cff6 100644 --- a/src/roslyn/src/Analyzers/VisualBasic/Analyzers/RemoveUnnecessaryImports/VisualBasicRemoveUnnecessaryImportsDiagnosticAnalyzer.vb +++ b/src/roslyn/src/Analyzers/VisualBasic/Analyzers/RemoveUnnecessaryImports/VisualBasicRemoveUnnecessaryImportsDiagnosticAnalyzer.vb @@ -5,6 +5,7 @@ Imports System.Collections.Immutable Imports System.Threading Imports Microsoft.CodeAnalysis +Imports Microsoft.CodeAnalysis.Collections Imports Microsoft.CodeAnalysis.Diagnostics Imports Microsoft.CodeAnalysis.LanguageService Imports Microsoft.CodeAnalysis.PooledObjects diff --git a/src/roslyn/src/Analyzers/VisualBasic/Tests/UseAutoProperty/UseAutoPropertyTests.vb b/src/roslyn/src/Analyzers/VisualBasic/Tests/UseAutoProperty/UseAutoPropertyTests.vb index b4315767663..6b45bb99245 100644 --- a/src/roslyn/src/Analyzers/VisualBasic/Tests/UseAutoProperty/UseAutoPropertyTests.vb +++ b/src/roslyn/src/Analyzers/VisualBasic/Tests/UseAutoProperty/UseAutoPropertyTests.vb @@ -1126,7 +1126,7 @@ End Class", options:=[Option](FormattingOptions2.UseTabs, False)) Await TestInRegularAndScriptAsync( " - + Public Class Foo [||]Private ReadOnly o2 As Object @@ -1137,7 +1137,7 @@ Public Class Foo End Property End Class - + [*] indent_style = tab @@ -1145,12 +1145,12 @@ indent_style = tab ", " - + Public Class Foo Public ReadOnly Property O As Object End Class - + [*] indent_style = tab @@ -1163,7 +1163,7 @@ indent_style = tab Await TestInRegularAndScriptAsync( " - + Public Class Foo [||]Private ReadOnly o2 As Object @@ -1174,7 +1174,7 @@ Public Class Foo End Property End Class - + [*] indent_style = space @@ -1182,12 +1182,12 @@ indent_style = space ", " - + Public Class Foo Public ReadOnly Property O As Object End Class - + [*] indent_style = space diff --git a/src/roslyn/src/CodeStyle/Core/Analyzers/Microsoft.CodeAnalysis.CodeStyle.csproj b/src/roslyn/src/CodeStyle/Core/Analyzers/Microsoft.CodeAnalysis.CodeStyle.csproj index 8860cb81eed..928ffeb9c51 100644 --- a/src/roslyn/src/CodeStyle/Core/Analyzers/Microsoft.CodeAnalysis.CodeStyle.csproj +++ b/src/roslyn/src/CodeStyle/Core/Analyzers/Microsoft.CodeAnalysis.CodeStyle.csproj @@ -51,5 +51,6 @@ + \ No newline at end of file diff --git a/src/roslyn/src/Compilers/CSharp/CSharpAnalyzerDriver/CSharpDeclarationComputer.cs b/src/roslyn/src/Compilers/CSharp/CSharpAnalyzerDriver/CSharpDeclarationComputer.cs index 85c78efd1a2..e2bef81c113 100644 --- a/src/roslyn/src/Compilers/CSharp/CSharpAnalyzerDriver/CSharpDeclarationComputer.cs +++ b/src/roslyn/src/Compilers/CSharp/CSharpAnalyzerDriver/CSharpDeclarationComputer.cs @@ -10,6 +10,7 @@ using System.Diagnostics; using System.Linq; using System.Threading; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Text; diff --git a/src/roslyn/src/Compilers/CSharp/Portable/Binder/Binder.CapturedParametersFinder.cs b/src/roslyn/src/Compilers/CSharp/Portable/Binder/Binder.CapturedParametersFinder.cs index 8a67729e863..ed16cb85c3d 100644 --- a/src/roslyn/src/Compilers/CSharp/Portable/Binder/Binder.CapturedParametersFinder.cs +++ b/src/roslyn/src/Compilers/CSharp/Portable/Binder/Binder.CapturedParametersFinder.cs @@ -4,6 +4,7 @@ using System.Collections.Generic; using System.Diagnostics; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; diff --git a/src/roslyn/src/Compilers/CSharp/Portable/Binder/Binder_Deconstruct.cs b/src/roslyn/src/Compilers/CSharp/Portable/Binder/Binder_Deconstruct.cs index 06a853b99f7..36f16a49668 100644 --- a/src/roslyn/src/Compilers/CSharp/Portable/Binder/Binder_Deconstruct.cs +++ b/src/roslyn/src/Compilers/CSharp/Portable/Binder/Binder_Deconstruct.cs @@ -683,7 +683,7 @@ private BoundExpression MakeDeconstructInvocationExpression( // This prevents, for example, an unused params parameter after the out parameters. var deconstructMethod = ((BoundCall)result).Method; var parameters = deconstructMethod.Parameters; - for (int i = (deconstructMethod.IsExtensionMethod ? 1 : 0); i < parameters.Length; i++) // Tracked by https://github.com/dotnet/roslyn/issues/76130: Test this code path with new extensions + for (int i = (deconstructMethod.IsExtensionMethod ? 1 : 0); i < parameters.Length; i++) { if (parameters[i].RefKind != RefKind.Out) { diff --git a/src/roslyn/src/Compilers/CSharp/Portable/Binder/Binder_InterpolatedString.cs b/src/roslyn/src/Compilers/CSharp/Portable/Binder/Binder_InterpolatedString.cs index 2fe795e8b50..fb21a3e6ba5 100644 --- a/src/roslyn/src/Compilers/CSharp/Portable/Binder/Binder_InterpolatedString.cs +++ b/src/roslyn/src/Compilers/CSharp/Portable/Binder/Binder_InterpolatedString.cs @@ -339,7 +339,7 @@ private BoundInterpolatedString BindUnconvertedInterpolatedExpressionToFactory( SyntaxNode syntax = unconvertedSource.Syntax; ImmutableArray expressions = makeInterpolatedStringFactoryArguments(syntax, parts, diagnostics); - BoundExpression construction = MakeInvocationExpression( + BoundExpression construction = MakeInvocationExpression( // Tracked by https://github.com/dotnet/roslyn/issues/76130 : test this scenario with a delegate-returning property (should be blocked by virtue of allowFieldsAndProperties: false) syntax, new BoundTypeExpression(syntax, null, factoryType) { WasCompilerGenerated = true }, factoryMethod, diff --git a/src/roslyn/src/Compilers/CSharp/Portable/Binder/Binder_Invocation.cs b/src/roslyn/src/Compilers/CSharp/Portable/Binder/Binder_Invocation.cs index c434edd5229..ef11a6d9fb0 100644 --- a/src/roslyn/src/Compilers/CSharp/Portable/Binder/Binder_Invocation.cs +++ b/src/roslyn/src/Compilers/CSharp/Portable/Binder/Binder_Invocation.cs @@ -137,11 +137,11 @@ internal BoundExpression MakeInvocationExpression( } BoundExpression result = BindInvocationExpression( - node, node, methodName, boundExpression, analyzedArguments, diagnostics, queryClause, - ignoreNormalFormIfHasValidParamsParameter: ignoreNormalFormIfHasValidParamsParameter, + node, node, methodName, boundExpression, analyzedArguments, diagnostics, acceptOnlyMethods: !allowFieldsAndProperties, + queryClause, ignoreNormalFormIfHasValidParamsParameter: ignoreNormalFormIfHasValidParamsParameter, disallowExpandedNonArrayParams: disallowExpandedNonArrayParams); - // Query operator can't be called dynamically. + // Query operator can't be called dynamically. if (queryClause != null && result.Kind == BoundKind.DynamicInvocation) { // the error has already been reported by BindInvocationExpression @@ -245,7 +245,7 @@ BoundExpression bindArgumentsAndInvocation(InvocationExpressionSyntax node, Boun boundExpression = CheckValue(boundExpression, BindValueKind.RValueOrMethodGroup, diagnostics); string name = boundExpression.Kind == BoundKind.MethodGroup ? GetName(node.Expression) : null; BindArgumentsAndNames(node.ArgumentList, diagnostics, analyzedArguments, allowArglist: true); - return BindInvocationExpression(node, node.Expression, name, boundExpression, analyzedArguments, diagnostics); + return BindInvocationExpression(node, node.Expression, name, boundExpression, analyzedArguments, diagnostics, acceptOnlyMethods: false); } static bool receiverIsInvocation(InvocationExpressionSyntax node, out InvocationExpressionSyntax nested) @@ -324,6 +324,7 @@ private BoundExpression BindInvocationExpression( BoundExpression boundExpression, AnalyzedArguments analyzedArguments, BindingDiagnosticBag diagnostics, + bool acceptOnlyMethods, CSharpSyntaxNode queryClause = null, bool ignoreNormalFormIfHasValidParamsParameter = false, bool disallowExpandedNonArrayParams = false) @@ -356,7 +357,7 @@ private BoundExpression BindInvocationExpression( ignoreNormalFormIfHasValidParamsParameter: ignoreNormalFormIfHasValidParamsParameter, disallowExpandedNonArrayParams: disallowExpandedNonArrayParams, anyApplicableCandidates: out _, - acceptOnlyMethods: false); + acceptOnlyMethods: acceptOnlyMethods); } else if ((object)(delegateType = GetDelegateType(boundExpression)) != null) { @@ -727,7 +728,7 @@ private BoundExpression BindMethodGroupInvocation( Debug.Assert(extensionMemberAccess.Kind != BoundKind.MethodGroup); extensionMemberAccess = CheckValue(extensionMemberAccess, BindValueKind.RValue, diagnostics); - BoundExpression extensionMemberInvocation = BindInvocationExpression(syntax, expression, methodName: null, extensionMemberAccess, analyzedArguments, diagnostics); + BoundExpression extensionMemberInvocation = BindInvocationExpression(syntax, expression, methodName: null, extensionMemberAccess, analyzedArguments, diagnostics, acceptOnlyMethods: false); anyApplicableCandidates = !extensionMemberInvocation.HasAnyErrors; return extensionMemberInvocation; } diff --git a/src/roslyn/src/Compilers/CSharp/Portable/Binder/Binder_Patterns.cs b/src/roslyn/src/Compilers/CSharp/Portable/Binder/Binder_Patterns.cs index ce3304eef8d..860fbe3e565 100644 --- a/src/roslyn/src/Compilers/CSharp/Portable/Binder/Binder_Patterns.cs +++ b/src/roslyn/src/Compilers/CSharp/Portable/Binder/Binder_Patterns.cs @@ -1058,7 +1058,7 @@ deconstructMethod is null && if (deconstructMethod is null) hasErrors = true; - int skippedExtensionParameters = deconstructMethod?.IsExtensionMethod == true ? 1 : 0; // Tracked by https://github.com/dotnet/roslyn/issues/76130: Test this code path with new extensions + int skippedExtensionParameters = deconstructMethod?.IsExtensionMethod == true ? 1 : 0; for (int i = 0; i < node.Subpatterns.Count; i++) { var subPattern = node.Subpatterns[i]; diff --git a/src/roslyn/src/Compilers/CSharp/Portable/Binder/RefSafetyAnalysis.cs b/src/roslyn/src/Compilers/CSharp/Portable/Binder/RefSafetyAnalysis.cs index 91747ec2bbc..019efd40e18 100644 --- a/src/roslyn/src/Compilers/CSharp/Portable/Binder/RefSafetyAnalysis.cs +++ b/src/roslyn/src/Compilers/CSharp/Portable/Binder/RefSafetyAnalysis.cs @@ -627,7 +627,7 @@ static SafeContext getDeclarationValEscape(BoundTypeExpression typeExpression, S // and so the ref safety of the pattern is equivalent to a `Deconstruct(out var ...)` invocation // where "safe-context inference of declaration expressions" would have the same effect. if (node.DeconstructMethod is { } m && - tryGetThisParameter(m)?.EffectiveScope == ScopedKind.None) + tryGetReceiverParameter(m)?.EffectiveScope == ScopedKind.None) { using (new PatternInput(this, _localScopeDepth)) { @@ -637,12 +637,16 @@ static SafeContext getDeclarationValEscape(BoundTypeExpression typeExpression, S return base.VisitRecursivePattern(node); - static ParameterSymbol? tryGetThisParameter(MethodSymbol method) + static ParameterSymbol? tryGetReceiverParameter(MethodSymbol method) { - if (method.IsExtensionMethod) // Tracked by https://github.com/dotnet/roslyn/issues/76130: Test this code path with new extensions + if (method.IsExtensionMethod) { return method.Parameters is [{ } firstParameter, ..] ? firstParameter : null; } + else if (method.GetIsNewExtensionMember()) + { + return method.ContainingType.ExtensionParameter; + } return method.TryGetThisParameter(out var thisParameter) ? thisParameter : null; } diff --git a/src/roslyn/src/Compilers/CSharp/Portable/Binder/Semantics/OverloadResolution/MethodTypeInference.cs b/src/roslyn/src/Compilers/CSharp/Portable/Binder/Semantics/OverloadResolution/MethodTypeInference.cs index 6739e439ee5..e6c1bb9edd3 100644 --- a/src/roslyn/src/Compilers/CSharp/Portable/Binder/Semantics/OverloadResolution/MethodTypeInference.cs +++ b/src/roslyn/src/Compilers/CSharp/Portable/Binder/Semantics/OverloadResolution/MethodTypeInference.cs @@ -652,7 +652,7 @@ private void MakeExplicitParameterTypeInferences(Binder binder, BoundExpression } else if (IsUnfixedTypeParameter(target) && !target.NullableAnnotation.IsAnnotated() && kind is ExactOrBoundsKind.LowerBound) { - var ordinal = GetOrdinal((TypeParameterSymbol)target.Type); // Tracked by https://github.com/dotnet/roslyn/issues/76130 : test nullability scenario where the override of ordinals matters + var ordinal = GetOrdinal((TypeParameterSymbol)target.Type); _nullableAnnotationLowerBounds[ordinal] = _nullableAnnotationLowerBounds[ordinal].Join(argumentType.NullableAnnotation); } } diff --git a/src/roslyn/src/Compilers/CSharp/Portable/CSharpResources.resx b/src/roslyn/src/Compilers/CSharp/Portable/CSharpResources.resx index 61cb849a9e4..b3f569a40c1 100644 --- a/src/roslyn/src/Compilers/CSharp/Portable/CSharpResources.resx +++ b/src/roslyn/src/Compilers/CSharp/Portable/CSharpResources.resx @@ -547,7 +547,7 @@ Inconsistent accessibility: indexer return type '{1}' is less accessible than indexer '{0}' - Inconsistent accessibility: parameter type '{1}' is less accessible than indexer '{0}' + Inconsistent accessibility: parameter type '{1}' is less accessible than indexer or property '{0}' Inconsistent accessibility: return type '{1}' is less accessible than operator '{0}' diff --git a/src/roslyn/src/Compilers/CSharp/Portable/Declarations/DeclarationTable.cs b/src/roslyn/src/Compilers/CSharp/Portable/Declarations/DeclarationTable.cs index 35274e114af..44c7cfa969a 100644 --- a/src/roslyn/src/Compilers/CSharp/Portable/Declarations/DeclarationTable.cs +++ b/src/roslyn/src/Compilers/CSharp/Portable/Declarations/DeclarationTable.cs @@ -6,6 +6,7 @@ using System.Collections.Generic; using System.Diagnostics; using System.Threading; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; diff --git a/src/roslyn/src/Compilers/CSharp/Portable/Emitter/EditAndContinue/EmitHelpers.cs b/src/roslyn/src/Compilers/CSharp/Portable/Emitter/EditAndContinue/EmitHelpers.cs index 03e2185b727..222963e9f55 100644 --- a/src/roslyn/src/Compilers/CSharp/Portable/Emitter/EditAndContinue/EmitHelpers.cs +++ b/src/roslyn/src/Compilers/CSharp/Portable/Emitter/EditAndContinue/EmitHelpers.cs @@ -10,6 +10,7 @@ using System.Reflection.Metadata; using System.Threading; using Microsoft.CodeAnalysis.CodeGen; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE; using Microsoft.CodeAnalysis.Emit; diff --git a/src/roslyn/src/Compilers/CSharp/Portable/Emitter/Model/AssemblyReference.cs b/src/roslyn/src/Compilers/CSharp/Portable/Emitter/Model/AssemblyReference.cs index 4c682100fcd..067c5910bc0 100644 --- a/src/roslyn/src/Compilers/CSharp/Portable/Emitter/Model/AssemblyReference.cs +++ b/src/roslyn/src/Compilers/CSharp/Portable/Emitter/Model/AssemblyReference.cs @@ -6,11 +6,12 @@ using System; using System.Collections.Generic; +using System.Collections.Immutable; +using System.Diagnostics; using System.Reflection; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.CSharp.Symbols; using Roslyn.Utilities; -using System.Diagnostics; -using System.Collections.Immutable; namespace Microsoft.CodeAnalysis.CSharp.Emit { diff --git a/src/roslyn/src/Compilers/CSharp/Portable/Emitter/Model/FunctionPointerTypeSymbolAdapter.cs b/src/roslyn/src/Compilers/CSharp/Portable/Emitter/Model/FunctionPointerTypeSymbolAdapter.cs index 08765ddc7a0..7bf3c4b7924 100644 --- a/src/roslyn/src/Compilers/CSharp/Portable/Emitter/Model/FunctionPointerTypeSymbolAdapter.cs +++ b/src/roslyn/src/Compilers/CSharp/Portable/Emitter/Model/FunctionPointerTypeSymbolAdapter.cs @@ -7,6 +7,7 @@ using System.Reflection.Metadata; using System.Threading; using Microsoft.Cci; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.Symbols; using Roslyn.Utilities; diff --git a/src/roslyn/src/Compilers/CSharp/Portable/Emitter/Model/ModuleReference.cs b/src/roslyn/src/Compilers/CSharp/Portable/Emitter/Model/ModuleReference.cs index 3feead87fc0..788ee08c2ef 100644 --- a/src/roslyn/src/Compilers/CSharp/Portable/Emitter/Model/ModuleReference.cs +++ b/src/roslyn/src/Compilers/CSharp/Portable/Emitter/Model/ModuleReference.cs @@ -8,6 +8,7 @@ using System.Collections.Immutable; using System.Diagnostics; using System.Reflection; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.Emit; using Roslyn.Utilities; diff --git a/src/roslyn/src/Compilers/CSharp/Portable/Emitter/Model/NamedTypeReference.cs b/src/roslyn/src/Compilers/CSharp/Portable/Emitter/Model/NamedTypeReference.cs index 0636eb1fa96..ec227b7a699 100644 --- a/src/roslyn/src/Compilers/CSharp/Portable/Emitter/Model/NamedTypeReference.cs +++ b/src/roslyn/src/Compilers/CSharp/Portable/Emitter/Model/NamedTypeReference.cs @@ -7,6 +7,7 @@ using System.Collections.Generic; using System.Diagnostics; using System.Reflection.Metadata; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.Emit; using Roslyn.Utilities; diff --git a/src/roslyn/src/Compilers/CSharp/Portable/Emitter/Model/NamedTypeSymbolAdapter.cs b/src/roslyn/src/Compilers/CSharp/Portable/Emitter/Model/NamedTypeSymbolAdapter.cs index 9fb7c177d38..7be1ce2af19 100644 --- a/src/roslyn/src/Compilers/CSharp/Portable/Emitter/Model/NamedTypeSymbolAdapter.cs +++ b/src/roslyn/src/Compilers/CSharp/Portable/Emitter/Model/NamedTypeSymbolAdapter.cs @@ -11,6 +11,7 @@ using System.Reflection.Metadata; using System.Runtime.InteropServices; using Microsoft.Cci; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.CSharp.Emit; using Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE; using Microsoft.CodeAnalysis.Emit; diff --git a/src/roslyn/src/Compilers/CSharp/Portable/Emitter/Model/PEModuleBuilder.cs b/src/roslyn/src/Compilers/CSharp/Portable/Emitter/Model/PEModuleBuilder.cs index 38f5669225f..44178fe8e4c 100644 --- a/src/roslyn/src/Compilers/CSharp/Portable/Emitter/Model/PEModuleBuilder.cs +++ b/src/roslyn/src/Compilers/CSharp/Portable/Emitter/Model/PEModuleBuilder.cs @@ -15,6 +15,7 @@ using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CodeGen; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.PooledObjects; diff --git a/src/roslyn/src/Compilers/CSharp/Portable/Emitter/Model/PENetModuleBuilder.cs b/src/roslyn/src/Compilers/CSharp/Portable/Emitter/Model/PENetModuleBuilder.cs index 576881232a3..f8889a0a0be 100644 --- a/src/roslyn/src/Compilers/CSharp/Portable/Emitter/Model/PENetModuleBuilder.cs +++ b/src/roslyn/src/Compilers/CSharp/Portable/Emitter/Model/PENetModuleBuilder.cs @@ -5,6 +5,7 @@ using System; using System.Collections.Generic; using System.Collections.Immutable; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.PooledObjects; diff --git a/src/roslyn/src/Compilers/CSharp/Portable/Emitter/Model/SymbolAdapter.cs b/src/roslyn/src/Compilers/CSharp/Portable/Emitter/Model/SymbolAdapter.cs index 44b552ef719..07c68572755 100644 --- a/src/roslyn/src/Compilers/CSharp/Portable/Emitter/Model/SymbolAdapter.cs +++ b/src/roslyn/src/Compilers/CSharp/Portable/Emitter/Model/SymbolAdapter.cs @@ -8,6 +8,7 @@ using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.CSharp.Emit; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; diff --git a/src/roslyn/src/Compilers/CSharp/Portable/Emitter/Model/TypeMemberReference.cs b/src/roslyn/src/Compilers/CSharp/Portable/Emitter/Model/TypeMemberReference.cs index e10acefabb9..eda13204ce1 100644 --- a/src/roslyn/src/Compilers/CSharp/Portable/Emitter/Model/TypeMemberReference.cs +++ b/src/roslyn/src/Compilers/CSharp/Portable/Emitter/Model/TypeMemberReference.cs @@ -5,6 +5,7 @@ #nullable disable using System.Collections.Generic; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.Emit; using Roslyn.Utilities; diff --git a/src/roslyn/src/Compilers/CSharp/Portable/Errors/CSDiagnosticInfo.cs b/src/roslyn/src/Compilers/CSharp/Portable/Errors/CSDiagnosticInfo.cs index a55bd7fcd3e..704d7fa78a5 100644 --- a/src/roslyn/src/Compilers/CSharp/Portable/Errors/CSDiagnosticInfo.cs +++ b/src/roslyn/src/Compilers/CSharp/Portable/Errors/CSDiagnosticInfo.cs @@ -8,6 +8,7 @@ using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; +using Microsoft.CodeAnalysis.Collections; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp diff --git a/src/roslyn/src/Compilers/CSharp/Portable/FlowAnalysis/AlwaysAssignedWalker.cs b/src/roslyn/src/Compilers/CSharp/Portable/FlowAnalysis/AlwaysAssignedWalker.cs index d0968cbae14..c562970d33c 100644 --- a/src/roslyn/src/Compilers/CSharp/Portable/FlowAnalysis/AlwaysAssignedWalker.cs +++ b/src/roslyn/src/Compilers/CSharp/Portable/FlowAnalysis/AlwaysAssignedWalker.cs @@ -7,6 +7,7 @@ using System.Collections.Generic; using System.Diagnostics; using System.Linq; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Text; diff --git a/src/roslyn/src/Compilers/CSharp/Portable/FlowAnalysis/EmptyStructTypeCache.cs b/src/roslyn/src/Compilers/CSharp/Portable/FlowAnalysis/EmptyStructTypeCache.cs index ba93a2a6603..7884d845796 100644 --- a/src/roslyn/src/Compilers/CSharp/Portable/FlowAnalysis/EmptyStructTypeCache.cs +++ b/src/roslyn/src/Compilers/CSharp/Portable/FlowAnalysis/EmptyStructTypeCache.cs @@ -6,6 +6,7 @@ using System.Collections.Generic; using System.Diagnostics; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.CSharp.Symbols; using Roslyn.Utilities; diff --git a/src/roslyn/src/Compilers/CSharp/Portable/FlowAnalysis/EntryPointsWalker.cs b/src/roslyn/src/Compilers/CSharp/Portable/FlowAnalysis/EntryPointsWalker.cs index b7ef6b04e09..13ae85db3ca 100644 --- a/src/roslyn/src/Compilers/CSharp/Portable/FlowAnalysis/EntryPointsWalker.cs +++ b/src/roslyn/src/Compilers/CSharp/Portable/FlowAnalysis/EntryPointsWalker.cs @@ -7,6 +7,7 @@ using System.Collections.Generic; using System.Diagnostics; using System.Linq; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Text; diff --git a/src/roslyn/src/Compilers/CSharp/Portable/FlowAnalysis/VariablesDeclaredWalker.cs b/src/roslyn/src/Compilers/CSharp/Portable/FlowAnalysis/VariablesDeclaredWalker.cs index 06a907ec88a..4fbadee5185 100644 --- a/src/roslyn/src/Compilers/CSharp/Portable/FlowAnalysis/VariablesDeclaredWalker.cs +++ b/src/roslyn/src/Compilers/CSharp/Portable/FlowAnalysis/VariablesDeclaredWalker.cs @@ -5,12 +5,13 @@ #nullable disable using System.Collections.Generic; +using System.Diagnostics; using System.Linq; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; -using System.Diagnostics; namespace Microsoft.CodeAnalysis.CSharp { diff --git a/src/roslyn/src/Compilers/CSharp/Portable/Lowering/ClosureConversion/SynthesizedClosureEnvironment.cs b/src/roslyn/src/Compilers/CSharp/Portable/Lowering/ClosureConversion/SynthesizedClosureEnvironment.cs index b7754a59820..c7929635e69 100644 --- a/src/roslyn/src/Compilers/CSharp/Portable/Lowering/ClosureConversion/SynthesizedClosureEnvironment.cs +++ b/src/roslyn/src/Compilers/CSharp/Portable/Lowering/ClosureConversion/SynthesizedClosureEnvironment.cs @@ -8,6 +8,7 @@ using System.Collections.Immutable; using System.Diagnostics; using Microsoft.CodeAnalysis.CodeGen; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.PooledObjects; diff --git a/src/roslyn/src/Compilers/CSharp/Portable/Lowering/LocalRewriter/LocalRewriter.PatternLocalRewriter.cs b/src/roslyn/src/Compilers/CSharp/Portable/Lowering/LocalRewriter/LocalRewriter.PatternLocalRewriter.cs index 56b944a4888..ac58ea84b9d 100644 --- a/src/roslyn/src/Compilers/CSharp/Portable/Lowering/LocalRewriter/LocalRewriter.PatternLocalRewriter.cs +++ b/src/roslyn/src/Compilers/CSharp/Portable/Lowering/LocalRewriter/LocalRewriter.PatternLocalRewriter.cs @@ -152,6 +152,7 @@ protected BoundExpression LowerEvaluation(BoundDagEvaluation evaluation) PropertySymbol property = p.Property; var outputTemp = new BoundDagTemp(p.Syntax, property.Type, p); BoundExpression output = _tempAllocator.GetTemp(outputTemp); + input = _factory.ConvertReceiverForExtensionMemberIfNeeded(property, input); return _factory.AssignmentExpression(output, _localRewriter.MakePropertyAccess(_factory.Syntax, input, property, LookupResultKind.Viable, property.Type, isLeftOfAssignment: false)); } @@ -169,7 +170,7 @@ void addArg(RefKind refKind, BoundExpression expression) Debug.Assert(method.Name == WellKnownMemberNames.DeconstructMethodName); int extensionExtra; - if (method.IsStatic) // Tracked by https://github.com/dotnet/roslyn/issues/76130: Test this code path with new extensions + if (method.IsStatic) { Debug.Assert(method.IsExtensionMethod); receiver = _factory.Type(method.ContainingType); @@ -190,6 +191,7 @@ void addArg(RefKind refKind, BoundExpression expression) addArg(RefKind.Out, _tempAllocator.GetTemp(outputTemp)); } + receiver = _factory.ConvertReceiverForExtensionMemberIfNeeded(method, receiver); return _factory.Call(receiver, method, refKindBuilder.ToImmutableAndFree(), argBuilder.ToImmutableAndFree()); } diff --git a/src/roslyn/src/Compilers/CSharp/Portable/Lowering/LocalRewriter/LocalRewriter_FixedStatement.cs b/src/roslyn/src/Compilers/CSharp/Portable/Lowering/LocalRewriter/LocalRewriter_FixedStatement.cs index 892a1ba24ef..718c3fda82a 100644 --- a/src/roslyn/src/Compilers/CSharp/Portable/Lowering/LocalRewriter/LocalRewriter_FixedStatement.cs +++ b/src/roslyn/src/Compilers/CSharp/Portable/Lowering/LocalRewriter/LocalRewriter_FixedStatement.cs @@ -355,6 +355,7 @@ private BoundStatement InitializeFixedStatementGetPinnable( } // .GetPinnable() + callReceiver = factory.ConvertReceiverForExtensionMemberIfNeeded(getPinnableMethod, callReceiver); var getPinnableCall = getPinnableMethod.IsStatic ? factory.Call(null, getPinnableMethod, callReceiver) : factory.Call(callReceiver, getPinnableMethod); diff --git a/src/roslyn/src/Compilers/CSharp/Portable/Lowering/LocalRewriter/LocalRewriter_ObjectOrCollectionInitializerExpression.cs b/src/roslyn/src/Compilers/CSharp/Portable/Lowering/LocalRewriter/LocalRewriter_ObjectOrCollectionInitializerExpression.cs index ec0cd11e141..da2b10c2df2 100644 --- a/src/roslyn/src/Compilers/CSharp/Portable/Lowering/LocalRewriter/LocalRewriter_ObjectOrCollectionInitializerExpression.cs +++ b/src/roslyn/src/Compilers/CSharp/Portable/Lowering/LocalRewriter/LocalRewriter_ObjectOrCollectionInitializerExpression.cs @@ -698,9 +698,11 @@ private BoundExpression MakeObjectInitializerMemberAccess( #if DEBUG var discardedUseSiteInfo = CompoundUseSiteInfo.Discarded; Debug.Assert(_compilation.Conversions.ClassifyConversionFromType(rewrittenReceiver.Type, memberSymbol.ContainingType, isChecked: false, ref discardedUseSiteInfo).IsImplicit || + (memberSymbol.GetIsNewExtensionMember() && !memberSymbol.IsStatic && ConversionsBase.IsValidExtensionMethodThisArgConversion(_compilation.Conversions.ClassifyConversionFromType(rewrittenReceiver.Type, memberSymbol.ContainingType.ExtensionParameter!.Type, isChecked: false, ref discardedUseSiteInfo))) || _compilation.Conversions.HasImplicitConversionToOrImplementsVarianceCompatibleInterface(rewrittenReceiver.Type, memberSymbol.ContainingType, ref discardedUseSiteInfo, out _)); // It is possible there are use site diagnostics from the above, but none that we need report as we aren't generating code for the conversion #endif + rewrittenReceiver = _factory.ConvertReceiverForExtensionMemberIfNeeded(memberSymbol, rewrittenReceiver); switch (memberSymbol.Kind) { diff --git a/src/roslyn/src/Compilers/CSharp/Portable/Lowering/SynthesizedMethodBaseSymbol.cs b/src/roslyn/src/Compilers/CSharp/Portable/Lowering/SynthesizedMethodBaseSymbol.cs index a796c718606..09f0b8d2868 100644 --- a/src/roslyn/src/Compilers/CSharp/Portable/Lowering/SynthesizedMethodBaseSymbol.cs +++ b/src/roslyn/src/Compilers/CSharp/Portable/Lowering/SynthesizedMethodBaseSymbol.cs @@ -11,6 +11,7 @@ using System.Reflection; using System.Threading; using Microsoft.Cci; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.CSharp.Emit; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; diff --git a/src/roslyn/src/Compilers/CSharp/Portable/Lowering/SyntheticBoundNodeFactory.cs b/src/roslyn/src/Compilers/CSharp/Portable/Lowering/SyntheticBoundNodeFactory.cs index 15748f836eb..72e2a86bf7c 100644 --- a/src/roslyn/src/Compilers/CSharp/Portable/Lowering/SyntheticBoundNodeFactory.cs +++ b/src/roslyn/src/Compilers/CSharp/Portable/Lowering/SyntheticBoundNodeFactory.cs @@ -431,6 +431,24 @@ public BoundExpression AssignmentExpression(BoundExpression left, BoundExpressio return AssignmentExpression(Syntax, left, right, isRef: isRef, wasCompilerGenerated: true); } + public BoundExpression ConvertReceiverForExtensionMemberIfNeeded(Symbol member, BoundExpression receiver) + { + if (member.GetIsNewExtensionMember()) + { + Debug.Assert(!member.IsStatic); + ParameterSymbol? extensionParameter = member.ContainingType.ExtensionParameter; + Debug.Assert(extensionParameter is not null); +#if DEBUG + var discardedUseSiteInfo = CompoundUseSiteInfo.Discarded; + Debug.Assert(Conversions.IsValidExtensionMethodThisArgConversion(this.Compilation.Conversions.ClassifyConversionFromType(receiver.Type, extensionParameter.Type, isChecked: false, ref discardedUseSiteInfo))); +#endif + + return this.Convert(extensionParameter.Type, receiver); + } + + return receiver; + } + /// /// Creates a general assignment that might be instrumented. /// diff --git a/src/roslyn/src/Compilers/CSharp/Portable/SymbolDisplay/SymbolDisplayVisitor_Minimal.cs b/src/roslyn/src/Compilers/CSharp/Portable/SymbolDisplay/SymbolDisplayVisitor_Minimal.cs index 6f1c92c44ad..4df1ce062cf 100644 --- a/src/roslyn/src/Compilers/CSharp/Portable/SymbolDisplay/SymbolDisplayVisitor_Minimal.cs +++ b/src/roslyn/src/Compilers/CSharp/Portable/SymbolDisplay/SymbolDisplayVisitor_Minimal.cs @@ -7,6 +7,7 @@ using System.Diagnostics; using System.Linq; using System.Threading; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; diff --git a/src/roslyn/src/Compilers/CSharp/Portable/Symbols/AnonymousTypes/PublicSymbols/AnonymousManager.TypeOrDelegatePublicSymbol.cs b/src/roslyn/src/Compilers/CSharp/Portable/Symbols/AnonymousTypes/PublicSymbols/AnonymousManager.TypeOrDelegatePublicSymbol.cs index 7a7f6e03314..1faee4ca6cd 100644 --- a/src/roslyn/src/Compilers/CSharp/Portable/Symbols/AnonymousTypes/PublicSymbols/AnonymousManager.TypeOrDelegatePublicSymbol.cs +++ b/src/roslyn/src/Compilers/CSharp/Portable/Symbols/AnonymousTypes/PublicSymbols/AnonymousManager.TypeOrDelegatePublicSymbol.cs @@ -6,6 +6,7 @@ using System.Collections.Generic; using System.Collections.Immutable; using System.Runtime.InteropServices; +using Microsoft.CodeAnalysis.Collections; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Symbols diff --git a/src/roslyn/src/Compilers/CSharp/Portable/Symbols/AnonymousTypes/SynthesizedSymbols/AnonymousType.DelegateTemplateSymbol.cs b/src/roslyn/src/Compilers/CSharp/Portable/Symbols/AnonymousTypes/SynthesizedSymbols/AnonymousType.DelegateTemplateSymbol.cs index 9988175aaa0..5f29d796fec 100644 --- a/src/roslyn/src/Compilers/CSharp/Portable/Symbols/AnonymousTypes/SynthesizedSymbols/AnonymousType.DelegateTemplateSymbol.cs +++ b/src/roslyn/src/Compilers/CSharp/Portable/Symbols/AnonymousTypes/SynthesizedSymbols/AnonymousType.DelegateTemplateSymbol.cs @@ -5,6 +5,7 @@ using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.CSharp.Emit; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; diff --git a/src/roslyn/src/Compilers/CSharp/Portable/Symbols/AnonymousTypes/SynthesizedSymbols/AnonymousType.TypeOrDelegateTemplateSymbol.cs b/src/roslyn/src/Compilers/CSharp/Portable/Symbols/AnonymousTypes/SynthesizedSymbols/AnonymousType.TypeOrDelegateTemplateSymbol.cs index 2d5944bc713..c8041fcc68a 100644 --- a/src/roslyn/src/Compilers/CSharp/Portable/Symbols/AnonymousTypes/SynthesizedSymbols/AnonymousType.TypeOrDelegateTemplateSymbol.cs +++ b/src/roslyn/src/Compilers/CSharp/Portable/Symbols/AnonymousTypes/SynthesizedSymbols/AnonymousType.TypeOrDelegateTemplateSymbol.cs @@ -8,6 +8,7 @@ using System.Diagnostics; using System.Runtime.InteropServices; using System.Threading; +using Microsoft.CodeAnalysis.Collections; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Symbols diff --git a/src/roslyn/src/Compilers/CSharp/Portable/Symbols/ArrayTypeSymbol.cs b/src/roslyn/src/Compilers/CSharp/Portable/Symbols/ArrayTypeSymbol.cs index 572ee0cc344..0ad5f45886c 100644 --- a/src/roslyn/src/Compilers/CSharp/Portable/Symbols/ArrayTypeSymbol.cs +++ b/src/roslyn/src/Compilers/CSharp/Portable/Symbols/ArrayTypeSymbol.cs @@ -8,6 +8,7 @@ using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Symbols; using Roslyn.Utilities; diff --git a/src/roslyn/src/Compilers/CSharp/Portable/Symbols/DynamicTypeSymbol.cs b/src/roslyn/src/Compilers/CSharp/Portable/Symbols/DynamicTypeSymbol.cs index 305545280cf..c88106e235d 100644 --- a/src/roslyn/src/Compilers/CSharp/Portable/Symbols/DynamicTypeSymbol.cs +++ b/src/roslyn/src/Compilers/CSharp/Portable/Symbols/DynamicTypeSymbol.cs @@ -6,6 +6,7 @@ using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; diff --git a/src/roslyn/src/Compilers/CSharp/Portable/Symbols/ErrorTypeSymbol.cs b/src/roslyn/src/Compilers/CSharp/Portable/Symbols/ErrorTypeSymbol.cs index e1ce775921f..bc35c827607 100644 --- a/src/roslyn/src/Compilers/CSharp/Portable/Symbols/ErrorTypeSymbol.cs +++ b/src/roslyn/src/Compilers/CSharp/Portable/Symbols/ErrorTypeSymbol.cs @@ -7,6 +7,7 @@ using System.Collections.Immutable; using System.Diagnostics; using System.Runtime.InteropServices; +using Microsoft.CodeAnalysis.Collections; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Symbols diff --git a/src/roslyn/src/Compilers/CSharp/Portable/Symbols/FunctionPointers/FunctionPointerTypeSymbol.cs b/src/roslyn/src/Compilers/CSharp/Portable/Symbols/FunctionPointers/FunctionPointerTypeSymbol.cs index 0af58ff20b8..5a595ddcecf 100644 --- a/src/roslyn/src/Compilers/CSharp/Portable/Symbols/FunctionPointers/FunctionPointerTypeSymbol.cs +++ b/src/roslyn/src/Compilers/CSharp/Portable/Symbols/FunctionPointers/FunctionPointerTypeSymbol.cs @@ -7,6 +7,7 @@ using System.Collections.Immutable; using System.Diagnostics; using Microsoft.Cci; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; diff --git a/src/roslyn/src/Compilers/CSharp/Portable/Symbols/Metadata/PE/PEGlobalNamespaceSymbol.cs b/src/roslyn/src/Compilers/CSharp/Portable/Symbols/Metadata/PE/PEGlobalNamespaceSymbol.cs index 05500ca014e..546018c6523 100644 --- a/src/roslyn/src/Compilers/CSharp/Portable/Symbols/Metadata/PE/PEGlobalNamespaceSymbol.cs +++ b/src/roslyn/src/Compilers/CSharp/Portable/Symbols/Metadata/PE/PEGlobalNamespaceSymbol.cs @@ -4,16 +4,17 @@ #nullable disable -using Microsoft.CodeAnalysis.CSharp.Symbols; -using Microsoft.CodeAnalysis.CSharp.Syntax; -using Microsoft.CodeAnalysis.Text; -using Roslyn.Utilities; +using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Reflection.Metadata; -using System; using System.Threading; +using Microsoft.CodeAnalysis.Collections; +using Microsoft.CodeAnalysis.CSharp.Symbols; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.CodeAnalysis.Text; +using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE { diff --git a/src/roslyn/src/Compilers/CSharp/Portable/Symbols/MissingAssemblySymbol.cs b/src/roslyn/src/Compilers/CSharp/Portable/Symbols/MissingAssemblySymbol.cs index 91cb0f329d3..1c1c488965e 100644 --- a/src/roslyn/src/Compilers/CSharp/Portable/Symbols/MissingAssemblySymbol.cs +++ b/src/roslyn/src/Compilers/CSharp/Portable/Symbols/MissingAssemblySymbol.cs @@ -10,6 +10,7 @@ using System.Collections.ObjectModel; using System.Diagnostics; using System.Threading; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Text; diff --git a/src/roslyn/src/Compilers/CSharp/Portable/Symbols/MissingModuleSymbol.cs b/src/roslyn/src/Compilers/CSharp/Portable/Symbols/MissingModuleSymbol.cs index 4154d729b90..e5ded01c4a2 100644 --- a/src/roslyn/src/Compilers/CSharp/Portable/Symbols/MissingModuleSymbol.cs +++ b/src/roslyn/src/Compilers/CSharp/Portable/Symbols/MissingModuleSymbol.cs @@ -10,6 +10,7 @@ using System.Diagnostics; using System.Reflection.PortableExecutable; using System.Runtime.InteropServices; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Text; diff --git a/src/roslyn/src/Compilers/CSharp/Portable/Symbols/NamespaceOrTypeSymbol.cs b/src/roslyn/src/Compilers/CSharp/Portable/Symbols/NamespaceOrTypeSymbol.cs index 10ec3093df8..23a25f694e8 100644 --- a/src/roslyn/src/Compilers/CSharp/Portable/Symbols/NamespaceOrTypeSymbol.cs +++ b/src/roslyn/src/Compilers/CSharp/Portable/Symbols/NamespaceOrTypeSymbol.cs @@ -7,6 +7,7 @@ using System.Collections.Immutable; using System.Diagnostics; using System.Linq; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Symbols; diff --git a/src/roslyn/src/Compilers/CSharp/Portable/Symbols/NativeIntegerTypeSymbol.cs b/src/roslyn/src/Compilers/CSharp/Portable/Symbols/NativeIntegerTypeSymbol.cs index 1364dedfc3c..f736683de14 100644 --- a/src/roslyn/src/Compilers/CSharp/Portable/Symbols/NativeIntegerTypeSymbol.cs +++ b/src/roslyn/src/Compilers/CSharp/Portable/Symbols/NativeIntegerTypeSymbol.cs @@ -8,6 +8,7 @@ using System.Diagnostics; using System.Linq; using System.Threading; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; diff --git a/src/roslyn/src/Compilers/CSharp/Portable/Symbols/PointerTypeSymbol.cs b/src/roslyn/src/Compilers/CSharp/Portable/Symbols/PointerTypeSymbol.cs index 11cd05b0834..8a19a720f6d 100644 --- a/src/roslyn/src/Compilers/CSharp/Portable/Symbols/PointerTypeSymbol.cs +++ b/src/roslyn/src/Compilers/CSharp/Portable/Symbols/PointerTypeSymbol.cs @@ -5,9 +5,10 @@ using System; using System.Collections.Generic; using System.Collections.Immutable; -using Roslyn.Utilities; using System.Diagnostics; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.PooledObjects; +using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Symbols { diff --git a/src/roslyn/src/Compilers/CSharp/Portable/Symbols/PropertyOrEventSymbolExtensions.cs b/src/roslyn/src/Compilers/CSharp/Portable/Symbols/PropertyOrEventSymbolExtensions.cs index f692fb763a0..6671fc0a0d9 100644 --- a/src/roslyn/src/Compilers/CSharp/Portable/Symbols/PropertyOrEventSymbolExtensions.cs +++ b/src/roslyn/src/Compilers/CSharp/Portable/Symbols/PropertyOrEventSymbolExtensions.cs @@ -6,6 +6,7 @@ using System.Collections.Generic; using System.Collections.Immutable; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Text; diff --git a/src/roslyn/src/Compilers/CSharp/Portable/Symbols/Source/SourceAssemblySymbol.cs b/src/roslyn/src/Compilers/CSharp/Portable/Symbols/Source/SourceAssemblySymbol.cs index 90d064f042a..629b285bde5 100644 --- a/src/roslyn/src/Compilers/CSharp/Portable/Symbols/Source/SourceAssemblySymbol.cs +++ b/src/roslyn/src/Compilers/CSharp/Portable/Symbols/Source/SourceAssemblySymbol.cs @@ -12,6 +12,7 @@ using System.Linq; using System.Reflection; using System.Threading; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.CSharp.Emit; using Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE; using Microsoft.CodeAnalysis.CSharp.Syntax; diff --git a/src/roslyn/src/Compilers/CSharp/Portable/Symbols/Source/SourceFixedFieldSymbol.cs b/src/roslyn/src/Compilers/CSharp/Portable/Symbols/Source/SourceFixedFieldSymbol.cs index 16402ae80cc..5c1e3e3e790 100644 --- a/src/roslyn/src/Compilers/CSharp/Portable/Symbols/Source/SourceFixedFieldSymbol.cs +++ b/src/roslyn/src/Compilers/CSharp/Portable/Symbols/Source/SourceFixedFieldSymbol.cs @@ -10,6 +10,7 @@ using System.Diagnostics; using System.Runtime.InteropServices; using System.Threading; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.CSharp.Emit; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; diff --git a/src/roslyn/src/Compilers/CSharp/Portable/Symbols/Source/SourceMethodSymbolWithAttributes.cs b/src/roslyn/src/Compilers/CSharp/Portable/Symbols/Source/SourceMethodSymbolWithAttributes.cs index 39cd11f8b51..740883fe346 100644 --- a/src/roslyn/src/Compilers/CSharp/Portable/Symbols/Source/SourceMethodSymbolWithAttributes.cs +++ b/src/roslyn/src/Compilers/CSharp/Portable/Symbols/Source/SourceMethodSymbolWithAttributes.cs @@ -14,6 +14,7 @@ using System.Text; using System.Threading; using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Collections; diff --git a/src/roslyn/src/Compilers/CSharp/Portable/Symbols/Synthesized/ReadOnlyListType/SynthesizedReadOnlyListEnumeratorTypeSymbol.cs b/src/roslyn/src/Compilers/CSharp/Portable/Symbols/Synthesized/ReadOnlyListType/SynthesizedReadOnlyListEnumeratorTypeSymbol.cs index 0d6a1dd0e47..10585d9c9d7 100644 --- a/src/roslyn/src/Compilers/CSharp/Portable/Symbols/Synthesized/ReadOnlyListType/SynthesizedReadOnlyListEnumeratorTypeSymbol.cs +++ b/src/roslyn/src/Compilers/CSharp/Portable/Symbols/Synthesized/ReadOnlyListType/SynthesizedReadOnlyListEnumeratorTypeSymbol.cs @@ -8,6 +8,7 @@ using System.Diagnostics; using System.Linq; using System.Runtime.InteropServices; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; diff --git a/src/roslyn/src/Compilers/CSharp/Portable/Symbols/Synthesized/ReadOnlyListType/SynthesizedReadOnlyListTypeSymbol.cs b/src/roslyn/src/Compilers/CSharp/Portable/Symbols/Synthesized/ReadOnlyListType/SynthesizedReadOnlyListTypeSymbol.cs index 7d1c4d80cfd..53039024f9c 100644 --- a/src/roslyn/src/Compilers/CSharp/Portable/Symbols/Synthesized/ReadOnlyListType/SynthesizedReadOnlyListTypeSymbol.cs +++ b/src/roslyn/src/Compilers/CSharp/Portable/Symbols/Synthesized/ReadOnlyListType/SynthesizedReadOnlyListTypeSymbol.cs @@ -8,6 +8,7 @@ using System.Diagnostics; using System.Linq; using System.Runtime.InteropServices; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.CSharp.Emit; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; diff --git a/src/roslyn/src/Compilers/CSharp/Portable/Symbols/Synthesized/Records/SynthesizedPrimaryConstructor.cs b/src/roslyn/src/Compilers/CSharp/Portable/Symbols/Synthesized/Records/SynthesizedPrimaryConstructor.cs index 965d2db9659..11062737533 100644 --- a/src/roslyn/src/Compilers/CSharp/Portable/Symbols/Synthesized/Records/SynthesizedPrimaryConstructor.cs +++ b/src/roslyn/src/Compilers/CSharp/Portable/Symbols/Synthesized/Records/SynthesizedPrimaryConstructor.cs @@ -7,6 +7,7 @@ using System.Diagnostics; using System.Linq; using System.Threading; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.CSharp.Syntax; using Roslyn.Utilities; diff --git a/src/roslyn/src/Compilers/CSharp/Portable/Symbols/Synthesized/SynthesizedContainer.cs b/src/roslyn/src/Compilers/CSharp/Portable/Symbols/Synthesized/SynthesizedContainer.cs index f4582d2a201..777c42eff8b 100644 --- a/src/roslyn/src/Compilers/CSharp/Portable/Symbols/Synthesized/SynthesizedContainer.cs +++ b/src/roslyn/src/Compilers/CSharp/Portable/Symbols/Synthesized/SynthesizedContainer.cs @@ -9,8 +9,9 @@ using System.Collections.Immutable; using System.Diagnostics; using System.Runtime.InteropServices; -using Microsoft.CodeAnalysis.PooledObjects; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.CSharp.Emit; +using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Symbols diff --git a/src/roslyn/src/Compilers/CSharp/Portable/Symbols/Synthesized/SynthesizedEmbeddedAttributeSymbol.cs b/src/roslyn/src/Compilers/CSharp/Portable/Symbols/Synthesized/SynthesizedEmbeddedAttributeSymbol.cs index c57954b8425..12a5391732c 100644 --- a/src/roslyn/src/Compilers/CSharp/Portable/Symbols/Synthesized/SynthesizedEmbeddedAttributeSymbol.cs +++ b/src/roslyn/src/Compilers/CSharp/Portable/Symbols/Synthesized/SynthesizedEmbeddedAttributeSymbol.cs @@ -4,16 +4,17 @@ #nullable disable -using Microsoft.Cci; -using Roslyn.Utilities; using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; -using System.Runtime.InteropServices; using System.Linq; +using System.Runtime.InteropServices; +using Microsoft.Cci; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.CSharp.Emit; using Microsoft.CodeAnalysis.PooledObjects; +using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Symbols { diff --git a/src/roslyn/src/Compilers/CSharp/Portable/Symbols/Synthesized/SynthesizedInlineArrayTypeSymbol.cs b/src/roslyn/src/Compilers/CSharp/Portable/Symbols/Synthesized/SynthesizedInlineArrayTypeSymbol.cs index 317f919c9ba..54d00df7b3b 100644 --- a/src/roslyn/src/Compilers/CSharp/Portable/Symbols/Synthesized/SynthesizedInlineArrayTypeSymbol.cs +++ b/src/roslyn/src/Compilers/CSharp/Portable/Symbols/Synthesized/SynthesizedInlineArrayTypeSymbol.cs @@ -7,6 +7,7 @@ using System.Collections.Immutable; using System.Diagnostics; using System.Runtime.InteropServices; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.CSharp.Emit; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; diff --git a/src/roslyn/src/Compilers/CSharp/Portable/Symbols/Synthesized/SynthesizedIntrinsicOperatorSymbol.cs b/src/roslyn/src/Compilers/CSharp/Portable/Symbols/Synthesized/SynthesizedIntrinsicOperatorSymbol.cs index 3c3fe92963a..12ec047f2ef 100644 --- a/src/roslyn/src/Compilers/CSharp/Portable/Symbols/Synthesized/SynthesizedIntrinsicOperatorSymbol.cs +++ b/src/roslyn/src/Compilers/CSharp/Portable/Symbols/Synthesized/SynthesizedIntrinsicOperatorSymbol.cs @@ -4,11 +4,12 @@ #nullable disable +using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; +using Microsoft.CodeAnalysis.Collections; using Roslyn.Utilities; -using System; namespace Microsoft.CodeAnalysis.CSharp.Symbols { diff --git a/src/roslyn/src/Compilers/CSharp/Portable/Symbols/Synthesized/SynthesizedPrivateImplementationDetailsType.cs b/src/roslyn/src/Compilers/CSharp/Portable/Symbols/Synthesized/SynthesizedPrivateImplementationDetailsType.cs index e207f611093..0fec97a2b57 100644 --- a/src/roslyn/src/Compilers/CSharp/Portable/Symbols/Synthesized/SynthesizedPrivateImplementationDetailsType.cs +++ b/src/roslyn/src/Compilers/CSharp/Portable/Symbols/Synthesized/SynthesizedPrivateImplementationDetailsType.cs @@ -9,6 +9,7 @@ using System.Runtime.InteropServices; using Microsoft.Cci; using Microsoft.CodeAnalysis.CodeGen; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.Symbols; using Roslyn.Utilities; diff --git a/src/roslyn/src/Compilers/CSharp/Portable/Symbols/TypeParameterSymbol.cs b/src/roslyn/src/Compilers/CSharp/Portable/Symbols/TypeParameterSymbol.cs index 57ed680f453..ae94e980832 100644 --- a/src/roslyn/src/Compilers/CSharp/Portable/Symbols/TypeParameterSymbol.cs +++ b/src/roslyn/src/Compilers/CSharp/Portable/Symbols/TypeParameterSymbol.cs @@ -8,6 +8,7 @@ using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Symbols; using Roslyn.Utilities; diff --git a/src/roslyn/src/Compilers/CSharp/Portable/Syntax/CSharpSyntaxTree.cs b/src/roslyn/src/Compilers/CSharp/Portable/Syntax/CSharpSyntaxTree.cs index d9563546a49..c7c3d656049 100644 --- a/src/roslyn/src/Compilers/CSharp/Portable/Syntax/CSharpSyntaxTree.cs +++ b/src/roslyn/src/Compilers/CSharp/Portable/Syntax/CSharpSyntaxTree.cs @@ -13,6 +13,7 @@ using System.Text; using System.Threading; using System.Threading.Tasks; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Text; diff --git a/src/roslyn/src/Compilers/CSharp/Portable/Syntax/CompilationUnitSyntax.cs b/src/roslyn/src/Compilers/CSharp/Portable/Syntax/CompilationUnitSyntax.cs index e3bc236f583..726e2702ce4 100644 --- a/src/roslyn/src/Compilers/CSharp/Portable/Syntax/CompilationUnitSyntax.cs +++ b/src/roslyn/src/Compilers/CSharp/Portable/Syntax/CompilationUnitSyntax.cs @@ -4,6 +4,7 @@ using System; using System.Collections.Generic; +using Microsoft.CodeAnalysis.Collections; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Syntax diff --git a/src/roslyn/src/Compilers/CSharp/Portable/Syntax/InternalSyntax/CSharpSyntaxNode.cs b/src/roslyn/src/Compilers/CSharp/Portable/Syntax/InternalSyntax/CSharpSyntaxNode.cs index 39479fcba12..5fcbbead083 100644 --- a/src/roslyn/src/Compilers/CSharp/Portable/Syntax/InternalSyntax/CSharpSyntaxNode.cs +++ b/src/roslyn/src/Compilers/CSharp/Portable/Syntax/InternalSyntax/CSharpSyntaxNode.cs @@ -9,6 +9,7 @@ using System.Diagnostics; using System.Linq; using System.Runtime.CompilerServices; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.Syntax.InternalSyntax; using Roslyn.Utilities; diff --git a/src/roslyn/src/Compilers/CSharp/Portable/xlf/CSharpResources.cs.xlf b/src/roslyn/src/Compilers/CSharp/Portable/xlf/CSharpResources.cs.xlf index 37ae8bfc426..164941bfe1c 100644 --- a/src/roslyn/src/Compilers/CSharp/Portable/xlf/CSharpResources.cs.xlf +++ b/src/roslyn/src/Compilers/CSharp/Portable/xlf/CSharpResources.cs.xlf @@ -6009,8 +6009,8 @@ - Inconsistent accessibility: parameter type '{1}' is less accessible than indexer '{0}' - Nekonzistentní dostupnost: Typ parametru {1} je míň dostupný než indexer {0}. + Inconsistent accessibility: parameter type '{1}' is less accessible than indexer or property '{0}' + Nekonzistentní dostupnost: Typ parametru {1} je míň dostupný než indexer {0}. diff --git a/src/roslyn/src/Compilers/CSharp/Portable/xlf/CSharpResources.de.xlf b/src/roslyn/src/Compilers/CSharp/Portable/xlf/CSharpResources.de.xlf index e481e2a7893..2cfd37350a1 100644 --- a/src/roslyn/src/Compilers/CSharp/Portable/xlf/CSharpResources.de.xlf +++ b/src/roslyn/src/Compilers/CSharp/Portable/xlf/CSharpResources.de.xlf @@ -6009,8 +6009,8 @@ - Inconsistent accessibility: parameter type '{1}' is less accessible than indexer '{0}' - Inkonsistenter Zugriff: Parametertyp "{1}" ist weniger zugreifbar als Indexer "{0}". + Inconsistent accessibility: parameter type '{1}' is less accessible than indexer or property '{0}' + Inkonsistenter Zugriff: Parametertyp "{1}" ist weniger zugreifbar als Indexer "{0}". diff --git a/src/roslyn/src/Compilers/CSharp/Portable/xlf/CSharpResources.es.xlf b/src/roslyn/src/Compilers/CSharp/Portable/xlf/CSharpResources.es.xlf index 3dcae73e93f..5b904b8347d 100644 --- a/src/roslyn/src/Compilers/CSharp/Portable/xlf/CSharpResources.es.xlf +++ b/src/roslyn/src/Compilers/CSharp/Portable/xlf/CSharpResources.es.xlf @@ -6009,8 +6009,8 @@ - Inconsistent accessibility: parameter type '{1}' is less accessible than indexer '{0}' - Incoherencia de accesibilidad: el tipo de parámetro '{1}' es menos accesible que el indizador '{0}' + Inconsistent accessibility: parameter type '{1}' is less accessible than indexer or property '{0}' + Incoherencia de accesibilidad: el tipo de parámetro '{1}' es menos accesible que el indizador '{0}' diff --git a/src/roslyn/src/Compilers/CSharp/Portable/xlf/CSharpResources.fr.xlf b/src/roslyn/src/Compilers/CSharp/Portable/xlf/CSharpResources.fr.xlf index 73299c0f677..3643165b3ae 100644 --- a/src/roslyn/src/Compilers/CSharp/Portable/xlf/CSharpResources.fr.xlf +++ b/src/roslyn/src/Compilers/CSharp/Portable/xlf/CSharpResources.fr.xlf @@ -6009,8 +6009,8 @@ - Inconsistent accessibility: parameter type '{1}' is less accessible than indexer '{0}' - Accessibilité incohérente : le type de paramètre '{1}' est moins accessible que l'indexeur '{0}' + Inconsistent accessibility: parameter type '{1}' is less accessible than indexer or property '{0}' + Accessibilité incohérente : le type de paramètre '{1}' est moins accessible que l'indexeur '{0}' diff --git a/src/roslyn/src/Compilers/CSharp/Portable/xlf/CSharpResources.it.xlf b/src/roslyn/src/Compilers/CSharp/Portable/xlf/CSharpResources.it.xlf index ca9c6d18326..8f62ff52a10 100644 --- a/src/roslyn/src/Compilers/CSharp/Portable/xlf/CSharpResources.it.xlf +++ b/src/roslyn/src/Compilers/CSharp/Portable/xlf/CSharpResources.it.xlf @@ -6009,8 +6009,8 @@ target:module Compila un modulo che può essere aggiunto ad altro - Inconsistent accessibility: parameter type '{1}' is less accessible than indexer '{0}' - Accessibilità incoerente: il tipo parametro '{1}' è meno accessibile dell'indicizzatore '{0}' + Inconsistent accessibility: parameter type '{1}' is less accessible than indexer or property '{0}' + Accessibilità incoerente: il tipo parametro '{1}' è meno accessibile dell'indicizzatore '{0}' diff --git a/src/roslyn/src/Compilers/CSharp/Portable/xlf/CSharpResources.ja.xlf b/src/roslyn/src/Compilers/CSharp/Portable/xlf/CSharpResources.ja.xlf index 64ffd6274ee..af9147be028 100644 --- a/src/roslyn/src/Compilers/CSharp/Portable/xlf/CSharpResources.ja.xlf +++ b/src/roslyn/src/Compilers/CSharp/Portable/xlf/CSharpResources.ja.xlf @@ -6009,8 +6009,8 @@ - Inconsistent accessibility: parameter type '{1}' is less accessible than indexer '{0}' - アクセシビリティに一貫性がありません。パラメーター型 '{1}' のアクセシビリティはインデクサー '{0}' よりも低く設定されています + Inconsistent accessibility: parameter type '{1}' is less accessible than indexer or property '{0}' + アクセシビリティに一貫性がありません。パラメーター型 '{1}' のアクセシビリティはインデクサー '{0}' よりも低く設定されています diff --git a/src/roslyn/src/Compilers/CSharp/Portable/xlf/CSharpResources.ko.xlf b/src/roslyn/src/Compilers/CSharp/Portable/xlf/CSharpResources.ko.xlf index 7c16a674e24..8f1588fb754 100644 --- a/src/roslyn/src/Compilers/CSharp/Portable/xlf/CSharpResources.ko.xlf +++ b/src/roslyn/src/Compilers/CSharp/Portable/xlf/CSharpResources.ko.xlf @@ -6009,8 +6009,8 @@ - Inconsistent accessibility: parameter type '{1}' is less accessible than indexer '{0}' - 일관성 없는 액세스 가능성: '{1}' 매개 변수 형식이 '{0}' 인덱서보다 액세스하기 어렵습니다. + Inconsistent accessibility: parameter type '{1}' is less accessible than indexer or property '{0}' + 일관성 없는 액세스 가능성: '{1}' 매개 변수 형식이 '{0}' 인덱서보다 액세스하기 어렵습니다. diff --git a/src/roslyn/src/Compilers/CSharp/Portable/xlf/CSharpResources.pl.xlf b/src/roslyn/src/Compilers/CSharp/Portable/xlf/CSharpResources.pl.xlf index 40a51a9d7ab..8a892cfd63d 100644 --- a/src/roslyn/src/Compilers/CSharp/Portable/xlf/CSharpResources.pl.xlf +++ b/src/roslyn/src/Compilers/CSharp/Portable/xlf/CSharpResources.pl.xlf @@ -6009,8 +6009,8 @@ - Inconsistent accessibility: parameter type '{1}' is less accessible than indexer '{0}' - Niespójność dostępności: typ parametru „{1}” jest mniej dostępny niż indeksator „{0}” + Inconsistent accessibility: parameter type '{1}' is less accessible than indexer or property '{0}' + Niespójność dostępności: typ parametru „{1}” jest mniej dostępny niż indeksator „{0}” diff --git a/src/roslyn/src/Compilers/CSharp/Portable/xlf/CSharpResources.pt-BR.xlf b/src/roslyn/src/Compilers/CSharp/Portable/xlf/CSharpResources.pt-BR.xlf index 133576185f6..827cc499e67 100644 --- a/src/roslyn/src/Compilers/CSharp/Portable/xlf/CSharpResources.pt-BR.xlf +++ b/src/roslyn/src/Compilers/CSharp/Portable/xlf/CSharpResources.pt-BR.xlf @@ -6009,8 +6009,8 @@ - Inconsistent accessibility: parameter type '{1}' is less accessible than indexer '{0}' - Acessibilidade inconsistente: tipo de parâmetro "{1}" é menos acessível do que o indexador "{0}" + Inconsistent accessibility: parameter type '{1}' is less accessible than indexer or property '{0}' + Acessibilidade inconsistente: tipo de parâmetro "{1}" é menos acessível do que o indexador "{0}" diff --git a/src/roslyn/src/Compilers/CSharp/Portable/xlf/CSharpResources.ru.xlf b/src/roslyn/src/Compilers/CSharp/Portable/xlf/CSharpResources.ru.xlf index 30b7d953160..7488a8c4a28 100644 --- a/src/roslyn/src/Compilers/CSharp/Portable/xlf/CSharpResources.ru.xlf +++ b/src/roslyn/src/Compilers/CSharp/Portable/xlf/CSharpResources.ru.xlf @@ -6010,8 +6010,8 @@ - Inconsistent accessibility: parameter type '{1}' is less accessible than indexer '{0}' - Несогласованность по доступности: доступность типа параметра "{1}" ниже доступности индексатора "{0}" + Inconsistent accessibility: parameter type '{1}' is less accessible than indexer or property '{0}' + Несогласованность по доступности: доступность типа параметра "{1}" ниже доступности индексатора "{0}" diff --git a/src/roslyn/src/Compilers/CSharp/Portable/xlf/CSharpResources.tr.xlf b/src/roslyn/src/Compilers/CSharp/Portable/xlf/CSharpResources.tr.xlf index 2c46ca1dae0..1e55e37679f 100644 --- a/src/roslyn/src/Compilers/CSharp/Portable/xlf/CSharpResources.tr.xlf +++ b/src/roslyn/src/Compilers/CSharp/Portable/xlf/CSharpResources.tr.xlf @@ -6009,8 +6009,8 @@ - Inconsistent accessibility: parameter type '{1}' is less accessible than indexer '{0}' - Tutarsız erişilebilirlik: '{1}' parametre türü, '{0}' dizin oluşturucusundan daha az erişilebilir + Inconsistent accessibility: parameter type '{1}' is less accessible than indexer or property '{0}' + Tutarsız erişilebilirlik: '{1}' parametre türü, '{0}' dizin oluşturucusundan daha az erişilebilir diff --git a/src/roslyn/src/Compilers/CSharp/Portable/xlf/CSharpResources.zh-Hans.xlf b/src/roslyn/src/Compilers/CSharp/Portable/xlf/CSharpResources.zh-Hans.xlf index 8ca0b9a047b..d205367c9b8 100644 --- a/src/roslyn/src/Compilers/CSharp/Portable/xlf/CSharpResources.zh-Hans.xlf +++ b/src/roslyn/src/Compilers/CSharp/Portable/xlf/CSharpResources.zh-Hans.xlf @@ -6009,8 +6009,8 @@ - Inconsistent accessibility: parameter type '{1}' is less accessible than indexer '{0}' - 可访问性不一致: 参数类型“{1}”的可访问性低于索引器“{0}” + Inconsistent accessibility: parameter type '{1}' is less accessible than indexer or property '{0}' + 可访问性不一致: 参数类型“{1}”的可访问性低于索引器“{0}” diff --git a/src/roslyn/src/Compilers/CSharp/Portable/xlf/CSharpResources.zh-Hant.xlf b/src/roslyn/src/Compilers/CSharp/Portable/xlf/CSharpResources.zh-Hant.xlf index 04b102802f3..fa2ad94a245 100644 --- a/src/roslyn/src/Compilers/CSharp/Portable/xlf/CSharpResources.zh-Hant.xlf +++ b/src/roslyn/src/Compilers/CSharp/Portable/xlf/CSharpResources.zh-Hant.xlf @@ -6009,8 +6009,8 @@ strument:TestCoverage 產生檢測要收集 - Inconsistent accessibility: parameter type '{1}' is less accessible than indexer '{0}' - 不一致的存取範圍: 參數類型 '{1}' 比索引子 '{0}' 的存取範圍小 + Inconsistent accessibility: parameter type '{1}' is less accessible than indexer or property '{0}' + 不一致的存取範圍: 參數類型 '{1}' 比索引子 '{0}' 的存取範圍小 diff --git a/src/roslyn/src/Compilers/CSharp/Test/CommandLine/CommandLineTests.cs b/src/roslyn/src/Compilers/CSharp/Test/CommandLine/CommandLineTests.cs index f67a433d908..8b56952f07c 100644 --- a/src/roslyn/src/Compilers/CSharp/Test/CommandLine/CommandLineTests.cs +++ b/src/roslyn/src/Compilers/CSharp/Test/CommandLine/CommandLineTests.cs @@ -8,6 +8,7 @@ using System.Collections.Generic; using System.Collections.Immutable; using System.ComponentModel; +using System.Diagnostics; using System.Globalization; using System.IO; using System.IO.MemoryMappedFiles; @@ -20,7 +21,9 @@ using System.Text; using System.Text.RegularExpressions; using System.Threading; +using Basic.Reference.Assemblies; using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Diagnostics; @@ -35,10 +38,8 @@ using Roslyn.Utilities; using TestResources.Analyzers; using Xunit; -using Basic.Reference.Assemblies; using static Microsoft.CodeAnalysis.CommonDiagnosticAnalyzers; using static Roslyn.Test.Utilities.SharedResourceHelpers; -using System.Diagnostics; namespace Microsoft.CodeAnalysis.CSharp.CommandLine.UnitTests { diff --git a/src/roslyn/src/Compilers/CSharp/Test/Emit/CodeGen/CodeGenExprLambdaTests.cs b/src/roslyn/src/Compilers/CSharp/Test/Emit/CodeGen/CodeGenExprLambdaTests.cs index a79f04945d6..0e748539c83 100644 --- a/src/roslyn/src/Compilers/CSharp/Test/Emit/CodeGen/CodeGenExprLambdaTests.cs +++ b/src/roslyn/src/Compilers/CSharp/Test/Emit/CodeGen/CodeGenExprLambdaTests.cs @@ -30,362 +30,6 @@ protected CompilationVerifier CompileAndVerifyUtil( /// protected static MetadataReference ExpressionAssemblyRef => SystemCoreRef_v46; - #region A string containing expression-tree dumping utilities - private const string ExpressionTestLibrary = @" -using System; -using System.Globalization; -using System.Linq.Expressions; -using System.Text; - -public class TestBase -{ - protected static void DCheck(Expression e, string expected) { Check(e.Dump(), expected); } - protected static void Check(Expression> e, string expected) { Check(e.Dump(), expected); } - protected static void Check(Expression> e, string expected) { Check(e.Dump(), expected); } - protected static void Check(Expression> e, string expected) { Check(e.Dump(), expected); } - protected static void Check(Expression> e, string expected) { Check(e.Dump(), expected); } - protected static string ToString(Expression> e) { return e.Dump(); } - protected static string ToString(Expression> e) { return e.Dump(); } - protected static string ToString(Expression> e) { return e.Dump(); } - private static void Check(string actual, string expected) - { - if (expected != actual) - { - Console.WriteLine(""FAIL""); - Console.WriteLine(""expected: "" + expected); - Console.WriteLine(""actual: "" + actual); -// throw new Exception(""expected='"" + expected + ""'; actual='"" + actual + ""'""); - } - } -} - -public static class ExpressionExtensions -{ - public static string Dump(this Expression self) - { - return ExpressionPrinter.Print(self.Body); - } -} - -class ExpressionPrinter : System.Linq.Expressions.ExpressionVisitor -{ - private StringBuilder s = new StringBuilder(); - - public static string Print(Expression e) - { - var p = new ExpressionPrinter(); - p.Visit(e); - return p.s.ToString(); - } - - public override Expression Visit(Expression node) - { - if (node == null) { s.Append(""null""); return null; } - s.Append(node.NodeType.ToString()); - s.Append(""(""); - base.Visit(node); - s.Append("" Type:"" + node.Type); - s.Append("")""); - return null; - } - - protected override MemberBinding VisitMemberBinding(MemberBinding node) - { - if (node == null) { s.Append(""null""); return null; } - return base.VisitMemberBinding(node); - } - - protected override MemberMemberBinding VisitMemberMemberBinding(MemberMemberBinding node) - { - s.Append(""MemberMemberBinding(Member=""); - s.Append(node.Member.ToString()); - foreach (var b in node.Bindings) - { - s.Append("" ""); - VisitMemberBinding(b); - } - s.Append("")""); - return null; - } - - protected override MemberListBinding VisitMemberListBinding(MemberListBinding node) - { - s.Append(""MemberListBinding(Member=""); - s.Append(node.Member.ToString()); - foreach (var i in node.Initializers) - { - s.Append("" ""); - VisitElementInit(i); - } - s.Append("")""); - return null; - } - - protected override MemberAssignment VisitMemberAssignment(MemberAssignment node) - { - s.Append(""MemberAssignment(Member=""); - s.Append(node.Member.ToString()); - s.Append("" Expression=""); - Visit(node.Expression); - s.Append("")""); - return null; - } - - protected override Expression VisitMemberInit(MemberInitExpression node) - { - s.Append(""NewExpression: ""); - Visit(node.NewExpression); - s.Append("" Bindings:[""); - bool first = true; - foreach (var b in node.Bindings) - { - if (!first) s.Append("" ""); - VisitMemberBinding(b); - first = false; - } - s.Append(""]""); - return null; - } - - protected override Expression VisitBinary(BinaryExpression node) - { - Visit(node.Left); - s.Append("" ""); - Visit(node.Right); - if (node.Conversion != null) - { - s.Append("" Conversion:""); - Visit(node.Conversion); - } - if (node.IsLifted) s.Append("" Lifted""); - if (node.IsLiftedToNull) s.Append("" LiftedToNull""); - if (node.Method != null) s.Append("" Method:["" + node.Method + ""]""); - return null; - } - - protected override Expression VisitConditional(ConditionalExpression node) - { - Visit(node.Test); - s.Append("" ? ""); - Visit(node.IfTrue); - s.Append("" : ""); - Visit(node.IfFalse); - return null; - } - - protected override Expression VisitConstant(ConstantExpression node) - { - // s.Append(node.Value == null ? ""null"" : node.Value.ToString()); - s.Append(node.Value == null ? ""null"" : GetCultureInvariantString(node.Value)); - return null; - } - - protected override Expression VisitDefault(DefaultExpression node) - { - return null; - } - - protected override Expression VisitIndex(IndexExpression node) - { - Visit(node.Object); - s.Append(""[""); - int n = node.Arguments.Count; - for (int i = 0; i < n; i++) - { - if (i != 0) s.Append("" ""); - Visit(node.Arguments[i]); - } - s.Append(""]""); - if (node.Indexer != null) s.Append("" Indexer:"" + node.Indexer); - return null; - } - - protected override Expression VisitInvocation(InvocationExpression node) - { - Visit(node.Expression); - s.Append(""(""); - int n = node.Arguments.Count; - for (int i = 0; i < n; i++) - { - if (i != 0) s.Append("" ""); - Visit(node.Arguments[i]); - } - s.Append("")""); - return null; - } - - protected override Expression VisitLambda(Expression node) - { - s.Append(""(""); - int n = node.Parameters.Count; - for (int i = 0; i < n; i++) - { - if (i != 0) s.Append("" ""); - Visit(node.Parameters[i]); - } - s.Append("") => ""); - if (node.Name != null) s.Append(node.Name); - Visit(node.Body); - if (node.ReturnType != null) s.Append("" ReturnType:"" + node.ReturnType); - if (node.TailCall) s.Append("" TailCall""); - return null; - } - - protected override Expression VisitListInit(ListInitExpression node) - { - Visit(node.NewExpression); - s.Append(""{""); - int n = node.Initializers.Count; - for (int i = 0; i < n; i++) - { - if (i != 0) s.Append("" ""); - Visit(node.Initializers[i]); - } - s.Append(""}""); - return null; - } - - protected override ElementInit VisitElementInit(ElementInit node) - { - Visit(node); - return null; - } - - private void Visit(ElementInit node) - { - s.Append(""ElementInit(""); - s.Append(node.AddMethod); - int n = node.Arguments.Count; - for (int i = 0; i < n; i++) - { - s.Append("" ""); - Visit(node.Arguments[i]); - } - s.Append("")""); - } - - protected override Expression VisitMember(MemberExpression node) - { - Visit(node.Expression); - s.Append("".""); - s.Append(node.Member.Name); - return null; - } - - protected override Expression VisitMethodCall(MethodCallExpression node) - { - Visit(node.Object); - s.Append("".["" + node.Method + ""]""); - s.Append(""(""); - int n = node.Arguments.Count; - for (int i = 0; i < n; i++) - { - if (i != 0) s.Append("", ""); - Visit(node.Arguments[i]); - } - s.Append("")""); - return null; - } - - protected override Expression VisitNew(NewExpression node) - { - s.Append((node.Constructor != null) ? ""["" + node.Constructor + ""]"" : ""<.ctor>""); - s.Append(""(""); - int n = node.Arguments.Count; - for (int i = 0; i < n; i++) - { - if (i != 0) s.Append("", ""); - Visit(node.Arguments[i]); - } - s.Append("")""); - if (node.Members != null) - { - n = node.Members.Count; - if (n != 0) - { - s.Append(""{""); - for (int i = 0; i < n; i++) - { - var info = node.Members[i]; - if (i != 0) s.Append("" ""); - s.Append(info); - } - s.Append(""}""); - } - } - return null; - } - - protected override Expression VisitNewArray(NewArrayExpression node) - { - s.Append(""[""); - int n = node.Expressions.Count; - for (int i = 0; i < n; i++) - { - if (i != 0) s.Append("" ""); - Visit(node.Expressions[i]); - } - s.Append(""]""); - return null; - } - - protected override Expression VisitParameter(ParameterExpression node) - { - s.Append(node.Name); - if (node.IsByRef) s.Append("" ByRef""); - return null; - } - - protected override Expression VisitTypeBinary(TypeBinaryExpression node) - { - Visit(node.Expression); - s.Append("" TypeOperand:"" + node.TypeOperand); - return null; - } - - protected override Expression VisitUnary(UnaryExpression node) - { - Visit(node.Operand); - if (node.IsLifted) s.Append("" Lifted""); - if (node.IsLiftedToNull) s.Append("" LiftedToNull""); - if (node.Method != null) s.Append("" Method:["" + node.Method + ""]""); - return null; - } - - public static string GetCultureInvariantString(object value) - { - var valueType = value.GetType(); - if (valueType == typeof(string)) - { - return value as string; - } - - if (valueType == typeof(DateTime)) - { - return ((DateTime)value).ToString(""M/d/yyyy h:mm:ss tt"", CultureInfo.InvariantCulture); - } - - if (valueType == typeof(float)) - { - return ((float)value).ToString(CultureInfo.InvariantCulture); - } - - if (valueType == typeof(double)) - { - return ((double)value).ToString(CultureInfo.InvariantCulture); - } - - if (valueType == typeof(decimal)) - { - return ((decimal)value).ToString(CultureInfo.InvariantCulture); - } - - return value.ToString(); - } -} -"; - #endregion A string containing expression-tree dumping utilities - [Fact] public void ExprLambdaReordering() { diff --git a/src/roslyn/src/Compilers/CSharp/Test/Emit/Emit/CompilationEmitTests.cs b/src/roslyn/src/Compilers/CSharp/Test/Emit/Emit/CompilationEmitTests.cs index c4dca4e0d28..a85ace38643 100644 --- a/src/roslyn/src/Compilers/CSharp/Test/Emit/Emit/CompilationEmitTests.cs +++ b/src/roslyn/src/Compilers/CSharp/Test/Emit/Emit/CompilationEmitTests.cs @@ -15,6 +15,8 @@ using System.Reflection.PortableExecutable; using System.Text; using System.Threading; +using Basic.Reference.Assemblies; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.CSharp.Emit; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE; @@ -24,7 +26,6 @@ using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; -using Basic.Reference.Assemblies; namespace Microsoft.CodeAnalysis.CSharp.UnitTests.Emit { diff --git a/src/roslyn/src/Compilers/CSharp/Test/Emit/Emit/EmitMetadataTests.cs b/src/roslyn/src/Compilers/CSharp/Test/Emit/Emit/EmitMetadataTests.cs index 484d3f8c0f0..d70f3f478ae 100644 --- a/src/roslyn/src/Compilers/CSharp/Test/Emit/Emit/EmitMetadataTests.cs +++ b/src/roslyn/src/Compilers/CSharp/Test/Emit/Emit/EmitMetadataTests.cs @@ -13,6 +13,7 @@ using System.Reflection.PortableExecutable; using System.Runtime.InteropServices; using System.Threading; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.CSharp.Emit; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE; diff --git a/src/roslyn/src/Compilers/CSharp/Test/Emit3/Semantics/ExtensionTests.cs b/src/roslyn/src/Compilers/CSharp/Test/Emit3/Semantics/ExtensionTests.cs index 17f3ef8e322..b0656529312 100644 --- a/src/roslyn/src/Compilers/CSharp/Test/Emit3/Semantics/ExtensionTests.cs +++ b/src/roslyn/src/Compilers/CSharp/Test/Emit3/Semantics/ExtensionTests.cs @@ -24,7 +24,7 @@ namespace Microsoft.CodeAnalysis.CSharp.UnitTests.Semantics; [CompilerTrait(CompilerFeature.Extensions)] -public class ExtensionTests : CompilingTestBase +public partial class ExtensionTests : CompilingTestBase { private static string ExpectedOutput(string output) { @@ -126,10 +126,10 @@ .class nested public auto ansi sealed beforefieldinit '<>E__0' extends [netstandard]System.Object { // Methods - .method private hidebysig specialname static + .method private hidebysig specialname static void '$' ( object '' - ) cil managed + ) cil managed { .custom instance void [netstandard]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 @@ -296,10 +296,10 @@ 01 00 00 00 extends [netstandard]System.Object { // Methods - .method private hidebysig specialname static + .method private hidebysig specialname static void '$' ( !T '' - ) cil managed + ) cil managed { .custom instance void [netstandard]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 @@ -585,10 +585,10 @@ extends [netstandard]System.Object 01 00 01 00 00 ) // Methods - .method private hidebysig specialname static + .method private hidebysig specialname static void '$' ( !T '' - ) cil managed + ) cil managed { .custom instance void [netstandard]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 @@ -829,10 +829,10 @@ .class nested public auto ansi sealed beforefieldinit '<>E__0' extends [netstandard]System.Object { // Methods - .method private hidebysig specialname static + .method private hidebysig specialname static void '$' ( object '' - ) cil managed + ) cil managed { .custom instance void [netstandard]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 @@ -1125,10 +1125,10 @@ .class nested public auto ansi sealed beforefieldinit '<>E__0' extends [netstandard]System.Object { // Methods - .method private hidebysig specialname static + .method private hidebysig specialname static void '$' ( class [netstandard]System.Text.StringBuilder '' - ) cil managed + ) cil managed { .custom instance void [netstandard]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 @@ -1138,10 +1138,10 @@ 01 00 00 00 .maxstack 8 IL_0000: ret } // end of method '<>E__0'::'$' - .method public hidebysig static + .method public hidebysig static class [netstandard]System.Text.StringBuilder Inspect ( class [netstandard]System.Text.StringBuilder sb - ) cil managed + ) cil managed { // Method begins at RVA 0x20a7 // Code size 2 (0x2) @@ -1159,8 +1159,8 @@ 01 00 00 00 // Fields .field public class [netstandard]System.Text.StringBuilder sb // Methods - .method public hidebysig specialname rtspecialname - instance void .ctor () cil managed + .method public hidebysig specialname rtspecialname + instance void .ctor () cil managed { // Method begins at RVA 0x2079 // Code size 7 (0x7) @@ -1169,8 +1169,8 @@ .maxstack 8 IL_0001: call instance void [netstandard]System.Object::.ctor() IL_0006: ret } // end of method '<>c__DisplayClass1_0'::.ctor - .method assembly hidebysig - instance void 'b__0' () cil managed + .method assembly hidebysig + instance void 'b__0' () cil managed { // Method begins at RVA 0x20ac // Code size 42 (0x2a) @@ -1204,10 +1204,10 @@ [1] int32 } // end of method '<>c__DisplayClass1_0'::'b__0' } // end of class <>c__DisplayClass1_0 // Methods - .method public hidebysig static + .method public hidebysig static class [netstandard]System.Text.StringBuilder Inspect ( class [netstandard]System.Text.StringBuilder sb - ) cil managed + ) cil managed { // Method begins at RVA 0x2081 // Code size 35 (0x23) @@ -1289,10 +1289,10 @@ .class nested public auto ansi sealed beforefieldinit '<>E__0' extends [netstandard]System.Object { // Methods - .method private hidebysig specialname static + .method private hidebysig specialname static void '$' ( int32 '' - ) cil managed + ) cil managed { .custom instance void [netstandard]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 @@ -1302,8 +1302,8 @@ 01 00 00 00 .maxstack 8 IL_0000: ret } // end of method '<>E__0'::'$' - .method public hidebysig static - class [netstandard]System.Action DoSomething () cil managed + .method public hidebysig static + class [netstandard]System.Action DoSomething () cil managed { // Method begins at RVA 0x20be // Code size 2 (0x2) @@ -1321,8 +1321,8 @@ 01 00 00 00 // Fields .field public int32 b // Methods - .method public hidebysig specialname rtspecialname - instance void .ctor () cil managed + .method public hidebysig specialname rtspecialname + instance void .ctor () cil managed { // Method begins at RVA 0x2073 // Code size 7 (0x7) @@ -1331,8 +1331,8 @@ .maxstack 8 IL_0001: call instance void [netstandard]System.Object::.ctor() IL_0006: ret } // end of method '<>c__DisplayClass1_0'::.ctor - .method assembly hidebysig - instance void 'b__0' () cil managed + .method assembly hidebysig + instance void 'b__0' () cil managed { // Method begins at RVA 0x20c4 // Code size 35 (0x23) @@ -1357,8 +1357,8 @@ [0] int32 } // end of method '<>c__DisplayClass1_0'::'b__0' } // end of class <>c__DisplayClass1_0 // Methods - .method public hidebysig static - class [netstandard]System.Action DoSomething () cil managed + .method public hidebysig static + class [netstandard]System.Action DoSomething () cil managed { // Method begins at RVA 0x207c // Code size 52 (0x34) @@ -1454,10 +1454,10 @@ .class nested public auto ansi sealed beforefieldinit '<>E__0' extends [netstandard]System.Object { // Methods - .method private hidebysig specialname static + .method private hidebysig specialname static void '$' ( int32 '' - ) cil managed + ) cil managed { .custom instance void [netstandard]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 @@ -1467,8 +1467,8 @@ 01 00 00 00 .maxstack 8 IL_0000: ret } // end of method '<>E__0'::'$' - .method public hidebysig static - class [netstandard]System.Action DoSomething () cil managed + .method public hidebysig static + class [netstandard]System.Action DoSomething () cil managed { // Method begins at RVA 0x20bc // Code size 2 (0x2) @@ -1486,8 +1486,8 @@ 01 00 00 00 // Fields .field public int32 b // Methods - .method public hidebysig specialname rtspecialname - instance void .ctor () cil managed + .method public hidebysig specialname rtspecialname + instance void .ctor () cil managed { // Method begins at RVA 0x2073 // Code size 7 (0x7) @@ -1496,8 +1496,8 @@ .maxstack 8 IL_0001: call instance void [netstandard]System.Object::.ctor() IL_0006: ret } // end of method '<>c__DisplayClass1_0'::.ctor - .method assembly hidebysig - instance void 'b__0' () cil managed + .method assembly hidebysig + instance void 'b__0' () cil managed { // Method begins at RVA 0x20c0 // Code size 35 (0x23) @@ -1522,8 +1522,8 @@ [0] int32 } // end of method '<>c__DisplayClass1_0'::'b__0' } // end of class <>c__DisplayClass1_0 // Methods - .method public hidebysig static - class [netstandard]System.Action DoSomething () cil managed + .method public hidebysig static + class [netstandard]System.Action DoSomething () cil managed { // Method begins at RVA 0x207c // Code size 50 (0x32) @@ -1744,10 +1744,10 @@ .class nested public auto ansi sealed beforefieldinit '<>E__0' extends [netstandard]System.Object { // Methods - .method private hidebysig specialname static + .method private hidebysig specialname static void '$' ( object o - ) cil managed + ) cil managed { .custom instance void [netstandard]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 @@ -1757,8 +1757,8 @@ 01 00 00 00 .maxstack 8 IL_0000: ret } // end of method '<>E__0'::'$' - .method private hidebysig - instance void M () cil managed + .method private hidebysig + instance void M () cil managed { // Method begins at RVA 0x2069 // Code size 2 (0x2) @@ -1768,10 +1768,10 @@ .maxstack 8 } // end of method '<>E__0'::M } // end of class <>E__0 // Methods - .method private hidebysig static + .method private hidebysig static void M ( object o - ) cil managed + ) cil managed { .custom instance void [netstandard]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 @@ -1850,10 +1850,10 @@ .class nested public auto ansi sealed beforefieldinit '<>E__0' extends [netstandard]System.Object { // Methods - .method private hidebysig specialname static + .method private hidebysig specialname static void '$' ( object '' - ) cil managed + ) cil managed { .custom instance void [netstandard]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 @@ -1863,8 +1863,8 @@ 01 00 00 00 .maxstack 8 IL_0000: ret } // end of method '<>E__0'::'$' - .method private hidebysig static - void M () cil managed + .method private hidebysig static + void M () cil managed { // Method begins at RVA 0x2069 // Code size 2 (0x2) @@ -1874,8 +1874,8 @@ .maxstack 8 } // end of method '<>E__0'::M } // end of class <>E__0 // Methods - .method private hidebysig static - void M () cil managed + .method private hidebysig static + void M () cil managed { // Method begins at RVA 0x2067 // Code size 1 (0x1) @@ -1971,10 +1971,10 @@ .class nested public auto ansi sealed beforefieldinit '<>E__0' extends [netstandard]System.Object { // Methods - .method private hidebysig specialname static + .method private hidebysig specialname static void '$' ( object o - ) cil managed + ) cil managed { .custom instance void [netstandard]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 @@ -1984,8 +1984,8 @@ 01 00 00 00 .maxstack 8 IL_0000: ret } // end of method '<>E__0'::'$' - .method private hidebysig specialname - instance int32 get_Property () cil managed + .method private hidebysig specialname + instance int32 get_Property () cil managed { // Method begins at RVA 0x206d // Code size 2 (0x2) @@ -1993,10 +1993,10 @@ .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method '<>E__0'::get_Property - .method private hidebysig specialname + .method private hidebysig specialname instance void set_Property ( int32 'value' - ) cil managed + ) cil managed { // Method begins at RVA 0x206d // Code size 2 (0x2) @@ -2012,10 +2012,10 @@ .property instance int32 Property() } } // end of class <>E__0 // Methods - .method private hidebysig static + .method private hidebysig static int32 get_Property ( object o - ) cil managed + ) cil managed { // Method begins at RVA 0x2067 // Code size 3 (0x3) @@ -2023,11 +2023,11 @@ .maxstack 8 IL_0000: ldc.i4.s 42 IL_0002: ret } // end of method Extensions::get_Property - .method private hidebysig static + .method private hidebysig static void set_Property ( object o, int32 'value' - ) cil managed + ) cil managed { // Method begins at RVA 0x206b // Code size 1 (0x1) @@ -2140,10 +2140,10 @@ .class nested public auto ansi sealed beforefieldinit '<>E__0' extends [netstandard]System.Object { // Methods - .method private hidebysig specialname static + .method private hidebysig specialname static void '$' ( object '' - ) cil managed + ) cil managed { .custom instance void [netstandard]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 @@ -2153,8 +2153,8 @@ 01 00 00 00 .maxstack 8 IL_0000: ret } // end of method '<>E__0'::'$' - .method private hidebysig specialname static - int32 get_Property () cil managed + .method private hidebysig specialname static + int32 get_Property () cil managed { // Method begins at RVA 0x206d // Code size 2 (0x2) @@ -2162,10 +2162,10 @@ .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method '<>E__0'::get_Property - .method private hidebysig specialname static + .method private hidebysig specialname static void set_Property ( int32 'value' - ) cil managed + ) cil managed { // Method begins at RVA 0x206d // Code size 2 (0x2) @@ -2181,8 +2181,8 @@ .property int32 Property() } } // end of class <>E__0 // Methods - .method private hidebysig static - int32 get_Property () cil managed + .method private hidebysig static + int32 get_Property () cil managed { // Method begins at RVA 0x2067 // Code size 3 (0x3) @@ -2190,10 +2190,10 @@ .maxstack 8 IL_0000: ldc.i4.s 42 IL_0002: ret } // end of method Extensions::get_Property - .method private hidebysig static + .method private hidebysig static void set_Property ( int32 'value' - ) cil managed + ) cil managed { // Method begins at RVA 0x206b // Code size 1 (0x1) @@ -2279,10 +2279,10 @@ extends [netstandard]System.Object 01 00 04 49 74 65 6d 00 00 ) // Methods - .method private hidebysig specialname static + .method private hidebysig specialname static void '$' ( object o - ) cil managed + ) cil managed { .custom instance void [netstandard]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 @@ -2292,10 +2292,10 @@ 01 00 00 00 .maxstack 8 IL_0000: ret } // end of method '<>E__0'::'$' - .method private hidebysig specialname + .method private hidebysig specialname instance int32 get_Item ( int32 i - ) cil managed + ) cil managed { // Method begins at RVA 0x206d // Code size 2 (0x2) @@ -2303,11 +2303,11 @@ .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method '<>E__0'::get_Item - .method private hidebysig specialname + .method private hidebysig specialname instance void set_Item ( int32 i, int32 'value' - ) cil managed + ) cil managed { // Method begins at RVA 0x206d // Code size 2 (0x2) @@ -2325,11 +2325,11 @@ int32 i } } // end of class <>E__0 // Methods - .method private hidebysig static + .method private hidebysig static int32 get_Item ( object o, int32 i - ) cil managed + ) cil managed { // Method begins at RVA 0x2067 // Code size 3 (0x3) @@ -2337,12 +2337,12 @@ .maxstack 8 IL_0000: ldc.i4.s 42 IL_0002: ret } // end of method Extensions::get_Item - .method private hidebysig static + .method private hidebysig static void set_Item ( object o, int32 i, int32 'value' - ) cil managed + ) cil managed { // Method begins at RVA 0x206b // Code size 1 (0x1) @@ -2731,7 +2731,7 @@ public void ReceiverParameter_WithIdentifier() var src = """ public static class Extensions { - extension(object o) + extension(object o) { public object M() { return o; } } @@ -2884,7 +2884,7 @@ public void ReceiverParameter_TypeParameter_Unreferenced_01() public static class Extensions { - extension(int) + extension(int) { public static void M() { } } @@ -2896,7 +2896,7 @@ public static void M() { } // int.M(); Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "M").WithArguments("int", "M").WithLocation(1, 5), // (5,18): error CS9295: The extended type 'int' must reference all the type parameters declared by the extension, but type parameter 'T' is not referenced. - // extension(int) + // extension(int) Diagnostic(ErrorCode.ERR_UnderspecifiedExtension, "int").WithArguments("int", "T").WithLocation(5, 18)); } @@ -2908,7 +2908,7 @@ public void ReceiverParameter_TypeParameter_Unreferenced_02() public static class Extensions { - extension(T1) + extension(T1) { public static void M() { } } @@ -2920,7 +2920,7 @@ public static void M() { } // int.M(); Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "M").WithArguments("int", "M").WithLocation(1, 5), // (5,23): error CS9295: The extended type 'T1' must reference all the type parameters declared by the extension, but type parameter 'T2' is not referenced. - // extension(T1) + // extension(T1) Diagnostic(ErrorCode.ERR_UnderspecifiedExtension, "T1").WithArguments("T1", "T2").WithLocation(5, 23)); } @@ -3302,7 +3302,7 @@ public void ReceiverParameter_Ref_01() public static class Extensions { - extension(ref int i) + extension(ref int i) { public void M() { System.Console.Write(i); i = 43; } } @@ -3519,7 +3519,7 @@ public void ReceiverParameter_RefReadonly_01() public static class Extensions { - extension(ref readonly int i) + extension(ref readonly int i) { public void M() { System.Console.Write(i); } } @@ -3941,25 +3941,51 @@ static class Extensions ); } - [Fact] - public void ReceiverParameter_RefScope() + [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/78491")] + public void ReceiverParameter_RefScope_01() { var src = """ +int i = 42; +i.M(); + static class Extensions { extension(scoped ref int receiver) { + public void M() => System.Console.Write(receiver); } } """; var comp = CreateCompilation(src); - CompileAndVerify(comp, symbolValidator: (m) => + CompileAndVerify(comp, expectedOutput: "42", symbolValidator: (m) => { AssertEx.Equal(ScopedKind.ScopedRef, m.GlobalNamespace.GetMember("Extensions.<>E__0.$").Parameters[0].EffectiveScope); }).VerifyDiagnostics(); } + [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/78491")] + public void ReceiverParameter_RefScope_02() + { + var src = """ +int i = 42; +i.M(); + +static class Extensions +{ + extension(scoped ref int receiver) + { + public ref int M() => ref receiver; + } +} +"""; + var comp = CreateCompilation(src); + comp.VerifyEmitDiagnostics( + // (8,35): error CS9075: Cannot return a parameter by reference 'receiver' because it is scoped to the current method + // public ref int M() => ref receiver; + Diagnostic(ErrorCode.ERR_RefReturnScopedParameter, "receiver").WithArguments("receiver").WithLocation(8, 35)); + } + [Fact] public void ReceiverParameter_Nullability() { @@ -3985,7 +4011,11 @@ static class Extensions AssertEx.Equal("System.String?", m.GlobalNamespace.GetMember("Extensions.<>E__1.$").Parameters[0].TypeWithAnnotations.ToTestDisplayString()); }).VerifyDiagnostics(); - // Tracked by https://github.com/dotnet/roslyn/issues/76130 : verify nullability in GetDeclaredSymbol and GetSymbolInfo + var tree = comp.SyntaxTrees.Single(); + var model = comp.GetSemanticModel(tree); + var parameters = tree.GetRoot().DescendantNodes().OfType().ToArray(); + Assert.Equal("System.String? receiver", model.GetDeclaredSymbol(parameters[0]).ToTestDisplayString(includeNonNullable: true)); + Assert.Equal("System.String?", model.GetDeclaredSymbol(parameters[1]).ToTestDisplayString(includeNonNullable: true)); } [Fact] @@ -4044,12 +4074,10 @@ class C {} // (5,21): error CS0051: Inconsistent accessibility: parameter type 'C' is less accessible than method 'Extensions.extension(C).M()' // public void M() {} Diagnostic(ErrorCode.ERR_BadVisParamType, "M").WithArguments("Extensions.extension(C).M()", "C").WithLocation(5, 21), - - // Tracked by https://github.com/dotnet/roslyn/issues/76130 : Error wording, this isn't an indexer - // (6,20): error CS0055: Inconsistent accessibility: parameter type 'C' is less accessible than indexer 'Extensions.extension(C).P' + // (6,20): error CS0055: Inconsistent accessibility: parameter type 'C' is less accessible than indexer or property 'Extensions.extension(C).P' // public int P { get => 0; set {}} Diagnostic(ErrorCode.ERR_BadVisIndexerParam, "P").WithArguments("Extensions.extension(C).P", "C").WithLocation(6, 20), - // (7,20): error CS0055: Inconsistent accessibility: parameter type 'C' is less accessible than indexer 'Extensions.extension(C).this[int]' + // (7,20): error CS0055: Inconsistent accessibility: parameter type 'C' is less accessible than indexer or property 'Extensions.extension(C).this[int]' // public int this[int i] { get => 0; set {}} Diagnostic(ErrorCode.ERR_BadVisIndexerParam, "this").WithArguments("Extensions.extension(C).this[int]", "C").WithLocation(7, 20) ); @@ -4103,22 +4131,19 @@ private class C {} // (5,21): error CS0051: Inconsistent accessibility: parameter type 'Extensions.C' is less accessible than method 'Extensions.extension(Extensions.C).M()' // public void M() {} Diagnostic(ErrorCode.ERR_BadVisParamType, "M").WithArguments("Extensions.extension(Extensions.C).M()", "Extensions.C").WithLocation(5, 21), - - // Tracked by https://github.com/dotnet/roslyn/issues/76130 : Error wording, this isn't an indexer - - // (6,20): error CS0055: Inconsistent accessibility: parameter type 'Extensions.C' is less accessible than indexer 'Extensions.extension(Extensions.C).P' + // (6,20): error CS0055: Inconsistent accessibility: parameter type 'Extensions.C' is less accessible than indexer or property 'Extensions.extension(Extensions.C).P' // public int P { get => 0; set {}} Diagnostic(ErrorCode.ERR_BadVisIndexerParam, "P").WithArguments("Extensions.extension(Extensions.C).P", "Extensions.C").WithLocation(6, 20), - // (7,20): error CS0055: Inconsistent accessibility: parameter type 'Extensions.C' is less accessible than indexer 'Extensions.extension(Extensions.C).this[int]' + // (7,20): error CS0055: Inconsistent accessibility: parameter type 'Extensions.C' is less accessible than indexer or property 'Extensions.extension(Extensions.C).this[int]' // public int this[int i] { get => 0; set {}} Diagnostic(ErrorCode.ERR_BadVisIndexerParam, "this").WithArguments("Extensions.extension(Extensions.C).this[int]", "Extensions.C").WithLocation(7, 20), // (13,23): error CS0051: Inconsistent accessibility: parameter type 'Extensions.C' is less accessible than method 'Extensions.extension(Extensions.C).M2()' // internal void M2() {} Diagnostic(ErrorCode.ERR_BadVisParamType, "M2").WithArguments("Extensions.extension(Extensions.C).M2()", "Extensions.C").WithLocation(13, 23), - // (14,22): error CS0055: Inconsistent accessibility: parameter type 'Extensions.C' is less accessible than indexer 'Extensions.extension(Extensions.C).P2' + // (14,22): error CS0055: Inconsistent accessibility: parameter type 'Extensions.C' is less accessible than indexer or property 'Extensions.extension(Extensions.C).P2' // internal int P2 { get => 0; set {}} Diagnostic(ErrorCode.ERR_BadVisIndexerParam, "P2").WithArguments("Extensions.extension(Extensions.C).P2", "Extensions.C").WithLocation(14, 22), - // (15,22): error CS0055: Inconsistent accessibility: parameter type 'Extensions.C' is less accessible than indexer 'Extensions.extension(Extensions.C).this[byte]' + // (15,22): error CS0055: Inconsistent accessibility: parameter type 'Extensions.C' is less accessible than indexer or property 'Extensions.extension(Extensions.C).this[byte]' // internal int this[byte i] { get => 0; set {}} Diagnostic(ErrorCode.ERR_BadVisIndexerParam, "this").WithArguments("Extensions.extension(Extensions.C).this[byte]", "Extensions.C").WithLocation(15, 22) ); @@ -4538,7 +4563,7 @@ static void Main() _ = GetInt().P; } - static int GetInt() => 0; + static int GetInt() => 0; } static class Extensions @@ -4582,23 +4607,24 @@ static void Main() _ = GetInt().P; } - static int GetInt() => 0; + static int GetInt() => 0; } static class Extensions { extension(ref readonly int receiver) { - public void M1() {} - public int P => 0; + public void M1() { System.Console.Write("ranM1 "); } + public int P { get { System.Console.Write("ranP"); return 0; } } } public static void M2 (this ref readonly int receiver) { + System.Console.Write("ranM2 "); } } """; - var comp = CreateCompilation(src); + var comp = CreateCompilation(src, options: TestOptions.DebugExe); comp.VerifyEmitDiagnostics( // (5,9): warning CS9193: Argument 0 should be a variable because it is passed to a 'ref readonly' parameter @@ -4612,7 +4638,7 @@ public static void M2 (this ref readonly int receiver) Diagnostic(ErrorCode.WRN_RefReadonlyNotVariable, "GetInt()").WithArguments("0").WithLocation(7, 13) ); - // Tracked by https://github.com/dotnet/roslyn/issues/76130 : Test emit and execution for a scenario like this + CompileAndVerify(comp, expectedOutput: "ranM1 ranM2 ranP"); } [Fact] @@ -4628,25 +4654,25 @@ static void Main() _ = GetInt().P; } - static int GetInt() => 0; + static int GetInt() => 0; } static class Extensions { extension(in int receiver) { - public void M1() {} - public int P => 0; + public void M1() { System.Console.Write("ranM1 "); } + public int P { get { System.Console.Write("ranP"); return 0; } } } - public static void M2 (this in int receiver) + public static void M2(this in int receiver) { + System.Console.Write("ranM2 "); } } """; - var comp = CreateCompilation(src); - - comp.VerifyEmitDiagnostics(); // Tracked by https://github.com/dotnet/roslyn/issues/76130 : Test emit and execution for a scenario like this + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + CompileAndVerify(comp, expectedOutput: "ranM1 ranM2 ranP").VerifyDiagnostics(); } [Fact] @@ -4680,10 +4706,10 @@ .class nested public auto ansi sealed beforefieldinit '<>E__0' extends [mscorlib]System.Object { // Methods - .method private hidebysig specialname static + .method private hidebysig specialname static void '$' ( object o - ) cil managed + ) cil managed { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 @@ -4693,10 +4719,10 @@ 01 00 00 00 .maxstack 8 IL_0000: ret } // end of method '<>E__0'::'$' - .method private hidebysig + .method private hidebysig instance void M ( string s - ) cil managed + ) cil managed { // Method begins at RVA 0x2079 // Code size 2 (0x2) @@ -4706,11 +4732,11 @@ .maxstack 8 } // end of method '<>E__0'::M } // end of class <>E__0 // Methods - .method private hidebysig static + .method private hidebysig static void M ( object o, string s - ) cil managed + ) cil managed { .custom instance void [mscorlib]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 @@ -4799,10 +4825,10 @@ .class nested public auto ansi sealed beforefieldinit '<>E__0' extends [mscorlib]System.Object { // Methods - .method private hidebysig specialname static + .method private hidebysig specialname static void '$' ( object o - ) cil managed + ) cil managed { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 @@ -4812,10 +4838,10 @@ 01 00 00 00 .maxstack 8 IL_0000: ret } // end of method '<>E__0'::'$' - .method public hidebysig + .method public hidebysig instance string M ( string s - ) cil managed + ) cil managed { // Method begins at RVA 0x207d // Code size 2 (0x2) @@ -4825,11 +4851,11 @@ .maxstack 8 } // end of method '<>E__0'::M } // end of class <>E__0 // Methods - .method public hidebysig static + .method public hidebysig static string M ( object o, string s - ) cil managed + ) cil managed { .custom instance void [mscorlib]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 @@ -5168,10 +5194,10 @@ .class nested public auto ansi sealed beforefieldinit '<>E__0' extends [mscorlib]System.Object { // Methods - .method private hidebysig specialname static + .method private hidebysig specialname static void '$' ( object o - ) cil managed + ) cil managed { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 @@ -5181,10 +5207,10 @@ 01 00 00 00 .maxstack 8 IL_0000: ret } // end of method '<>E__0'::'$' - .method public hidebysig + .method public hidebysig instance string M ( string s - ) cil managed + ) cil managed { // Method begins at RVA 0x20ad // Code size 2 (0x2) @@ -5204,11 +5230,11 @@ .field public object o .field public string s } // end of class <>c__DisplayClass1_0 // Methods - .method public hidebysig static + .method public hidebysig static string M ( object o, string s - ) cil managed + ) cil managed { .custom instance void [mscorlib]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 @@ -5229,10 +5255,10 @@ [0] valuetype Extensions/'<>c__DisplayClass1_0' IL_0012: call string Extensions::'b__1_0'(valuetype Extensions/'<>c__DisplayClass1_0'&) IL_0017: ret } // end of method Extensions::M - .method assembly hidebysig static + .method assembly hidebysig static string 'b__1_0' ( valuetype Extensions/'<>c__DisplayClass1_0'& '' - ) cil managed + ) cil managed { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 @@ -5348,10 +5374,10 @@ .class nested public auto ansi sealed beforefieldinit '<>E__0' extends [mscorlib]System.Object { // Methods - .method private hidebysig specialname static + .method private hidebysig specialname static void '$' ( object o - ) cil managed + ) cil managed { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 @@ -5361,10 +5387,10 @@ 01 00 00 00 .maxstack 8 IL_0000: ret } // end of method '<>E__0'::'$' - .method public hidebysig + .method public hidebysig instance string M ( string s - ) cil managed + ) cil managed { // Method begins at RVA 0x208e // Code size 2 (0x2) @@ -5383,8 +5409,8 @@ 01 00 00 00 .field public object o .field public string s // Methods - .method public hidebysig specialname rtspecialname - instance void .ctor () cil managed + .method public hidebysig specialname rtspecialname + instance void .ctor () cil managed { // Method begins at RVA 0x2091 // Code size 7 (0x7) @@ -5393,8 +5419,8 @@ .maxstack 8 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method '<>c__DisplayClass1_0'::.ctor - .method assembly hidebysig - instance string 'b__0' () cil managed + .method assembly hidebysig + instance string 'b__0' () cil managed { // Method begins at RVA 0x2099 // Code size 30 (0x1e) @@ -5414,11 +5440,11 @@ .maxstack 8 } // end of method '<>c__DisplayClass1_0'::'b__0' } // end of class <>c__DisplayClass1_0 // Methods - .method public hidebysig static + .method public hidebysig static string M ( object o, string s - ) cil managed + ) cil managed { .custom instance void [mscorlib]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 @@ -5536,10 +5562,10 @@ .class nested public auto ansi sealed beforefieldinit '<>E__0' extends [mscorlib]System.Object { // Methods - .method private hidebysig specialname static + .method private hidebysig specialname static void '$' ( object o - ) cil managed + ) cil managed { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 @@ -5549,10 +5575,10 @@ 01 00 00 00 .maxstack 8 IL_0000: ret } // end of method '<>E__0'::'$' - .method public hidebysig + .method public hidebysig instance class [mscorlib]System.Collections.Generic.IEnumerable`1 M ( string s - ) cil managed + ) cil managed { // Method begins at RVA 0x2080 // Code size 2 (0x2) @@ -5593,10 +5619,10 @@ .field public object '<>3__o' .field private string s .field public string '<>3__s' // Methods - .method public hidebysig specialname rtspecialname + .method public hidebysig specialname rtspecialname instance void .ctor ( int32 '<>1__state' - ) cil managed + ) cil managed { .custom instance void [mscorlib]System.Diagnostics.DebuggerHiddenAttribute::.ctor() = ( 01 00 00 00 @@ -5614,8 +5640,8 @@ .maxstack 8 IL_0013: stfld int32 Extensions/'d__1'::'<>l__initialThreadId' IL_0018: ret } // end of method 'd__1'::.ctor - .method private final hidebysig newslot virtual - instance void System.IDisposable.Dispose () cil managed + .method private final hidebysig newslot virtual + instance void System.IDisposable.Dispose () cil managed { .custom instance void [mscorlib]System.Diagnostics.DebuggerHiddenAttribute::.ctor() = ( 01 00 00 00 @@ -5629,8 +5655,8 @@ .maxstack 8 IL_0003: stfld int32 Extensions/'d__1'::'<>1__state' IL_0008: ret } // end of method 'd__1'::System.IDisposable.Dispose - .method private final hidebysig newslot virtual - instance bool MoveNext () cil managed + .method private final hidebysig newslot virtual + instance bool MoveNext () cil managed { .override method instance bool [mscorlib]System.Collections.IEnumerator::MoveNext() // Method begins at RVA 0x20a8 @@ -5676,8 +5702,8 @@ [0] int32 IL_004a: ldc.i4.0 IL_004b: ret } // end of method 'd__1'::MoveNext - .method private final hidebysig specialname newslot virtual - instance string 'System.Collections.Generic.IEnumerator.get_Current' () cil managed + .method private final hidebysig specialname newslot virtual + instance string 'System.Collections.Generic.IEnumerator.get_Current' () cil managed { .custom instance void [mscorlib]System.Diagnostics.DebuggerHiddenAttribute::.ctor() = ( 01 00 00 00 @@ -5690,8 +5716,8 @@ .maxstack 8 IL_0001: ldfld string Extensions/'d__1'::'<>2__current' IL_0006: ret } // end of method 'd__1'::'System.Collections.Generic.IEnumerator.get_Current' - .method private final hidebysig newslot virtual - instance void System.Collections.IEnumerator.Reset () cil managed + .method private final hidebysig newslot virtual + instance void System.Collections.IEnumerator.Reset () cil managed { .custom instance void [mscorlib]System.Diagnostics.DebuggerHiddenAttribute::.ctor() = ( 01 00 00 00 @@ -5703,8 +5729,8 @@ .maxstack 8 IL_0000: newobj instance void [mscorlib]System.NotSupportedException::.ctor() IL_0005: throw } // end of method 'd__1'::System.Collections.IEnumerator.Reset - .method private final hidebysig specialname newslot virtual - instance object System.Collections.IEnumerator.get_Current () cil managed + .method private final hidebysig specialname newslot virtual + instance object System.Collections.IEnumerator.get_Current () cil managed { .custom instance void [mscorlib]System.Diagnostics.DebuggerHiddenAttribute::.ctor() = ( 01 00 00 00 @@ -5717,8 +5743,8 @@ .maxstack 8 IL_0001: ldfld string Extensions/'d__1'::'<>2__current' IL_0006: ret } // end of method 'd__1'::System.Collections.IEnumerator.get_Current - .method private final hidebysig newslot virtual - instance class [mscorlib]System.Collections.Generic.IEnumerator`1 'System.Collections.Generic.IEnumerable.GetEnumerator' () cil managed + .method private final hidebysig newslot virtual + instance class [mscorlib]System.Collections.Generic.IEnumerator`1 'System.Collections.Generic.IEnumerable.GetEnumerator' () cil managed { .custom instance void [mscorlib]System.Diagnostics.DebuggerHiddenAttribute::.ctor() = ( 01 00 00 00 @@ -5758,8 +5784,8 @@ [0] class Extensions/'d__1' IL_0041: ldloc.0 IL_0042: ret } // end of method 'd__1'::'System.Collections.Generic.IEnumerable.GetEnumerator' - .method private final hidebysig newslot virtual - instance class [mscorlib]System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator () cil managed + .method private final hidebysig newslot virtual + instance class [mscorlib]System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator () cil managed { .custom instance void [mscorlib]System.Diagnostics.DebuggerHiddenAttribute::.ctor() = ( 01 00 00 00 @@ -5783,11 +5809,11 @@ .property instance object System.Collections.IEnumerator.Current() } } // end of class d__1 // Methods - .method public hidebysig static + .method public hidebysig static class [mscorlib]System.Collections.Generic.IEnumerable`1 M ( object o, string s - ) cil managed + ) cil managed { .custom instance void [mscorlib]System.Runtime.CompilerServices.IteratorStateMachineAttribute::.ctor(class [mscorlib]System.Type) = ( 01 00 12 45 78 74 65 6e 73 69 6f 6e 73 2b 3c 4d @@ -5937,10 +5963,10 @@ .class nested public auto ansi sealed beforefieldinit '<>E__0' extends [mscorlib]System.Object { // Methods - .method private hidebysig specialname static + .method private hidebysig specialname static void '$' ( object o - ) cil managed + ) cil managed { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 @@ -5950,10 +5976,10 @@ 01 00 00 00 .maxstack 8 IL_0000: ret } // end of method '<>E__0'::'$' - .method public hidebysig + .method public hidebysig instance class [mscorlib]System.Threading.Tasks.Task`1 M ( string s - ) cil managed + ) cil managed { // Method begins at RVA 0x20b5 // Code size 2 (0x2) @@ -5976,8 +6002,8 @@ .field public object o .field public string s .field private valuetype [mscorlib]System.Runtime.CompilerServices.YieldAwaitable/YieldAwaiter '<>u__1' // Methods - .method private final hidebysig newslot virtual - instance void MoveNext () cil managed + .method private final hidebysig newslot virtual + instance void MoveNext () cil managed { .override method instance void [mscorlib]System.Runtime.CompilerServices.IAsyncStateMachine::MoveNext() // Method begins at RVA 0x20b8 @@ -6067,10 +6093,10 @@ [4] class [mscorlib]System.Exception IL_00ac: call instance void valuetype [mscorlib]System.Runtime.CompilerServices.AsyncTaskMethodBuilder`1::SetResult(!0) IL_00b1: ret } // end of method 'd__1'::MoveNext - .method private final hidebysig newslot virtual + .method private final hidebysig newslot virtual instance void SetStateMachine ( class [mscorlib]System.Runtime.CompilerServices.IAsyncStateMachine stateMachine - ) cil managed + ) cil managed { .custom instance void [mscorlib]System.Diagnostics.DebuggerHiddenAttribute::.ctor() = ( 01 00 00 00 @@ -6087,11 +6113,11 @@ .maxstack 8 } // end of method 'd__1'::SetStateMachine } // end of class d__1 // Methods - .method public hidebysig static + .method public hidebysig static class [mscorlib]System.Threading.Tasks.Task`1 M ( object o, string s - ) cil managed + ) cil managed { .custom instance void [mscorlib]System.Runtime.CompilerServices.AsyncStateMachineAttribute::.ctor(class [mscorlib]System.Type) = ( 01 00 12 45 78 74 65 6e 73 69 6f 6e 73 2b 3c 4d @@ -6237,10 +6263,10 @@ .class nested public auto ansi sealed beforefieldinit '<>E__0`1' extends [mscorlib]System.Object { // Methods - .method private hidebysig specialname static + .method private hidebysig specialname static void '$' ( class C`1 o - ) cil managed + ) cil managed { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 @@ -6250,11 +6276,11 @@ 01 00 00 00 .maxstack 8 IL_0000: ret } // end of method '<>E__0`1'::'$' - .method public hidebysig + .method public hidebysig instance string M ( !T t, !!U u - ) cil managed + ) cil managed { // Method begins at RVA 0x20a7 // Code size 2 (0x2) @@ -6264,12 +6290,12 @@ .maxstack 8 } // end of method '<>E__0`1'::M } // end of class <>E__0`1 // Methods - .method public hidebysig static + .method public hidebysig static string M ( class C`1 o, !!T t, !!U u - ) cil managed + ) cil managed { .custom instance void [mscorlib]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 @@ -6478,10 +6504,10 @@ .class nested public auto ansi sealed beforefieldinit '<>E__0`1' extends [mscorlib]System.Object { // Methods - .method private hidebysig specialname static + .method private hidebysig specialname static void '$' ( class C`1 o - ) cil managed + ) cil managed { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 @@ -6491,11 +6517,11 @@ 01 00 00 00 .maxstack 8 IL_0000: ret } // end of method '<>E__0`1'::'$' - .method public hidebysig + .method public hidebysig instance class C`1 M ( !T t1, !!U u1 - ) cil managed + ) cil managed { // Method begins at RVA 0x216f // Code size 2 (0x2) @@ -6516,12 +6542,12 @@ .field public !U u1 .field public !T t1 } // end of class <>c__DisplayClass1_0`2 // Methods - .method public hidebysig static + .method public hidebysig static class C`1 M ( class C`1 o, !!T t1, !!U u1 - ) cil managed + ) cil managed { .custom instance void [mscorlib]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 @@ -6554,7 +6580,7 @@ .locals init ( IL_0033: call class C`1 Extensions::'b__1_0'(!!0, !!1, !!2, !!3, !!4, valuetype Extensions/'<>c__DisplayClass1_0`2'&) IL_0038: ret } // end of method Extensions::M - .method assembly hidebysig static + .method assembly hidebysig static class C`1 'b__1_0' ( !!T t2, !!U u2, @@ -6562,7 +6588,7 @@ class C`1 'b__1_0' ( !!Y y2, !!Z z2, valuetype Extensions/'<>c__DisplayClass1_0`2'& '' - ) cil managed + ) cil managed { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 @@ -6753,10 +6779,10 @@ .class nested public auto ansi sealed beforefieldinit '<>E__0`1' extends [mscorlib]System.Object { // Methods - .method private hidebysig specialname static + .method private hidebysig specialname static void '$' ( class C`1 o - ) cil managed + ) cil managed { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 @@ -6766,11 +6792,11 @@ 01 00 00 00 .maxstack 8 IL_0000: ret } // end of method '<>E__0`1'::'$' - .method public hidebysig + .method public hidebysig instance class C`1 M ( !T t1, !!U u1 - ) cil managed + ) cil managed { // Method begins at RVA 0x20c6 // Code size 2 (0x2) @@ -6790,8 +6816,8 @@ .field public class C`1 o .field public !U u1 .field public !T t1 // Methods - .method public hidebysig specialname rtspecialname - instance void .ctor () cil managed + .method public hidebysig specialname rtspecialname + instance void .ctor () cil managed { // Method begins at RVA 0x20c9 // Code size 7 (0x7) @@ -6800,11 +6826,11 @@ .maxstack 8 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method '<>c__DisplayClass1_0`2'::.ctor - .method assembly hidebysig + .method assembly hidebysig instance class C`1 'b__0' ( !T t2, !U u2 - ) cil managed + ) cil managed { // Method begins at RVA 0x20d4 // Code size 103 (0x67) @@ -6849,12 +6875,12 @@ .maxstack 4 } // end of method '<>c__DisplayClass1_0`2'::'b__0' } // end of class <>c__DisplayClass1_0`2 // Methods - .method public hidebysig static + .method public hidebysig static class C`1 M ( class C`1 o, !!T t1, !!U u1 - ) cil managed + ) cil managed { .custom instance void [mscorlib]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 @@ -7012,10 +7038,10 @@ .class nested public auto ansi sealed beforefieldinit '<>E__0`1' extends [mscorlib]System.Object { // Methods - .method private hidebysig specialname static + .method private hidebysig specialname static void '$' ( class C`1 o - ) cil managed + ) cil managed { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 @@ -7025,11 +7051,11 @@ 01 00 00 00 .maxstack 8 IL_0000: ret } // end of method '<>E__0`1'::'$' - .method public hidebysig + .method public hidebysig instance class [mscorlib]System.Collections.Generic.IEnumerable`1 M ( !T t1, !!U u1 - ) cil managed + ) cil managed { // Method begins at RVA 0x209e // Code size 2 (0x2) @@ -7072,10 +7098,10 @@ .field public !U '<>3__u1' .field private !T t1 .field public !T '<>3__t1' // Methods - .method public hidebysig specialname rtspecialname + .method public hidebysig specialname rtspecialname instance void .ctor ( int32 '<>1__state' - ) cil managed + ) cil managed { .custom instance void [mscorlib]System.Diagnostics.DebuggerHiddenAttribute::.ctor() = ( 01 00 00 00 @@ -7093,8 +7119,8 @@ .maxstack 8 IL_0013: stfld int32 class Extensions/'d__1`2'::'<>l__initialThreadId' IL_0018: ret } // end of method 'd__1`2'::.ctor - .method private final hidebysig newslot virtual - instance void System.IDisposable.Dispose () cil managed + .method private final hidebysig newslot virtual + instance void System.IDisposable.Dispose () cil managed { .custom instance void [mscorlib]System.Diagnostics.DebuggerHiddenAttribute::.ctor() = ( 01 00 00 00 @@ -7108,8 +7134,8 @@ .maxstack 8 IL_0003: stfld int32 class Extensions/'d__1`2'::'<>1__state' IL_0008: ret } // end of method 'd__1`2'::System.IDisposable.Dispose - .method private final hidebysig newslot virtual - instance bool MoveNext () cil managed + .method private final hidebysig newslot virtual + instance bool MoveNext () cil managed { .override method instance bool [mscorlib]System.Collections.IEnumerator::MoveNext() // Method begins at RVA 0x20c8 @@ -7156,8 +7182,8 @@ [0] int32 IL_005f: ldc.i4.0 IL_0060: ret } // end of method 'd__1`2'::MoveNext - .method private final hidebysig specialname newslot virtual - instance string 'System.Collections.Generic.IEnumerator.get_Current' () cil managed + .method private final hidebysig specialname newslot virtual + instance string 'System.Collections.Generic.IEnumerator.get_Current' () cil managed { .custom instance void [mscorlib]System.Diagnostics.DebuggerHiddenAttribute::.ctor() = ( 01 00 00 00 @@ -7170,8 +7196,8 @@ .maxstack 8 IL_0001: ldfld string class Extensions/'d__1`2'::'<>2__current' IL_0006: ret } // end of method 'd__1`2'::'System.Collections.Generic.IEnumerator.get_Current' - .method private final hidebysig newslot virtual - instance void System.Collections.IEnumerator.Reset () cil managed + .method private final hidebysig newslot virtual + instance void System.Collections.IEnumerator.Reset () cil managed { .custom instance void [mscorlib]System.Diagnostics.DebuggerHiddenAttribute::.ctor() = ( 01 00 00 00 @@ -7183,8 +7209,8 @@ .maxstack 8 IL_0000: newobj instance void [mscorlib]System.NotSupportedException::.ctor() IL_0005: throw } // end of method 'd__1`2'::System.Collections.IEnumerator.Reset - .method private final hidebysig specialname newslot virtual - instance object System.Collections.IEnumerator.get_Current () cil managed + .method private final hidebysig specialname newslot virtual + instance object System.Collections.IEnumerator.get_Current () cil managed { .custom instance void [mscorlib]System.Diagnostics.DebuggerHiddenAttribute::.ctor() = ( 01 00 00 00 @@ -7197,8 +7223,8 @@ .maxstack 8 IL_0001: ldfld string class Extensions/'d__1`2'::'<>2__current' IL_0006: ret } // end of method 'd__1`2'::System.Collections.IEnumerator.get_Current - .method private final hidebysig newslot virtual - instance class [mscorlib]System.Collections.Generic.IEnumerator`1 'System.Collections.Generic.IEnumerable.GetEnumerator' () cil managed + .method private final hidebysig newslot virtual + instance class [mscorlib]System.Collections.Generic.IEnumerator`1 'System.Collections.Generic.IEnumerable.GetEnumerator' () cil managed { .custom instance void [mscorlib]System.Diagnostics.DebuggerHiddenAttribute::.ctor() = ( 01 00 00 00 @@ -7242,8 +7268,8 @@ .locals init ( IL_004d: ldloc.0 IL_004e: ret } // end of method 'd__1`2'::'System.Collections.Generic.IEnumerable.GetEnumerator' - .method private final hidebysig newslot virtual - instance class [mscorlib]System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator () cil managed + .method private final hidebysig newslot virtual + instance class [mscorlib]System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator () cil managed { .custom instance void [mscorlib]System.Diagnostics.DebuggerHiddenAttribute::.ctor() = ( 01 00 00 00 @@ -7267,12 +7293,12 @@ .property instance object System.Collections.IEnumerator.Current() } } // end of class d__1`2 // Methods - .method public hidebysig static + .method public hidebysig static class [mscorlib]System.Collections.Generic.IEnumerable`1 M ( class C`1 o, !!T t1, !!U u1 - ) cil managed + ) cil managed { .custom instance void [mscorlib]System.Runtime.CompilerServices.IteratorStateMachineAttribute::.ctor(class [mscorlib]System.Type) = ( 01 00 14 45 78 74 65 6e 73 69 6f 6e 73 2b 3c 4d @@ -7401,10 +7427,10 @@ .class nested public auto ansi sealed beforefieldinit '<>E__0`1' extends [mscorlib]System.Object { // Methods - .method private hidebysig specialname static + .method private hidebysig specialname static void '$' ( class C`1 o - ) cil managed + ) cil managed { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 @@ -7414,11 +7440,11 @@ 01 00 00 00 .maxstack 8 IL_0000: ret } // end of method '<>E__0`1'::'$' - .method public hidebysig + .method public hidebysig instance class [mscorlib]System.Threading.Tasks.Task`1 M ( !T t1, !!U u1 - ) cil managed + ) cil managed { // Method begins at RVA 0x20d4 // Code size 2 (0x2) @@ -7442,8 +7468,8 @@ .field public !U u1 .field public !T t1 .field private valuetype [mscorlib]System.Runtime.CompilerServices.YieldAwaitable/YieldAwaiter '<>u__1' // Methods - .method private final hidebysig newslot virtual - instance void MoveNext () cil managed + .method private final hidebysig newslot virtual + instance void MoveNext () cil managed { .override method instance void [mscorlib]System.Runtime.CompilerServices.IAsyncStateMachine::MoveNext() // Method begins at RVA 0x20d8 @@ -7534,10 +7560,10 @@ [4] class [mscorlib]System.Exception IL_00c4: call instance void valuetype [mscorlib]System.Runtime.CompilerServices.AsyncTaskMethodBuilder`1::SetResult(!0) IL_00c9: ret } // end of method 'd__1`2'::MoveNext - .method private final hidebysig newslot virtual + .method private final hidebysig newslot virtual instance void SetStateMachine ( class [mscorlib]System.Runtime.CompilerServices.IAsyncStateMachine stateMachine - ) cil managed + ) cil managed { .custom instance void [mscorlib]System.Diagnostics.DebuggerHiddenAttribute::.ctor() = ( 01 00 00 00 @@ -7554,12 +7580,12 @@ .maxstack 8 } // end of method 'd__1`2'::SetStateMachine } // end of class d__1`2 // Methods - .method public hidebysig static + .method public hidebysig static class [mscorlib]System.Threading.Tasks.Task`1 M ( class C`1 o, !!T t1, !!U u1 - ) cil managed + ) cil managed { .custom instance void [mscorlib]System.Runtime.CompilerServices.AsyncStateMachineAttribute::.ctor(class [mscorlib]System.Type) = ( 01 00 14 45 78 74 65 6e 73 69 6f 6e 73 2b 3c 4d @@ -7718,10 +7744,10 @@ .class nested public auto ansi sealed beforefieldinit '<>E__0' extends [mscorlib]System.Object { // Methods - .method private hidebysig specialname static + .method private hidebysig specialname static void '$' ( object _ - ) cil managed + ) cil managed { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 @@ -7731,11 +7757,11 @@ 01 00 00 00 .maxstack 8 IL_0000: ret } // end of method '<>E__0'::'$' - .method public hidebysig static + .method public hidebysig static string M ( object o, string s - ) cil managed + ) cil managed { // Method begins at RVA 0x207d // Code size 2 (0x2) @@ -7745,11 +7771,11 @@ .maxstack 8 } // end of method '<>E__0'::M } // end of class <>E__0 // Methods - .method public hidebysig static + .method public hidebysig static string M ( object o, string s - ) cil managed + ) cil managed { // Method begins at RVA 0x2067 // Code size 19 (0x13) @@ -8199,10 +8225,10 @@ .class nested public auto ansi sealed beforefieldinit '<>E__0' extends [mscorlib]System.Object { // Methods - .method private hidebysig specialname static + .method private hidebysig specialname static void '$' ( object _ - ) cil managed + ) cil managed { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 @@ -8212,11 +8238,11 @@ 01 00 00 00 .maxstack 8 IL_0000: ret } // end of method '<>E__0'::'$' - .method public hidebysig static + .method public hidebysig static string M ( object o, string s - ) cil managed + ) cil managed { // Method begins at RVA 0x20ad // Code size 2 (0x2) @@ -8236,11 +8262,11 @@ .field public object o .field public string s } // end of class <>c__DisplayClass1_0 // Methods - .method public hidebysig static + .method public hidebysig static string M ( object o, string s - ) cil managed + ) cil managed { // Method begins at RVA 0x2068 // Code size 24 (0x18) @@ -8258,10 +8284,10 @@ [0] valuetype Extensions/'<>c__DisplayClass1_0' IL_0012: call string Extensions::'b__1_0'(valuetype Extensions/'<>c__DisplayClass1_0'&) IL_0017: ret } // end of method Extensions::M - .method assembly hidebysig static + .method assembly hidebysig static string 'b__1_0' ( valuetype Extensions/'<>c__DisplayClass1_0'& '' - ) cil managed + ) cil managed { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 @@ -8377,10 +8403,10 @@ .class nested public auto ansi sealed beforefieldinit '<>E__0' extends [mscorlib]System.Object { // Methods - .method private hidebysig specialname static + .method private hidebysig specialname static void '$' ( object _ - ) cil managed + ) cil managed { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 @@ -8390,11 +8416,11 @@ 01 00 00 00 .maxstack 8 IL_0000: ret } // end of method '<>E__0'::'$' - .method public hidebysig static + .method public hidebysig static string M ( object o, string s - ) cil managed + ) cil managed { // Method begins at RVA 0x208e // Code size 2 (0x2) @@ -8413,8 +8439,8 @@ 01 00 00 00 .field public object o .field public string s // Methods - .method public hidebysig specialname rtspecialname - instance void .ctor () cil managed + .method public hidebysig specialname rtspecialname + instance void .ctor () cil managed { // Method begins at RVA 0x2091 // Code size 7 (0x7) @@ -8423,8 +8449,8 @@ .maxstack 8 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method '<>c__DisplayClass1_0'::.ctor - .method assembly hidebysig - instance string 'b__0' () cil managed + .method assembly hidebysig + instance string 'b__0' () cil managed { // Method begins at RVA 0x2099 // Code size 30 (0x1e) @@ -8444,11 +8470,11 @@ .maxstack 8 } // end of method '<>c__DisplayClass1_0'::'b__0' } // end of class <>c__DisplayClass1_0 // Methods - .method public hidebysig static + .method public hidebysig static string M ( object o, string s - ) cil managed + ) cil managed { // Method begins at RVA 0x2067 // Code size 36 (0x24) @@ -8563,10 +8589,10 @@ .class nested public auto ansi sealed beforefieldinit '<>E__0' extends [mscorlib]System.Object { // Methods - .method private hidebysig specialname static + .method private hidebysig specialname static void '$' ( object _ - ) cil managed + ) cil managed { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 @@ -8576,11 +8602,11 @@ 01 00 00 00 .maxstack 8 IL_0000: ret } // end of method '<>E__0'::'$' - .method public hidebysig static + .method public hidebysig static class [mscorlib]System.Collections.Generic.IEnumerable`1 M ( object o, string s - ) cil managed + ) cil managed { // Method begins at RVA 0x2080 // Code size 2 (0x2) @@ -8621,10 +8647,10 @@ .field public object '<>3__o' .field private string s .field public string '<>3__s' // Methods - .method public hidebysig specialname rtspecialname + .method public hidebysig specialname rtspecialname instance void .ctor ( int32 '<>1__state' - ) cil managed + ) cil managed { .custom instance void [mscorlib]System.Diagnostics.DebuggerHiddenAttribute::.ctor() = ( 01 00 00 00 @@ -8642,8 +8668,8 @@ .maxstack 8 IL_0013: stfld int32 Extensions/'d__1'::'<>l__initialThreadId' IL_0018: ret } // end of method 'd__1'::.ctor - .method private final hidebysig newslot virtual - instance void System.IDisposable.Dispose () cil managed + .method private final hidebysig newslot virtual + instance void System.IDisposable.Dispose () cil managed { .custom instance void [mscorlib]System.Diagnostics.DebuggerHiddenAttribute::.ctor() = ( 01 00 00 00 @@ -8657,8 +8683,8 @@ .maxstack 8 IL_0003: stfld int32 Extensions/'d__1'::'<>1__state' IL_0008: ret } // end of method 'd__1'::System.IDisposable.Dispose - .method private final hidebysig newslot virtual - instance bool MoveNext () cil managed + .method private final hidebysig newslot virtual + instance bool MoveNext () cil managed { .override method instance bool [mscorlib]System.Collections.IEnumerator::MoveNext() // Method begins at RVA 0x20a8 @@ -8704,8 +8730,8 @@ [0] int32 IL_004a: ldc.i4.0 IL_004b: ret } // end of method 'd__1'::MoveNext - .method private final hidebysig specialname newslot virtual - instance string 'System.Collections.Generic.IEnumerator.get_Current' () cil managed + .method private final hidebysig specialname newslot virtual + instance string 'System.Collections.Generic.IEnumerator.get_Current' () cil managed { .custom instance void [mscorlib]System.Diagnostics.DebuggerHiddenAttribute::.ctor() = ( 01 00 00 00 @@ -8718,8 +8744,8 @@ .maxstack 8 IL_0001: ldfld string Extensions/'d__1'::'<>2__current' IL_0006: ret } // end of method 'd__1'::'System.Collections.Generic.IEnumerator.get_Current' - .method private final hidebysig newslot virtual - instance void System.Collections.IEnumerator.Reset () cil managed + .method private final hidebysig newslot virtual + instance void System.Collections.IEnumerator.Reset () cil managed { .custom instance void [mscorlib]System.Diagnostics.DebuggerHiddenAttribute::.ctor() = ( 01 00 00 00 @@ -8731,8 +8757,8 @@ .maxstack 8 IL_0000: newobj instance void [mscorlib]System.NotSupportedException::.ctor() IL_0005: throw } // end of method 'd__1'::System.Collections.IEnumerator.Reset - .method private final hidebysig specialname newslot virtual - instance object System.Collections.IEnumerator.get_Current () cil managed + .method private final hidebysig specialname newslot virtual + instance object System.Collections.IEnumerator.get_Current () cil managed { .custom instance void [mscorlib]System.Diagnostics.DebuggerHiddenAttribute::.ctor() = ( 01 00 00 00 @@ -8745,8 +8771,8 @@ .maxstack 8 IL_0001: ldfld string Extensions/'d__1'::'<>2__current' IL_0006: ret } // end of method 'd__1'::System.Collections.IEnumerator.get_Current - .method private final hidebysig newslot virtual - instance class [mscorlib]System.Collections.Generic.IEnumerator`1 'System.Collections.Generic.IEnumerable.GetEnumerator' () cil managed + .method private final hidebysig newslot virtual + instance class [mscorlib]System.Collections.Generic.IEnumerator`1 'System.Collections.Generic.IEnumerable.GetEnumerator' () cil managed { .custom instance void [mscorlib]System.Diagnostics.DebuggerHiddenAttribute::.ctor() = ( 01 00 00 00 @@ -8786,8 +8812,8 @@ [0] class Extensions/'d__1' IL_0041: ldloc.0 IL_0042: ret } // end of method 'd__1'::'System.Collections.Generic.IEnumerable.GetEnumerator' - .method private final hidebysig newslot virtual - instance class [mscorlib]System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator () cil managed + .method private final hidebysig newslot virtual + instance class [mscorlib]System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator () cil managed { .custom instance void [mscorlib]System.Diagnostics.DebuggerHiddenAttribute::.ctor() = ( 01 00 00 00 @@ -8811,11 +8837,11 @@ .property instance object System.Collections.IEnumerator.Current() } } // end of class d__1 // Methods - .method public hidebysig static + .method public hidebysig static class [mscorlib]System.Collections.Generic.IEnumerable`1 M ( object o, string s - ) cil managed + ) cil managed { .custom instance void [mscorlib]System.Runtime.CompilerServices.IteratorStateMachineAttribute::.ctor(class [mscorlib]System.Type) = ( 01 00 12 45 78 74 65 6e 73 69 6f 6e 73 2b 3c 4d @@ -8928,10 +8954,10 @@ .class nested public auto ansi sealed beforefieldinit '<>E__0' extends [mscorlib]System.Object { // Methods - .method private hidebysig specialname static + .method private hidebysig specialname static void '$' ( object _ - ) cil managed + ) cil managed { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 @@ -8941,11 +8967,11 @@ 01 00 00 00 .maxstack 8 IL_0000: ret } // end of method '<>E__0'::'$' - .method public hidebysig static + .method public hidebysig static class [mscorlib]System.Threading.Tasks.Task`1 M ( object o, string s - ) cil managed + ) cil managed { // Method begins at RVA 0x20b5 // Code size 2 (0x2) @@ -8968,8 +8994,8 @@ .field public object o .field public string s .field private valuetype [mscorlib]System.Runtime.CompilerServices.YieldAwaitable/YieldAwaiter '<>u__1' // Methods - .method private final hidebysig newslot virtual - instance void MoveNext () cil managed + .method private final hidebysig newslot virtual + instance void MoveNext () cil managed { .override method instance void [mscorlib]System.Runtime.CompilerServices.IAsyncStateMachine::MoveNext() // Method begins at RVA 0x20b8 @@ -9059,10 +9085,10 @@ [4] class [mscorlib]System.Exception IL_00ac: call instance void valuetype [mscorlib]System.Runtime.CompilerServices.AsyncTaskMethodBuilder`1::SetResult(!0) IL_00b1: ret } // end of method 'd__1'::MoveNext - .method private final hidebysig newslot virtual + .method private final hidebysig newslot virtual instance void SetStateMachine ( class [mscorlib]System.Runtime.CompilerServices.IAsyncStateMachine stateMachine - ) cil managed + ) cil managed { .custom instance void [mscorlib]System.Diagnostics.DebuggerHiddenAttribute::.ctor() = ( 01 00 00 00 @@ -9079,11 +9105,11 @@ .maxstack 8 } // end of method 'd__1'::SetStateMachine } // end of class d__1 // Methods - .method public hidebysig static + .method public hidebysig static class [mscorlib]System.Threading.Tasks.Task`1 M ( object o, string s - ) cil managed + ) cil managed { .custom instance void [mscorlib]System.Runtime.CompilerServices.AsyncStateMachineAttribute::.ctor(class [mscorlib]System.Type) = ( 01 00 12 45 78 74 65 6e 73 69 6f 6e 73 2b 3c 4d @@ -9218,10 +9244,10 @@ .class nested public auto ansi sealed beforefieldinit '<>E__0' extends [mscorlib]System.Object { // Methods - .method private hidebysig specialname static + .method private hidebysig specialname static void '$' ( object o - ) cil managed + ) cil managed { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 @@ -9231,8 +9257,8 @@ 01 00 00 00 .maxstack 8 IL_0000: ret } // end of method '<>E__0'::'$' - .method public hidebysig specialname - instance string get_P () cil managed + .method public hidebysig specialname + instance string get_P () cil managed { // Method begins at RVA 0x2071 // Code size 2 (0x2) @@ -9247,10 +9273,10 @@ .property instance string P() } } // end of class <>E__0 // Methods - .method public hidebysig static + .method public hidebysig static string get_P ( object o - ) cil managed + ) cil managed { // Method begins at RVA 0x2067 // Code size 7 (0x7) @@ -9507,10 +9533,10 @@ .class nested public auto ansi sealed beforefieldinit '<>E__0' extends [mscorlib]System.Object { // Methods - .method private hidebysig specialname static + .method private hidebysig specialname static void '$' ( object '' - ) cil managed + ) cil managed { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 @@ -9520,8 +9546,8 @@ 01 00 00 00 .maxstack 8 IL_0000: ret } // end of method '<>E__0'::'$' - .method public hidebysig specialname static - string get_P () cil managed + .method public hidebysig specialname static + string get_P () cil managed { // Method begins at RVA 0x2070 // Code size 2 (0x2) @@ -9536,8 +9562,8 @@ .property string P() } } // end of class <>E__0 // Methods - .method public hidebysig static - string get_P () cil managed + .method public hidebysig static + string get_P () cil managed { // Method begins at RVA 0x2067 // Code size 6 (0x6) @@ -9718,10 +9744,10 @@ .class nested public auto ansi sealed beforefieldinit '<>E__0' extends [mscorlib]System.Object { // Methods - .method private hidebysig specialname static + .method private hidebysig specialname static void '$' ( object o - ) cil managed + ) cil managed { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 @@ -9731,8 +9757,8 @@ 01 00 00 00 .maxstack 8 IL_0000: ret } // end of method '<>E__0'::'$' - .method public hidebysig specialname - instance string get_P () cil managed + .method public hidebysig specialname + instance string get_P () cil managed { // Method begins at RVA 0x2071 // Code size 2 (0x2) @@ -9747,10 +9773,10 @@ .property instance string P() } } // end of class <>E__0 // Methods - .method public hidebysig static + .method public hidebysig static string get_P ( object o - ) cil managed + ) cil managed { // Method begins at RVA 0x2067 // Code size 7 (0x7) @@ -9829,13 +9855,16 @@ .maxstack 1 public void Implementation_DelegateCaching_01() { var src = """ +42.M2(); + public static class Extensions { extension(T o) { - void M2() + public void M2() { - #pragma warning disable CS8321 // The local function 'local' is declared but never used + local()(); + System.Func local() { return C1.M1; @@ -9846,11 +9875,11 @@ System.Func local() class C1 { - static public V M1() => default; + static public V M1() { System.Console.Write((typeof(T), typeof(U), typeof(V))); return default; } } """; var comp = CreateCompilation(src); - var verifier = CompileAndVerify(comp).VerifyDiagnostics(); // Tracked by https://github.com/dotnet/roslyn/issues/76130 : Consider executing and verifying behavior + var verifier = CompileAndVerify(comp, expectedOutput: "(System.Int32, System.String, System.Int64)").VerifyDiagnostics(); verifier.VerifyTypeIL("Extensions", """ .class public auto ansi abstract sealed beforefieldinit Extensions @@ -9864,23 +9893,23 @@ .class nested public auto ansi sealed beforefieldinit '<>E__0`1' extends [mscorlib]System.Object { // Methods - .method private hidebysig specialname static + .method private hidebysig specialname static void '$' ( !T o - ) cil managed + ) cil managed { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - // Method begins at RVA 0x2067 + // Method begins at RVA 0x20e7 // Code size 1 (0x1) .maxstack 8 IL_0000: ret } // end of method '<>E__0`1'::'$' - .method private hidebysig - instance void M2 () cil managed + .method public hidebysig + instance void M2 () cil managed { - // Method begins at RVA 0x20a6 + // Method begins at RVA 0x20e9 // Code size 2 (0x2) .maxstack 8 IL_0000: ldnull @@ -9897,26 +9926,29 @@ 01 00 00 00 .field public static class [mscorlib]System.Func`1 '<0>__M1' } // end of class O__1_0`3 // Methods - .method private hidebysig static + .method public hidebysig static void M2 ( !!T o - ) cil managed + ) cil managed { .custom instance void [mscorlib]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) - // Method begins at RVA 0x2067 - // Code size 1 (0x1) + // Method begins at RVA 0x2078 + // Code size 12 (0xc) .maxstack 8 - IL_0000: ret + IL_0000: call class [mscorlib]System.Func`1 Extensions::'b__1_0'() + IL_0005: callvirt instance !0 class [mscorlib]System.Func`1::Invoke() + IL_000a: pop + IL_000b: ret } // end of method Extensions::M2 - .method assembly hidebysig static - class [mscorlib]System.Func`1 'b__1_0' () cil managed + .method assembly hidebysig static + class [mscorlib]System.Func`1 'b__1_0' () cil managed { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - // Method begins at RVA 0x2069 + // Method begins at RVA 0x2085 // Code size 28 (0x1c) .maxstack 8 IL_0000: ldsfld class [mscorlib]System.Func`1 class Extensions/'O__1_0`3'::'<0>__M1' @@ -9973,13 +10005,17 @@ class C1 public void Implementation_DelegateCaching_02() { var src = """ + +42.M2(); + public static class Extensions { extension(T o) { - void M2() + public void M2() { - #pragma warning disable CS8321 // The local function 'local' is declared but never used + local()(); + System.Action local() { return C1.M1; @@ -9990,11 +10026,11 @@ System.Action local() class C1 { - static public void M1() {} + static public void M1() { System.Console.Write(typeof(T)); } } """; var comp = CreateCompilation(src); - var verifier = CompileAndVerify(comp).VerifyDiagnostics(); // Tracked by https://github.com/dotnet/roslyn/issues/76130 : Consider executing and verifying behavior + var verifier = CompileAndVerify(comp, expectedOutput: "System.Int32").VerifyDiagnostics(); verifier.VerifyTypeIL("Extensions", """ .class public auto ansi abstract sealed beforefieldinit Extensions @@ -10008,23 +10044,23 @@ .class nested public auto ansi sealed beforefieldinit '<>E__0`1' extends [mscorlib]System.Object { // Methods - .method private hidebysig specialname static + .method private hidebysig specialname static void '$' ( !T o - ) cil managed + ) cil managed { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - // Method begins at RVA 0x2067 + // Method begins at RVA 0x20b2 // Code size 1 (0x1) .maxstack 8 IL_0000: ret } // end of method '<>E__0`1'::'$' - .method private hidebysig - instance void M2 () cil managed + .method public hidebysig + instance void M2 () cil managed { - // Method begins at RVA 0x208e + // Method begins at RVA 0x20b4 // Code size 2 (0x2) .maxstack 8 IL_0000: ldnull @@ -10041,26 +10077,28 @@ 01 00 00 00 .field public static class [mscorlib]System.Action '<0>__M1' } // end of class <>O__1_0`1 // Methods - .method private hidebysig static + .method public hidebysig static void M2 ( !!T o - ) cil managed + ) cil managed { .custom instance void [mscorlib]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) - // Method begins at RVA 0x2067 - // Code size 1 (0x1) + // Method begins at RVA 0x2078 + // Code size 11 (0xb) .maxstack 8 - IL_0000: ret + IL_0000: call class [mscorlib]System.Action Extensions::'b__1_0'() + IL_0005: callvirt instance void [mscorlib]System.Action::Invoke() + IL_000a: ret } // end of method Extensions::M2 - .method assembly hidebysig static - class [mscorlib]System.Action 'b__1_0' () cil managed + .method assembly hidebysig static + class [mscorlib]System.Action 'b__1_0' () cil managed { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - // Method begins at RVA 0x2069 + // Method begins at RVA 0x2084 // Code size 28 (0x1c) .maxstack 8 IL_0000: ldsfld class [mscorlib]System.Action class Extensions/'<>O__1_0`1'::'<0>__M1' @@ -10139,7 +10177,7 @@ static public void M1() {} } """; var comp = CreateCompilation(src); - var verifier = CompileAndVerify(comp).VerifyDiagnostics(); // Tracked by https://github.com/dotnet/roslyn/issues/76130 : Consider executing and verifying behavior + var verifier = CompileAndVerify(comp).VerifyDiagnostics(); verifier.VerifyTypeIL("Extensions", """ .class public auto ansi abstract sealed beforefieldinit Extensions @@ -10153,10 +10191,10 @@ .class nested public auto ansi sealed beforefieldinit '<>E__0' extends [mscorlib]System.Object { // Methods - .method private hidebysig specialname static + .method private hidebysig specialname static void '$' ( object o - ) cil managed + ) cil managed { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 @@ -10166,8 +10204,8 @@ 01 00 00 00 .maxstack 8 IL_0000: ret } // end of method '<>E__0'::'$' - .method private hidebysig - instance void M2 () cil managed + .method private hidebysig + instance void M2 () cil managed { // Method begins at RVA 0x208e // Code size 2 (0x2) @@ -10186,10 +10224,10 @@ 01 00 00 00 .field public static class [mscorlib]System.Action '<0>__M1' } // end of class <>O // Methods - .method private hidebysig static + .method private hidebysig static void M2 ( object o - ) cil managed + ) cil managed { .custom instance void [mscorlib]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 @@ -10199,8 +10237,8 @@ 01 00 00 00 .maxstack 8 IL_0000: ret } // end of method Extensions::M2 - .method assembly hidebysig static - class [mscorlib]System.Action 'b__1_0' () cil managed + .method assembly hidebysig static + class [mscorlib]System.Action 'b__1_0' () cil managed { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 @@ -10279,7 +10317,7 @@ static void local() } """; var comp = CreateCompilation(src); - var verifier = CompileAndVerify(comp).VerifyDiagnostics(); // Tracked by https://github.com/dotnet/roslyn/issues/76130 : Consider executing and verifying behavior + var verifier = CompileAndVerify(comp).VerifyDiagnostics(); verifier.VerifyTypeIL("Extensions", """ .class public auto ansi abstract sealed beforefieldinit Extensions @@ -10293,10 +10331,10 @@ .class nested public auto ansi sealed beforefieldinit '<>E__0`1' extends [mscorlib]System.Object { // Methods - .method private hidebysig specialname static + .method private hidebysig specialname static void '$' ( !T o - ) cil managed + ) cil managed { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 @@ -10306,8 +10344,8 @@ 01 00 00 00 .maxstack 8 IL_0000: ret } // end of method '<>E__0`1'::'$' - .method private hidebysig - instance class [mscorlib]System.Action M2 () cil managed + .method private hidebysig + instance class [mscorlib]System.Action M2 () cil managed { // Method begins at RVA 0x2098 // Code size 2 (0x2) @@ -10326,10 +10364,10 @@ 01 00 00 00 .field public static class [mscorlib]System.Action '<0>__local' } // end of class <>O__1_0`1 // Methods - .method private hidebysig static + .method private hidebysig static class [mscorlib]System.Action M2 ( !!T o - ) cil managed + ) cil managed { .custom instance void [mscorlib]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 @@ -10348,8 +10386,8 @@ .maxstack 8 IL_0016: stsfld class [mscorlib]System.Action class Extensions/'<>O__1_0`1'::'<0>__local' IL_001b: ret } // end of method Extensions::M2 - .method assembly hidebysig static - void 'b__1_0' () cil managed + .method assembly hidebysig static + void 'b__1_0' () cil managed { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 @@ -10421,7 +10459,7 @@ static void local() } """; var comp = CreateCompilation(src); - var verifier = CompileAndVerify(comp).VerifyDiagnostics(); // Tracked by https://github.com/dotnet/roslyn/issues/76130 : Consider executing and verifying behavior + var verifier = CompileAndVerify(comp).VerifyDiagnostics(); verifier.VerifyTypeIL("Extensions", """ .class public auto ansi abstract sealed beforefieldinit Extensions @@ -10435,10 +10473,10 @@ .class nested public auto ansi sealed beforefieldinit '<>E__0' extends [mscorlib]System.Object { // Methods - .method private hidebysig specialname static + .method private hidebysig specialname static void '$' ( object o - ) cil managed + ) cil managed { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 @@ -10448,8 +10486,8 @@ 01 00 00 00 .maxstack 8 IL_0000: ret } // end of method '<>E__0'::'$' - .method private hidebysig - instance class [mscorlib]System.Action M2 () cil managed + .method private hidebysig + instance class [mscorlib]System.Action M2 () cil managed { // Method begins at RVA 0x2098 // Code size 2 (0x2) @@ -10468,10 +10506,10 @@ 01 00 00 00 .field public static class [mscorlib]System.Action '<0>__local' } // end of class <>O // Methods - .method private hidebysig static + .method private hidebysig static class [mscorlib]System.Action M2 ( object o - ) cil managed + ) cil managed { .custom instance void [mscorlib]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 @@ -10490,8 +10528,8 @@ .maxstack 8 IL_0016: stsfld class [mscorlib]System.Action Extensions/'<>O'::'<0>__local' IL_001b: ret } // end of method Extensions::M2 - .method assembly hidebysig static - void 'b__1_0' () cil managed + .method assembly hidebysig static + void 'b__1_0' () cil managed { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 @@ -10546,13 +10584,21 @@ static void local() public void Implementation_DynamicCallSite_01() { var src = """ +42.M2(); + +class D +{ + public void M1(T t, U u, V v) { System.Console.Write((typeof(T), typeof(U), typeof(V))); } +} + public static class Extensions { extension(T o) { - void M2() + public void M2() { - #pragma warning disable CS8321 // The local function 'local' is declared but never used + local(new D(), default(T), default(U), 42L); + void local(dynamic d, T t, U u, V v) { d.M1(t, u, v); @@ -10562,7 +10608,7 @@ void local(dynamic d, T t, U u, V v) } """; var comp = CreateCompilation(src, targetFramework: TargetFramework.StandardAndCSharp); - var verifier = CompileAndVerify(comp).VerifyDiagnostics(); // Tracked by https://github.com/dotnet/roslyn/issues/76130 : Consider executing and verifying behavior + var verifier = CompileAndVerify(comp, expectedOutput: "(System.Int32, System.String, System.Int64)").VerifyDiagnostics(); verifier.VerifyTypeIL("Extensions", """ .class public auto ansi abstract sealed beforefieldinit Extensions @@ -10576,23 +10622,23 @@ .class nested public auto ansi sealed beforefieldinit '<>E__0`1' extends [mscorlib]System.Object { // Methods - .method private hidebysig specialname static + .method private hidebysig specialname static void '$' ( !T o - ) cil managed + ) cil managed { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - // Method begins at RVA 0x2067 + // Method begins at RVA 0x2152 // Code size 1 (0x1) .maxstack 8 IL_0000: ret } // end of method '<>E__0`1'::'$' - .method private hidebysig - instance void M2 () cil managed + .method public hidebysig + instance void M2 () cil managed { - // Method begins at RVA 0x20ea + // Method begins at RVA 0x2154 // Code size 2 (0x2) .maxstack 8 IL_0000: ldnull @@ -10609,26 +10655,40 @@ 01 00 00 00 .field public static class [System.Core]System.Runtime.CompilerServices.CallSite`1> '<>p__0' } // end of class <>o__0|1`3 // Methods - .method private hidebysig static + .method public hidebysig static void M2 ( !!T o - ) cil managed + ) cil managed { .custom instance void [mscorlib]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) - // Method begins at RVA 0x2067 - // Code size 1 (0x1) - .maxstack 8 - IL_0000: ret + // Method begins at RVA 0x20a8 + // Code size 32 (0x20) + .maxstack 4 + .locals init ( + [0] !!T, + [1] !!U + ) + IL_0000: newobj instance void D::.ctor() + IL_0005: ldloca.s 0 + IL_0007: initobj !!T + IL_000d: ldloc.0 + IL_000e: ldloca.s 1 + IL_0010: initobj !!U + IL_0016: ldloc.1 + IL_0017: ldc.i4.s 42 + IL_0019: conv.i8 + IL_001a: call void Extensions::'b__1_0'(object, !!0, !!1, !!2) + IL_001f: ret } // end of method Extensions::M2 - .method assembly hidebysig static + .method assembly hidebysig static void 'b__1_0' ( object d, !!T t, !!U u, !!V v - ) cil managed + ) cil managed { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 @@ -10637,7 +10697,7 @@ .param [1] .custom instance void [System.Core]System.Runtime.CompilerServices.DynamicAttribute::.ctor() = ( 01 00 00 00 ) - // Method begins at RVA 0x206c + // Method begins at RVA 0x20d4 // Code size 114 (0x72) .maxstack 9 IL_0000: ldsfld class [System.Core]System.Runtime.CompilerServices.CallSite`1> class Extensions/'<>o__0|1`3'::'<>p__0' @@ -10741,7 +10801,7 @@ void local(dynamic d, T t) } """; var comp = CreateCompilation(src, targetFramework: TargetFramework.StandardAndCSharp); - var verifier = CompileAndVerify(comp).VerifyDiagnostics(); // Tracked by https://github.com/dotnet/roslyn/issues/76130 : Consider executing and verifying behavior + var verifier = CompileAndVerify(comp).VerifyDiagnostics(); verifier.VerifyTypeIL("Extensions", """ .class public auto ansi abstract sealed beforefieldinit Extensions @@ -10755,10 +10815,10 @@ .class nested public auto ansi sealed beforefieldinit '<>E__0`1' extends [mscorlib]System.Object { // Methods - .method private hidebysig specialname static + .method private hidebysig specialname static void '$' ( !T o - ) cil managed + ) cil managed { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 @@ -10768,8 +10828,8 @@ 01 00 00 00 .maxstack 8 IL_0000: ret } // end of method '<>E__0`1'::'$' - .method private hidebysig - instance void M2 () cil managed + .method private hidebysig + instance void M2 () cil managed { // Method begins at RVA 0x20d4 // Code size 2 (0x2) @@ -10788,10 +10848,10 @@ 01 00 00 00 .field public static class [System.Core]System.Runtime.CompilerServices.CallSite`1> '<>p__0' } // end of class <>o__1`1 // Methods - .method private hidebysig static + .method private hidebysig static void M2 ( !!T o - ) cil managed + ) cil managed { .custom instance void [mscorlib]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 @@ -10801,11 +10861,11 @@ 01 00 00 00 .maxstack 8 IL_0000: ret } // end of method Extensions::M2 - .method assembly hidebysig static + .method assembly hidebysig static void 'b__1_0' ( object d, !!T t - ) cil managed + ) cil managed { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 @@ -10904,7 +10964,7 @@ void local(dynamic d) } """; var comp = CreateCompilation(src, targetFramework: TargetFramework.StandardAndCSharp); - var verifier = CompileAndVerify(comp).VerifyDiagnostics(); // Tracked by https://github.com/dotnet/roslyn/issues/76130 : Consider executing and verifying behavior + var verifier = CompileAndVerify(comp).VerifyDiagnostics(); verifier.VerifyTypeIL("Extensions", """ .class public auto ansi abstract sealed beforefieldinit Extensions @@ -10918,10 +10978,10 @@ .class nested public auto ansi sealed beforefieldinit '<>E__0' extends [mscorlib]System.Object { // Methods - .method private hidebysig specialname static + .method private hidebysig specialname static void '$' ( object o - ) cil managed + ) cil managed { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 @@ -10931,8 +10991,8 @@ 01 00 00 00 .maxstack 8 IL_0000: ret } // end of method '<>E__0'::'$' - .method private hidebysig - instance void M2 () cil managed + .method private hidebysig + instance void M2 () cil managed { // Method begins at RVA 0x20c9 // Code size 2 (0x2) @@ -10951,10 +11011,10 @@ 01 00 00 00 .field public static class [System.Core]System.Runtime.CompilerServices.CallSite`1> '<>p__0' } // end of class <>o__1 // Methods - .method private hidebysig static + .method private hidebysig static void M2 ( object o - ) cil managed + ) cil managed { .custom instance void [mscorlib]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 @@ -10964,10 +11024,10 @@ 01 00 00 00 .maxstack 8 IL_0000: ret } // end of method Extensions::M2 - .method assembly hidebysig static + .method assembly hidebysig static void 'b__1_0' ( object d - ) cil managed + ) cil managed { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 @@ -11299,7 +11359,7 @@ static class Extensions extension(C) { } } -class C1 +class C1 { void M(UseSiteError x) { } void M(C x) { } @@ -11439,7 +11499,7 @@ static class E { extension(object o) { - public void Method() => throw null; + public void Method() { System.Console.Write("ran"); } } } } @@ -11489,9 +11549,7 @@ namespace N4 void verify(string src, string extensionName) { var comp = CreateCompilation(src, options: TestOptions.DebugExe); - comp.VerifyEmitDiagnostics(); - // Tracked by https://github.com/dotnet/roslyn/issues/76130 : metadata is undone - //CompileAndVerify(comp, expectedOutput: "").VerifyDiagnostics(); + CompileAndVerify(comp, expectedOutput: "ran").VerifyDiagnostics(); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); @@ -11531,10 +11589,7 @@ public static class E """; var comp = CreateCompilation([src, eSrc], options: TestOptions.DebugExe); - comp.VerifyEmitDiagnostics(); - - // Tracked by https://github.com/dotnet/roslyn/issues/76130 : metadata is undone - //CompileAndVerify(comp, expectedOutput: "method"); + CompileAndVerify(comp, expectedOutput: "method").VerifyDiagnostics(); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); @@ -11640,9 +11695,7 @@ static class E2 } """; var comp = CreateCompilation(src); - comp.VerifyEmitDiagnostics(); - // Tracked by https://github.com/dotnet/roslyn/issues/76130 : metadata is undone - //CompileAndVerify(comp, expectedOutput: "E1.Method(42) E2.Method(hello)").VerifyDiagnostics(); + CompileAndVerify(comp, expectedOutput: "E1.Method(42) E2.Method(hello)").VerifyDiagnostics(); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); @@ -11698,9 +11751,7 @@ public static void Main() } """; var comp = CreateCompilation(src, options: TestOptions.DebugExe); - comp.VerifyEmitDiagnostics(); - // Tracked by https://github.com/dotnet/roslyn/issues/76130 : metadata is undone - //CompileAndVerify(comp, expectedOutput: "E1.Method(42) E2.Method(hello)").VerifyDiagnostics(); + CompileAndVerify(comp, expectedOutput: "E1.Method(42) E2.Method(hello)").VerifyDiagnostics(); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); @@ -11750,9 +11801,7 @@ static class E2 } """; var comp = CreateCompilation(src); - comp.VerifyEmitDiagnostics(); - // Tracked by https://github.com/dotnet/roslyn/issues/76130 : metadata is undone - //CompileAndVerify(comp, expectedOutput: "E1.Method E2.Method E1.Method").VerifyDiagnostics(); + CompileAndVerify(comp, expectedOutput: "E1.Method E2.Method E1.Method").VerifyDiagnostics(); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); @@ -11939,12 +11988,14 @@ static class E [Fact] public void InstanceMethodInvocation_MatchingExtendedType_TypeParameterWithBaseClass() { - var src = $$""" + var src = """ +D.M(new D()); + class C { } -class D +class D : C { - void M(T t) where T : C + public static void M(T t) where T : C { t.M2(); } @@ -11954,13 +12005,12 @@ static class E { extension(C c) { - public void M2() { } + public void M2() { System.Console.Write(typeof(C)); } } } """; var comp = CreateCompilation(src); - comp.VerifyEmitDiagnostics(); - // Tracked by https://github.com/dotnet/roslyn/issues/76130 : metadata is undone + CompileAndVerify(comp, expectedOutput: "C`1[D]").VerifyDiagnostics(); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); @@ -12737,17 +12787,18 @@ static class E } [Fact] - public void InstanceMethodInvocation_PatternBased_ForEach_NoMethod() + public void InstanceMethodInvocation_PatternBased_ForEach_MoveNext() { var src = """ foreach (var x in new C()) { - System.Console.Write(x); - break; } class C { } -class D { } +class D +{ + public int Current => 42; +} static class E { @@ -12759,6 +12810,50 @@ static class E extension(D d) { public bool MoveNext() => true; + } +} +"""; + var comp = CreateCompilation(src); + comp.VerifyEmitDiagnostics( + // (1,19): error CS0117: 'D' does not contain a definition for 'MoveNext' + // foreach (var x in new C()) + Diagnostic(ErrorCode.ERR_NoSuchMember, "new C()").WithArguments("D", "MoveNext").WithLocation(1, 19), + // (1,19): error CS0202: foreach requires that the return type 'D' of 'E.extension(C).GetEnumerator()' must have a suitable public 'MoveNext' method and public 'Current' property + // foreach (var x in new C()) + Diagnostic(ErrorCode.ERR_BadGetEnumerator, "new C()").WithArguments("D", "E.extension(C).GetEnumerator()").WithLocation(1, 19) + ); + + var tree = comp.SyntaxTrees.Single(); + var model = comp.GetSemanticModel(tree); + var loop = tree.GetRoot().DescendantNodes().OfType().Single(); + Assert.Null(model.GetForEachStatementInfo(loop).GetEnumeratorMethod); + Assert.Null(model.GetForEachStatementInfo(loop).MoveNextMethod); + Assert.Null(model.GetForEachStatementInfo(loop).CurrentProperty); + } + + [Fact] + public void InstanceMethodInvocation_PatternBased_ForEach_Current() + { + var src = """ +foreach (var x in new C()) +{ +} + +class C { } +class D +{ + public bool MoveNext() => true; +} + +static class E +{ + extension(C c) + { + public D GetEnumerator() => new D(); + } + + extension(D d) + { public int Current => 42; } } @@ -12781,6 +12876,42 @@ static class E Assert.Null(model.GetForEachStatementInfo(loop).CurrentProperty); } + [Fact] + public void InstanceMethodInvocation_PatternBased_ForEach_GetEnumerator_Conversion() + { + var src = """ +foreach (var x in new C()) +{ + System.Console.Write(x); + break; +} + +class C { } +class D +{ + public bool MoveNext() => true; + public int Current => 42; +} + +static class E +{ + extension(object o) + { + public D GetEnumerator() => new D(); + } +} +"""; + try + { + // Tracked by https://github.com/dotnet/roslyn/issues/76130 : assertion in NullableWalker + var comp = CreateCompilation(src); + CompileAndVerify(comp, expectedOutput: "42").VerifyDiagnostics(); + } + catch (InvalidOperationException) + { + } + } + [Fact] public void InstanceMethodInvocation_NameOf_SingleParameter() { @@ -12811,10 +12942,10 @@ static class E [Fact] public void InstanceMethodInvocation_Simple_ExpressionTree() { - // Tracked by https://github.com/dotnet/roslyn/issues/76130 : Verify shape of the tree if we decide to allow var source = """ using System.Linq.Expressions; Expression x = () => new C().M(42); +System.Console.Write(x.Dump()); System.Action a = x.Compile(); a(); @@ -12827,13 +12958,12 @@ static class E { extension(C c) { - public void M(int i) { System.Console.Write("ran"); } + public void M(int i) { System.Console.Write(" ran"); } } } """; - var comp = CreateCompilation(source); - comp.VerifyEmitDiagnostics(); - CompileAndVerify(comp, expectedOutput: "ran").VerifyDiagnostics(); + var comp = CreateCompilation([source, ExpressionTestLibrary]); + CompileAndVerify(comp, expectedOutput: "Call(null.[Void M(C, Int32)](New([Void .ctor()]() Type:C), Constant(42 Type:System.Int32)) Type:System.Void) ran").VerifyDiagnostics(); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); @@ -15711,7 +15841,7 @@ public class MyCollection : IEnumerable } [Fact] - public void ResolveAll_CollectionExpression_ExtensionAddDelegateTypeProperty() + public void ResolveAll_CollectionExpression_ExtensionAdd_DelegateTypeProperty() { var source = """ using System.Collections; @@ -15739,6 +15869,74 @@ public class MyCollection : IEnumerable // MyCollection c = [42]; Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "[42]").WithArguments("MyCollection", "Add").WithLocation(4, 18) ); + + source = """ +using System.Collections; +using System.Collections.Generic; + +MyCollection c = [42]; + +public class MyCollection : IEnumerable +{ + IEnumerator IEnumerable.GetEnumerator() => throw null; + IEnumerator IEnumerable.GetEnumerator() => throw null; + public System.Action Add => (int i) => { }; +} +"""; + comp = CreateCompilation(source); + comp.VerifyEmitDiagnostics( + // (4,18): error CS0118: 'Add' is a property but is used like a method + // MyCollection c = [42]; + Diagnostic(ErrorCode.ERR_BadSKknown, "[42]").WithArguments("Add", "property", "method").WithLocation(4, 18)); + } + + [Fact] + public void ResolveAll_CollectionExpression_ExtensionAdd_DynamicTypeProperty() + { + var source = """ +using System.Collections; +using System.Collections.Generic; + +MyCollection c = [42]; + +static class E +{ + extension(MyCollection c) + { + public dynamic Add => throw null; + } +} + +public class MyCollection : IEnumerable +{ + IEnumerator IEnumerable.GetEnumerator() => throw null; + IEnumerator IEnumerable.GetEnumerator() => throw null; +} +"""; + var comp = CreateCompilation(source); + comp.VerifyEmitDiagnostics( + // (4,18): error CS1061: 'MyCollection' does not contain a definition for 'Add' and no accessible extension method 'Add' accepting a first argument of type 'MyCollection' could be found (are you missing a using directive or an assembly reference?) + // MyCollection c = [42]; + Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "[42]").WithArguments("MyCollection", "Add").WithLocation(4, 18)); + + source = """ +using System.Collections; +using System.Collections.Generic; + +MyCollection c = [42]; + +public class MyCollection : IEnumerable +{ + IEnumerator IEnumerable.GetEnumerator() => throw null; + IEnumerator IEnumerable.GetEnumerator() => throw null; + public dynamic Add => throw null; +} +"""; + comp = CreateCompilation(source); + comp.VerifyEmitDiagnostics( + // (4,18): error CS0118: 'Add' is a property but is used like a method + // MyCollection c = [42]; + Diagnostic(ErrorCode.ERR_BadSKknown, "[42]").WithArguments("Add", "property", "method").WithLocation(4, 18)); } [Fact] @@ -16155,6 +16353,86 @@ static class E Assert.Equal("System.String E.<>E__0.M { get; }", model.GetSymbolInfo(memberAccess).Symbol.ToTestDisplayString()); } + [Fact] + public void ResolveAll_Query_Where_DelegateTypeProperty() + { + var src = """ +var x = from i in new C() + where i is not null + select i; + +System.Console.Write(x); + +public class C { } + +public static class E +{ + extension(C c) + { + public System.Func, C> Where => (System.Func f) => { System.Console.Write(f(c)); return c; }; + } +} +"""; + var comp = CreateCompilation(src); + CompileAndVerify(comp, expectedOutput: "TrueC").VerifyDiagnostics(); + + src = """ +var x = from i in new C() + where i is not null + select i; + +System.Console.Write(x); + +public class C +{ + public System.Func, C> Where => (System.Func f) => { System.Console.Write(f(this)); return this; }; +} +"""; + comp = CreateCompilation(src); + CompileAndVerify(comp, expectedOutput: "TrueC").VerifyDiagnostics(); + } + + [Fact] + public void ResolveAll_Query_Where_DynamicTypeProperty() + { + var src = """ +var x = from i in new C() + where i is not null + select i; + +public class C { } + +public static class E +{ + extension(C c) + { + public dynamic Where => throw null; + } +} +"""; + var comp = CreateCompilation(src); + comp.VerifyEmitDiagnostics( + // (2,15): error CS1977: Cannot use a lambda expression as an argument to a dynamically dispatched operation without first casting it to a delegate or expression tree type. + // where i is not null + Diagnostic(ErrorCode.ERR_BadDynamicMethodArgLambda, "i is not null").WithLocation(2, 15)); + + src = """ +var x = from i in new C() + where i is not null + select i; + +public class C +{ + public dynamic Where => throw null; +} +"""; + comp = CreateCompilation(src); + comp.VerifyEmitDiagnostics( + // (2,9): error CS1979: Query expressions over source type 'dynamic' or with a join sequence of type 'dynamic' are not allowed + // where i is not null + Diagnostic(ErrorCode.ERR_BadDynamicQuery, "where i is not null").WithLocation(2, 9)); + } + [Fact(Skip = "Tracked by https://github.com/dotnet/roslyn/issues/76130 : WasPropertyBackingFieldAccessChecked asserts that we're setting twice")] public void ResolveAll_Query_Cast() { @@ -18268,7 +18546,7 @@ static class E """; // Note: we apply the same conversion requirements even though no conversion on the receiver - // is needed in a static scenario. + // is needed in a static scenario. var comp = CreateCompilation(source, targetFramework: TargetFramework.Net90); comp.VerifyEmitDiagnostics( // (1,36): error CS0117: 'Span' does not contain a definition for 'M' @@ -18496,20 +18774,21 @@ public void StaticPropertyAccess_RefProperty_02() { var src = """ localFuncRef(ref object.Property); +System.Console.Write(E.field); -void localFuncRef(ref int i) => throw null; +void localFuncRef(ref int i) { i++; } static class E { + public static int field = 42; extension(object) { - public static ref int Property { get => throw null; } + public static ref int Property { get => ref E.field; } } } """; var comp = CreateCompilation(src); - comp.VerifyEmitDiagnostics(); - // Tracked by https://github.com/dotnet/roslyn/issues/76130 : metadata is undone + CompileAndVerify(comp, expectedOutput: "43").VerifyDiagnostics(); } [Fact] @@ -19951,11 +20230,12 @@ static class E } [Fact] - public void ExtensionMemberLookup_PatternBased_Deconstruct_NoMethod() + public void ExtensionMemberLookup_PatternBased_ForEach_DelegateTypeProperty() { var src = """ -var (x, y) = new C(); -System.Console.Write((x, y)); +using System.Collections; + +foreach (var x in new C()) { } class C { } @@ -19963,171 +20243,159 @@ static class E { extension(C c) { - public void Deconstruct(out int i, out int j) { i = 42; j = 43; } + public System.Func GetEnumerator => throw null; } } """; var comp = CreateCompilation(src); - // Tracked by https://github.com/dotnet/roslyn/issues/76130 : confirm when spec'ing pattern-based deconstruction - CompileAndVerify(comp, expectedOutput: "(42, 43)").VerifyDiagnostics(); + comp.VerifyEmitDiagnostics( + // (3,19): error CS1579: foreach statement cannot operate on variables of type 'C' because 'C' does not contain a public instance or extension definition for 'GetEnumerator' + // foreach (var x in new C()) { } + Diagnostic(ErrorCode.ERR_ForEachMissingMember, "new C()").WithArguments("C", "GetEnumerator").WithLocation(3, 19)); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); - var deconstruction = tree.GetRoot().DescendantNodes().OfType().First(); + var loop = tree.GetRoot().DescendantNodes().OfType().Single(); + Assert.Null(model.GetForEachStatementInfo(loop).GetEnumeratorMethod); - Assert.Equal("void E.<>E__0.Deconstruct(out System.Int32 i, out System.Int32 j)", - model.GetDeconstructionInfo(deconstruction).Method.ToTestDisplayString()); + src = """ +using System.Collections; + +foreach (var x in new C()) { } + +class C +{ + public System.Func GetEnumerator => throw null; +} +"""; + comp = CreateCompilation(src); + comp.VerifyEmitDiagnostics( + // (3,19): warning CS0280: 'C' does not implement the 'collection' pattern. 'C.GetEnumerator' has the wrong signature. + // foreach (var x in new C()) { } + Diagnostic(ErrorCode.WRN_PatternBadSignature, "new C()").WithArguments("C", "collection", "C.GetEnumerator").WithLocation(3, 19), + // (3,19): error CS1579: foreach statement cannot operate on variables of type 'C' because 'C' does not contain a public instance or extension definition for 'GetEnumerator' + // foreach (var x in new C()) { } + Diagnostic(ErrorCode.ERR_ForEachMissingMember, "new C()").WithArguments("C", "GetEnumerator").WithLocation(3, 19)); } [Fact] - public void ExtensionMemberLookup_PatternBased_Deconstruct_FallbackToExtensionMethod() + public void ExtensionMemberLookup_PatternBased_ForEach_GetEnumerator_DynamicTypeProperty() { - // If the method from the extension type is not applicable, we fall back - // to a Deconstruct extension method var src = """ -var (x, y) = new C(); -System.Console.Write((x, y)); +using System.Collections; -public class C { } +foreach (var x in new C()) { } + +class C { } static class E { extension(C c) { - public void Deconstruct(int inapplicable) => throw null; + public dynamic GetEnumerator => throw null; } } - -public static class E2 -{ - public static void Deconstruct(this C c, out int i, out int j) { i = 42; j = 43; } -} """; var comp = CreateCompilation(src); - // Tracked by https://github.com/dotnet/roslyn/issues/76130 : confirm when spec'ing pattern-based deconstruction - CompileAndVerify(comp, expectedOutput: "(42, 43)").VerifyDiagnostics(); + comp.VerifyEmitDiagnostics( + // (3,19): error CS1579: foreach statement cannot operate on variables of type 'C' because 'C' does not contain a public instance or extension definition for 'GetEnumerator' + // foreach (var x in new C()) { } + Diagnostic(ErrorCode.ERR_ForEachMissingMember, "new C()").WithArguments("C", "GetEnumerator").WithLocation(3, 19)); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); - var deconstruction = tree.GetRoot().DescendantNodes().OfType().First(); + var loop = tree.GetRoot().DescendantNodes().OfType().Single(); + Assert.Null(model.GetForEachStatementInfo(loop).GetEnumeratorMethod); - Assert.Equal("void E2.Deconstruct(this C c, out System.Int32 i, out System.Int32 j)", - model.GetDeconstructionInfo(deconstruction).Method.ToTestDisplayString()); + src = """ +foreach (var x in new C()) { } + +class C +{ + public dynamic GetEnumerator => throw null; +} +"""; + comp = CreateCompilation(src); + comp.VerifyEmitDiagnostics( + // (1,19): warning CS0280: 'C' does not implement the 'collection' pattern. 'C.GetEnumerator' has the wrong signature. + // foreach (var x in new C()) { } + Diagnostic(ErrorCode.WRN_PatternBadSignature, "new C()").WithArguments("C", "collection", "C.GetEnumerator").WithLocation(1, 19), + // (1,19): error CS1579: foreach statement cannot operate on variables of type 'C' because 'C' does not contain a public instance or extension definition for 'GetEnumerator' + // foreach (var x in new C()) { } + Diagnostic(ErrorCode.ERR_ForEachMissingMember, "new C()").WithArguments("C", "GetEnumerator").WithLocation(1, 19)); } [Fact] - public void ExtensionMemberLookup_PatternBased_Deconstruct_DelegateTypeProperty() + public void ExtensionMemberLookup_PatternBased_ForEach_GetEnumerator_Generic() { var src = """ -var (x1, y1) = new C1(); - -var (x2, y2) = new C2(); - -class C1 { } +using System.Collections.Generic; -class C2 -{ - public D Deconstruct => (out int i, out int j) => { i = 42; j = 43; }; -} +foreach (var x in new C()) { System.Console.Write(x); } -delegate void D(out int i, out int j); +class C { } static class E { - extension(C1 c) + extension(T t) { - public D Deconstruct => (out int i, out int j) => { i = 42; j = 43; }; + public IEnumerator GetEnumerator() + { + yield return t; + } } } """; var comp = CreateCompilation(src); - // Tracked by https://github.com/dotnet/roslyn/issues/76130 : revisit pattern-based deconstruction - comp.VerifyDiagnostics( - // (1,6): error CS8130: Cannot infer the type of implicitly-typed deconstruction variable 'x1'. - // var (x1, y1) = new C1(); - Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedDeconstructionVariable, "x1").WithArguments("x1").WithLocation(1, 6), - // (1,10): error CS8130: Cannot infer the type of implicitly-typed deconstruction variable 'y1'. - // var (x1, y1) = new C1(); - Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedDeconstructionVariable, "y1").WithArguments("y1").WithLocation(1, 10), - - // Tracked by https://github.com/dotnet/roslyn/issues/76130 : It looks like the following error is not reported for instance scenario. Noise? - - // (1,16): error CS1061: 'C1' does not contain a definition for 'Deconstruct' and no accessible extension method 'Deconstruct' accepting a first argument of type 'C1' could be found (are you missing a using directive or an assembly reference?) - // var (x1, y1) = new C1(); - Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "new C1()").WithArguments("C1", "Deconstruct").WithLocation(1, 16), - - // (1,16): error CS8129: No suitable 'Deconstruct' instance or extension method was found for type 'C1', with 2 out parameters and a void return type. - // var (x1, y1) = new C1(); - Diagnostic(ErrorCode.ERR_MissingDeconstruct, "new C1()").WithArguments("C1", "2").WithLocation(1, 16), - // (3,6): error CS8130: Cannot infer the type of implicitly-typed deconstruction variable 'x2'. - // var (x2, y2) = new C2(); - Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedDeconstructionVariable, "x2").WithArguments("x2").WithLocation(3, 6), - // (3,10): error CS8130: Cannot infer the type of implicitly-typed deconstruction variable 'y2'. - // var (x2, y2) = new C2(); - Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedDeconstructionVariable, "y2").WithArguments("y2").WithLocation(3, 10), - // (3,16): error CS8129: No suitable 'Deconstruct' instance or extension method was found for type 'C2', with 2 out parameters and a void return type. - // var (x2, y2) = new C2(); - Diagnostic(ErrorCode.ERR_MissingDeconstruct, "new C2()").WithArguments("C2", "2").WithLocation(3, 16) - ); + CompileAndVerify(comp, expectedOutput: "C").VerifyDiagnostics(); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); - var deconstruction = tree.GetRoot().DescendantNodes().OfType().First(); - - Assert.Null(model.GetDeconstructionInfo(deconstruction).Method); + var loop = tree.GetRoot().DescendantNodes().OfType().Single(); + Assert.Equal("System.Collections.Generic.IEnumerator E.<>E__0.GetEnumerator()", + model.GetForEachStatementInfo(loop).GetEnumeratorMethod.ToTestDisplayString()); } [Fact] - public void ExtensionMemberLookup_PatternBased_Deconstruct_DynamicProperty() + public void ExtensionMemberLookup_PatternBased_AwaitForEach_GetAsyncEnumerator() { var src = """ -var (x, y) = new C(); +using System.Collections.Generic; + +await foreach (var x in new C()) { System.Console.Write(x); } class C { } static class E { - extension(C c) + extension(T t) { - public dynamic Deconstruct => throw null; + public async IAsyncEnumerator GetAsyncEnumerator() + { + await System.Threading.Tasks.Task.Yield(); + yield return t; + } } } """; - var comp = CreateCompilation(src); - // Tracked by https://github.com/dotnet/roslyn/issues/76130 : revisit pattern-based deconstruction - comp.VerifyEmitDiagnostics( - // (1,6): error CS8130: Cannot infer the type of implicitly-typed deconstruction variable 'x'. - // var (x, y) = new C(); - Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedDeconstructionVariable, "x").WithArguments("x").WithLocation(1, 6), - // (1,9): error CS8130: Cannot infer the type of implicitly-typed deconstruction variable 'y'. - // var (x, y) = new C(); - Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedDeconstructionVariable, "y").WithArguments("y").WithLocation(1, 9), - // (1,14): error CS1061: 'C' does not contain a definition for 'Deconstruct' and no accessible extension method 'Deconstruct' accepting a first argument of type 'C' could be found (are you missing a using directive or an assembly reference?) - // var (x, y) = new C(); - Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "new C()").WithArguments("C", "Deconstruct").WithLocation(1, 14), - // (1,14): error CS8129: No suitable 'Deconstruct' instance or extension method was found for type 'C', with 2 out parameters and a void return type. - // var (x, y) = new C(); - Diagnostic(ErrorCode.ERR_MissingDeconstruct, "new C()").WithArguments("C", "2").WithLocation(1, 14) - ); + var comp = CreateCompilation(src, targetFramework: TargetFramework.Net90); + CompileAndVerify(comp, expectedOutput: ExpectedOutput("C"), verify: Verification.FailsPEVerify).VerifyDiagnostics(); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); - var deconstruction = tree.GetRoot().DescendantNodes().OfType().First(); - - Assert.Null(model.GetDeconstructionInfo(deconstruction).Method); + var loop = tree.GetRoot().DescendantNodes().OfType().Single(); + Assert.Equal("System.Collections.Generic.IAsyncEnumerator E.<>E__0.GetAsyncEnumerator()", + model.GetForEachStatementInfo(loop).GetEnumeratorMethod.ToTestDisplayString()); } [Fact] - public void ExtensionMemberLookup_PatternBased_Deconstruct_NoApplicableMethod() + public void ExtensionMemberLookup_PatternBased_Deconstruct_NoMethod() { var src = """ var (x, y) = new C(); System.Console.Write((x, y)); -class C -{ - public void Deconstruct() { } // not applicable -} +class C { } static class E { @@ -20137,7 +20405,6 @@ static class E } } """; - // Tracked by https://github.com/dotnet/roslyn/issues/76130 : confirm when spec'ing pattern-based deconstruction var comp = CreateCompilation(src); CompileAndVerify(comp, expectedOutput: "(42, 43)").VerifyDiagnostics(); @@ -20150,7 +20417,245 @@ static class E } [Fact] - public void ExtensionMemberLookup_PatternBased_Dispose_Async_NoMethod() + public void ExtensionMemberLookup_PatternBased_Deconstruct_Conversion() + { + var src = """ +var (x, y) = new C(); +System.Console.Write((x, y)); + +class C { } + +static class E +{ + extension(object o) + { + public void Deconstruct(out int i, out int j) { i = 42; j = 43; } + } +} +"""; + var comp = CreateCompilation(src); + CompileAndVerify(comp, expectedOutput: "(42, 43)").VerifyDiagnostics(); + } + + [Fact] + public void ExtensionMemberLookup_PatternBased_Deconstruct_Generic() + { + var src = """ +var (x, y) = new C(); +System.Console.Write((x, y)); + +class C { } + +static class E +{ + extension(T t) + { + public void Deconstruct(out int i, out int j) { i = 42; j = 43; } + } +} +"""; + var comp = CreateCompilation(src); + CompileAndVerify(comp, expectedOutput: "(42, 43)").VerifyDiagnostics(); + + var tree = comp.SyntaxTrees.Single(); + var model = comp.GetSemanticModel(tree); + var deconstruction = tree.GetRoot().DescendantNodes().OfType().First(); + + Assert.Equal("void E.<>E__0.Deconstruct(out System.Int32 i, out System.Int32 j)", + model.GetDeconstructionInfo(deconstruction).Method.ToTestDisplayString()); + } + + [Fact] + public void ExtensionMemberLookup_PatternBased_Deconstruct_FallbackToExtensionMethod() + { + // If the method from the extension type is not applicable, we fall back + // to a Deconstruct extension method + var src = """ +var (x, y) = new C(); +System.Console.Write((x, y)); + +public class C { } + +static class E +{ + extension(C c) + { + public void Deconstruct(int inapplicable) => throw null; + } +} + +public static class E2 +{ + public static void Deconstruct(this C c, out int i, out int j) { i = 42; j = 43; } +} +"""; + var comp = CreateCompilation(src); + CompileAndVerify(comp, expectedOutput: "(42, 43)").VerifyDiagnostics(); + + var tree = comp.SyntaxTrees.Single(); + var model = comp.GetSemanticModel(tree); + var deconstruction = tree.GetRoot().DescendantNodes().OfType().First(); + + Assert.Equal("void E2.Deconstruct(this C c, out System.Int32 i, out System.Int32 j)", + model.GetDeconstructionInfo(deconstruction).Method.ToTestDisplayString()); + } + + [Fact] + public void ExtensionMemberLookup_PatternBased_Deconstruct_DelegateTypeProperty() + { + var src = """ +var (x1, y1) = new C1(); + +var (x2, y2) = new C2(); + +class C1 { } + +class C2 +{ + public D Deconstruct => (out int i, out int j) => { i = 42; j = 43; }; +} + +delegate void D(out int i, out int j); + +static class E +{ + extension(C1 c) + { + public D Deconstruct => (out int i, out int j) => { i = 42; j = 43; }; + } +} +"""; + var comp = CreateCompilation(src); + comp.VerifyDiagnostics( + // (1,6): error CS8130: Cannot infer the type of implicitly-typed deconstruction variable 'x1'. + // var (x1, y1) = new C1(); + Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedDeconstructionVariable, "x1").WithArguments("x1").WithLocation(1, 6), + // (1,10): error CS8130: Cannot infer the type of implicitly-typed deconstruction variable 'y1'. + // var (x1, y1) = new C1(); + Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedDeconstructionVariable, "y1").WithArguments("y1").WithLocation(1, 10), + + // Tracked by https://github.com/dotnet/roslyn/issues/76130 : It looks like the following error is not reported for instance scenario. Noise? + + // (1,16): error CS1061: 'C1' does not contain a definition for 'Deconstruct' and no accessible extension method 'Deconstruct' accepting a first argument of type 'C1' could be found (are you missing a using directive or an assembly reference?) + // var (x1, y1) = new C1(); + Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "new C1()").WithArguments("C1", "Deconstruct").WithLocation(1, 16), + + // (1,16): error CS8129: No suitable 'Deconstruct' instance or extension method was found for type 'C1', with 2 out parameters and a void return type. + // var (x1, y1) = new C1(); + Diagnostic(ErrorCode.ERR_MissingDeconstruct, "new C1()").WithArguments("C1", "2").WithLocation(1, 16), + // (3,6): error CS8130: Cannot infer the type of implicitly-typed deconstruction variable 'x2'. + // var (x2, y2) = new C2(); + Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedDeconstructionVariable, "x2").WithArguments("x2").WithLocation(3, 6), + // (3,10): error CS8130: Cannot infer the type of implicitly-typed deconstruction variable 'y2'. + // var (x2, y2) = new C2(); + Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedDeconstructionVariable, "y2").WithArguments("y2").WithLocation(3, 10), + // (3,16): error CS8129: No suitable 'Deconstruct' instance or extension method was found for type 'C2', with 2 out parameters and a void return type. + // var (x2, y2) = new C2(); + Diagnostic(ErrorCode.ERR_MissingDeconstruct, "new C2()").WithArguments("C2", "2").WithLocation(3, 16) + ); + + var tree = comp.SyntaxTrees.Single(); + var model = comp.GetSemanticModel(tree); + var deconstruction = tree.GetRoot().DescendantNodes().OfType().First(); + + Assert.Null(model.GetDeconstructionInfo(deconstruction).Method); + } + + [Fact] + public void ExtensionMemberLookup_PatternBased_Deconstruct_DynamicProperty() + { + var src = """ +var (x, y) = new C(); + +class C { } + +static class E +{ + extension(C c) + { + public dynamic Deconstruct => throw null; + } +} +"""; + var comp = CreateCompilation(src); + // Tracked by https://github.com/dotnet/roslyn/issues/76130 : revisit pattern-based deconstruction + comp.VerifyEmitDiagnostics( + // (1,6): error CS8130: Cannot infer the type of implicitly-typed deconstruction variable 'x'. + // var (x, y) = new C(); + Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedDeconstructionVariable, "x").WithArguments("x").WithLocation(1, 6), + // (1,9): error CS8130: Cannot infer the type of implicitly-typed deconstruction variable 'y'. + // var (x, y) = new C(); + Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedDeconstructionVariable, "y").WithArguments("y").WithLocation(1, 9), + // (1,14): error CS1061: 'C' does not contain a definition for 'Deconstruct' and no accessible extension method 'Deconstruct' accepting a first argument of type 'C' could be found (are you missing a using directive or an assembly reference?) + // var (x, y) = new C(); + Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "new C()").WithArguments("C", "Deconstruct").WithLocation(1, 14), + // (1,14): error CS8129: No suitable 'Deconstruct' instance or extension method was found for type 'C', with 2 out parameters and a void return type. + // var (x, y) = new C(); + Diagnostic(ErrorCode.ERR_MissingDeconstruct, "new C()").WithArguments("C", "2").WithLocation(1, 14) + ); + + var tree = comp.SyntaxTrees.Single(); + var model = comp.GetSemanticModel(tree); + var deconstruction = tree.GetRoot().DescendantNodes().OfType().First(); + + Assert.Null(model.GetDeconstructionInfo(deconstruction).Method); + } + + [Fact] + public void ExtensionMemberLookup_PatternBased_Deconstruct_NoApplicableMethod() + { + var src = """ +var (x, y) = new C(); +System.Console.Write((x, y)); + +class C +{ + public void Deconstruct() { } // not applicable +} + +static class E +{ + extension(C c) + { + public void Deconstruct(out int i, out int j) { i = 42; j = 43; } + } +} +"""; + var comp = CreateCompilation(src); + CompileAndVerify(comp, expectedOutput: "(42, 43)").VerifyDiagnostics(); + + var tree = comp.SyntaxTrees.Single(); + var model = comp.GetSemanticModel(tree); + var deconstruction = tree.GetRoot().DescendantNodes().OfType().First(); + + Assert.Equal("void E.<>E__0.Deconstruct(out System.Int32 i, out System.Int32 j)", + model.GetDeconstructionInfo(deconstruction).Method.ToTestDisplayString()); + } + + [Fact] + public void ExtensionMemberLookup_PatternBased_PositionalPattern() + { + var src = """ +var c = new C(); +if (c is var (x, y)) + System.Console.Write((x, y)); + +class C { } + +static class E +{ + extension(T t) + { + public void Deconstruct(out int i, out int j) { i = 42; j = 43; } + } +} +"""; + var comp = CreateCompilation(src); + CompileAndVerify(comp, expectedOutput: "(42, 43)").VerifyDiagnostics(); + } + + [Fact] + public void ExtensionMemberLookup_PatternBased_DisposeAsync_NoMethod() { var src = """ using System.Threading.Tasks; @@ -20168,22 +20673,13 @@ static class E { extension(C1 c) { - public async Task DisposeAsync() - { - System.Console.Write("RAN"); - await Task.Yield(); - } + public Task DisposeAsync() => throw null; } - public static async Task DisposeAsync(this C2 c) - { - System.Console.Write("RAN"); - await Task.Yield(); - } + public static Task DisposeAsync(this C2 c) => throw null; } """; var comp = CreateCompilation(src); - // Tracked by https://github.com/dotnet/roslyn/issues/76130 : confirm when spec'ing pattern-based disposal var expectedDiagnostics = new[] { // (4,1): error CS8410: 'C1': type used in an asynchronous using statement must implement 'System.IAsyncDisposable' or implement a suitable 'DisposeAsync' method. @@ -20284,12 +20780,11 @@ static class E { extension(C c) { - public System.Func DisposeAsync => async () => { System.Console.Write("ran2"); await Task.Yield(); }; + public System.Func DisposeAsync => async () => { await Task.Yield(); }; } } """; var comp = CreateCompilation(src); - // Tracked by https://github.com/dotnet/roslyn/issues/76130 :(instance) confirm when spec'ing pattern-based disposal comp.VerifyEmitDiagnostics( // (3,1): error CS8410: 'C': type used in an asynchronous using statement must implement 'System.IAsyncDisposable' or implement a suitable 'DisposeAsync' method. // await using var x = new C(); @@ -20324,7 +20819,6 @@ public async Task DisposeAsync() } } """; - // Tracked by https://github.com/dotnet/roslyn/issues/76130 : confirm when spec'ing pattern-based disposal var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (4,1): error CS8410: 'C': type used in an asynchronous using statement must implement 'System.IAsyncDisposable' or implement a suitable 'DisposeAsync' method. @@ -20370,7 +20864,44 @@ public static void Dispose(this S2 s) { } } [Fact] - public void ExtensionMemberLookup_PatternBased_Fixed_NoMethod() + public void ExtensionMemberLookup_PatternBased_Dispose_RefStruct_DelegateTypeProperty() + { + var src = """ +using var x1 = new S1(); + +ref struct S1 { } + +static class E +{ + extension(S1 s) + { + public System.Action Dispose => throw null; + } +} +"""; + var comp = CreateCompilation(src); + comp.VerifyDiagnostics( + // (1,1): error CS1674: 'S1': type used in a using statement must implement 'System.IDisposable'. + // using var x1 = new S1(); + Diagnostic(ErrorCode.ERR_NoConvToIDisp, "using var x1 = new S1();").WithArguments("S1").WithLocation(1, 1)); + + src = """ +using var x1 = new S1(); + +ref struct S1 +{ + public System.Action Dispose => throw null; +} +"""; + comp = CreateCompilation(src); + comp.VerifyDiagnostics( + // (1,1): error CS1674: 'S1': type used in a using statement must implement 'System.IDisposable'. + // using var x1 = new S1(); + Diagnostic(ErrorCode.ERR_NoConvToIDisp, "using var x1 = new S1();").WithArguments("S1").WithLocation(1, 1)); + } + + [Fact] + public void ExtensionMemberLookup_PatternBased_Fixed_01() { var text = """ unsafe class C @@ -20395,13 +20926,40 @@ static class E } """; var comp = CreateCompilation(text, options: TestOptions.UnsafeReleaseExe); - // Tracked by https://github.com/dotnet/roslyn/issues/76130 : confirm when spec'ing pattern-based fixed - comp.VerifyEmitDiagnostics(); - // Tracked by https://github.com/dotnet/roslyn/issues/76130 : metadata is undone + CompileAndVerify(comp, expectedOutput: "pin 2", verify: Verification.Skipped).VerifyDiagnostics(); + } + + [Fact] + public void ExtensionMemberLookup_PatternBased_Fixed_02_Conversion() + { + var text = """ +unsafe class C +{ + public static void Main() + { + fixed (int* p = new Fixable()) + { + System.Console.WriteLine(p[1]); + } + } +} + +class Fixable { } + +static class E +{ + extension(object o) + { + public ref int GetPinnableReference() { System.Console.Write("pin "); return ref (new int[] { 1, 2, 3 })[0]; } + } +} +"""; + var comp = CreateCompilation(text, options: TestOptions.UnsafeReleaseExe); + CompileAndVerify(comp, expectedOutput: "pin 2", verify: Verification.Skipped).VerifyDiagnostics(); } [Fact] - public void ExtensionMemberLookup_PatternBased_Fixed_NoMethod_DelegateTypeProperty() + public void ExtensionMemberLookup_PatternBased_Fixed_03_DelegateTypeProperty() { var text = @" unsafe class C @@ -20422,389 +20980,1217 @@ public static void Main() class Fixable1 { } -class Fixable2 +class Fixable2 +{ + public MyDelegate GetPinnableReference => throw null; +} + +delegate ref int MyDelegate(); + +static class E +{ + extension(Fixable1 f) + { + public MyDelegate GetPinnableReference => throw null; + } +} +"; + var comp = CreateCompilation(text, options: TestOptions.UnsafeReleaseExe); + comp.VerifyEmitDiagnostics( + // (6,25): error CS8385: The given expression cannot be used in a fixed statement + // fixed (int* p = new Fixable1()) + Diagnostic(ErrorCode.ERR_ExprCannotBeFixed, "new Fixable1()").WithLocation(6, 25), + // (11,25): error CS8385: The given expression cannot be used in a fixed statement + // fixed (int* p = new Fixable2()) + Diagnostic(ErrorCode.ERR_ExprCannotBeFixed, "new Fixable2()").WithLocation(11, 25) + ); + } + + [Fact] + public void ExtensionMemberLookup_PatternBased_Fixed_04_DynamicTypeProperty() + { + var text = @" +unsafe class C +{ + public static void Main() + { + fixed (int* p = new Fixable1()) + { + } + } +} + +class Fixable1 { } + +delegate ref int MyDelegate(); + +static class E +{ + extension(Fixable1 f) + { + public dynamic GetPinnableReference => throw null; + } +} +"; + var comp = CreateCompilation(text, options: TestOptions.UnsafeReleaseExe); + comp.VerifyEmitDiagnostics( + // (6,25): error CS8385: The given expression cannot be used in a fixed statement + // fixed (int* p = new Fixable1()) + Diagnostic(ErrorCode.ERR_ExprCannotBeFixed, "new Fixable1()").WithLocation(6, 25)); + + text = @" +unsafe class C +{ + public static void Main() + { + fixed (int* p = new Fixable1()) + { + } + } +} + +class Fixable1 +{ + public dynamic GetPinnableReference => throw null; +} + +delegate ref int MyDelegate(); +"; + comp = CreateCompilation(text, options: TestOptions.UnsafeReleaseExe); + comp.VerifyEmitDiagnostics( + // (6,25): error CS8385: The given expression cannot be used in a fixed statement + // fixed (int* p = new Fixable1()) + Diagnostic(ErrorCode.ERR_ExprCannotBeFixed, "new Fixable1()").WithLocation(6, 25)); + } + + [Fact] + public void ExtensionMemberLookup_PatternBased_Fixed_05() + { + var src = """ +unsafe class C +{ + public static void Main() + { + /**/ + fixed (int* p = new Fixable()) + { + System.Console.WriteLine(p[1]); + } + /**/ + } +} + +class Fixable +{ + public ref int GetPinnableReference(int notApplicable) => throw null; // not applicable +} + +static class E +{ + extension(Fixable f) + { + public ref int GetPinnableReference() { return ref (new int[] { 1, 2, 3 })[0]; } + } +} +"""; + + var comp = CreateCompilation(src, options: TestOptions.UnsafeReleaseExe); + CompileAndVerify(comp, expectedOutput: "2", verify: Verification.Skipped).VerifyDiagnostics(); + + string expectedOperationTree = """ +IFixedOperation (OperationKind.None, Type: null) (Syntax: 'fixed (int* ... }') + Locals: Local_1: System.Int32* p + Declaration: + IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsImplicit) (Syntax: 'int* p = new Fixable()') + IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'int* p = new Fixable()') + Declarators: + IVariableDeclaratorOperation (Symbol: System.Int32* p) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'p = new Fixable()') + Initializer: + IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= new Fixable()') + IOperation: (OperationKind.None, Type: System.Int32*, IsImplicit) (Syntax: 'new Fixable()') + Children(1): + IObjectCreationOperation (Constructor: Fixable..ctor()) (OperationKind.ObjectCreation, Type: Fixable) (Syntax: 'new Fixable()') + Arguments(0) + Initializer: + null + Initializer: + null + Body: + IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }') + IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'System.Cons ... Line(p[1]);') + Expression: + IInvocationOperation (void System.Console.WriteLine(System.Int32 value)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'System.Cons ... eLine(p[1])') + Instance Receiver: + null + Arguments(1): + IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'p[1]') + IOperation: (OperationKind.None, Type: System.Int32) (Syntax: 'p[1]') + Children(2): + ILocalReferenceOperation: p (OperationKind.LocalReference, Type: System.Int32*) (Syntax: 'p') + ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') + InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) + OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) +"""; + + VerifyOperationTreeAndDiagnosticsForTest(src, expectedOperationTree, [], targetFramework: TargetFramework.Net70, compilationOptions: TestOptions.UnsafeReleaseExe); + } + + [Fact] + public void ExtensionMemberLookup_PatternBased_Fixed_06() + { + var text = @" +unsafe class C +{ + public static void Main() + { + fixed (int* p = new Fixable()) + { + } + } +} + +class Fixable { } + +static class E +{ + extension(Fixable f) + { + public static ref int GetPinnableReference() => throw null; + } +} +"; + + var comp = CreateCompilation(text, options: TestOptions.UnsafeReleaseExe); + comp.VerifyEmitDiagnostics( + // (6,25): error CS0176: Member 'E.extension(Fixable).GetPinnableReference()' cannot be accessed with an instance reference; qualify it with a type name instead + // fixed (int* p = new Fixable()) + Diagnostic(ErrorCode.ERR_ObjectProhibited, "new Fixable()").WithArguments("E.extension(Fixable).GetPinnableReference()").WithLocation(6, 25), + // (6,25): error CS8385: The given expression cannot be used in a fixed statement + // fixed (int* p = new Fixable()) + Diagnostic(ErrorCode.ERR_ExprCannotBeFixed, "new Fixable()").WithLocation(6, 25)); + } + + [Fact] + public void ExtensionMemberLookup_PatternBased_Await_ExtensionIsCompleted() + { + var text = @" +using System; +using System.Runtime.CompilerServices; + +int i = await new C(); +System.Console.Write(i); + +class C +{ + public D GetAwaiter() => new D(); +} + +class D : INotifyCompletion +{ + public int GetResult() => 42; + public void OnCompleted(Action continuation) => throw null; +} + +static class E +{ + extension(D d) + { + public bool IsCompleted => true; + } +} +"; + + var comp = CreateCompilation(text); + comp.VerifyEmitDiagnostics( + // (5,9): error CS0117: 'D' does not contain a definition for 'IsCompleted' + // int i = await new C(); + Diagnostic(ErrorCode.ERR_NoSuchMember, "await new C()").WithArguments("D", "IsCompleted").WithLocation(5, 9) + ); + } + + [Fact] + public void ExtensionMemberLookup_PatternBased_Await_ExtensionGetAwaiter() + { + var text = @" +using System; +using System.Runtime.CompilerServices; + +/**/ +int i = await new C(); +/**/ +System.Console.Write(i); + +class C +{ +} + +class D : INotifyCompletion +{ + public int GetResult() => 42; + public void OnCompleted(Action continuation) => throw null; + public bool IsCompleted => true; +} + +static class E +{ + extension(C c) + { + public D GetAwaiter() => new D(); + } +} +"; + + var comp = CreateCompilation(text); + CompileAndVerify(comp, expectedOutput: "42").VerifyDiagnostics(); + + string expectedOperationTree = """ +IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'int i = await new C();') +IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'int i = await new C()') + Declarators: + IVariableDeclaratorOperation (Symbol: System.Int32 i) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'i = await new C()') + Initializer: + IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= await new C()') + IAwaitOperation (OperationKind.Await, Type: System.Int32) (Syntax: 'await new C()') + Expression: + IObjectCreationOperation (Constructor: C..ctor()) (OperationKind.ObjectCreation, Type: C) (Syntax: 'new C()') + Arguments(0) + Initializer: + null + Initializer: + null +"""; + + VerifyOperationTreeAndDiagnosticsForTest(text, expectedOperationTree, [], targetFramework: TargetFramework.Net70); + } + + [Fact] + public void ExtensionMemberLookup_PatternBased_Await_ExtensionGetAwaiter_Conversion() + { + var text = @" +using System; +using System.Runtime.CompilerServices; + +int i = await new C(); +System.Console.Write(i); + +class C +{ +} + +class D : INotifyCompletion +{ + public int GetResult() => 42; + public void OnCompleted(Action continuation) => throw null; + public bool IsCompleted => true; +} + +static class E +{ + extension(object o) + { + public D GetAwaiter() => new D(); + } +} +"; + + var comp = CreateCompilation(text); + CompileAndVerify(comp, expectedOutput: "42").VerifyDiagnostics(); + } + + [Fact] + public void ExtensionMemberLookup_PatternBased_Await_ExtensionGetAwaiter_DelegateTypeProperty() + { + var text = @" +using System; +using System.Runtime.CompilerServices; + +int i = await new C(); +System.Console.Write(i); + +class C +{ +} + +class D : INotifyCompletion +{ + public int GetResult() => 42; + public void OnCompleted(Action continuation) => throw null; + public bool IsCompleted => true; +} + +static class E +{ + extension(C c) + { + public System.Func GetAwaiter => () => new D(); + } +} +"; + + var comp = CreateCompilation(text); + comp.VerifyEmitDiagnostics( + // (5,9): error CS1061: 'C' does not contain a definition for 'GetAwaiter' and no accessible extension method 'GetAwaiter' accepting a first argument of type 'C' could be found (are you missing a using directive or an assembly reference?) + // int i = await new C(); + Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "await new C()").WithArguments("C", "GetAwaiter").WithLocation(5, 9)); + + text = @" +using System; +using System.Runtime.CompilerServices; + +int i = await new C(); +System.Console.Write(i); + +class C +{ + public System.Func GetAwaiter => () => new D(); +} + +class D : INotifyCompletion +{ + public int GetResult() => 42; + public void OnCompleted(Action continuation) => throw null; + public bool IsCompleted => true; +} +"; + + comp = CreateCompilation(text); + comp.VerifyEmitDiagnostics( + // (5,9): error CS0118: 'GetAwaiter' is a property but is used like a method + // int i = await new C(); + Diagnostic(ErrorCode.ERR_BadSKknown, "await new C()").WithArguments("GetAwaiter", "property", "method").WithLocation(5, 9)); + } + + [Fact] + public void ExtensionMemberLookup_PatternBased_Await_ExtensionGetAwaiter_DynamicTypeProperty() + { + var text = @" +using System; +using System.Runtime.CompilerServices; + +int i = await new C(); +System.Console.Write(i); + +class C +{ +} + +class D : INotifyCompletion +{ + public int GetResult() => 42; + public void OnCompleted(Action continuation) => throw null; + public bool IsCompleted => true; +} + +static class E +{ + extension(C c) + { + public dynamic GetAwaiter => throw null; + } +} +"; + + var comp = CreateCompilation(text); + comp.VerifyEmitDiagnostics( + // (5,9): error CS1061: 'C' does not contain a definition for 'GetAwaiter' and no accessible extension method 'GetAwaiter' accepting a first argument of type 'C' could be found (are you missing a using directive or an assembly reference?) + // int i = await new C(); + Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "await new C()").WithArguments("C", "GetAwaiter").WithLocation(5, 9)); + + text = @" +using System; +using System.Runtime.CompilerServices; + +int i = await new C(); +System.Console.Write(i); + +class C +{ + public dynamic GetAwaiter => throw null; +} + +class D : INotifyCompletion +{ + public int GetResult() => 42; + public void OnCompleted(Action continuation) => throw null; + public bool IsCompleted => true; +} +"; + + comp = CreateCompilation(text); + comp.VerifyEmitDiagnostics( + // (5,9): error CS0118: 'GetAwaiter' is a property but is used like a method + // int i = await new C(); + Diagnostic(ErrorCode.ERR_BadSKknown, "await new C()").WithArguments("GetAwaiter", "property", "method").WithLocation(5, 9)); + } + + [Fact] + public void ExtensionMemberLookup_PatternBased_Await_ExtensionGetResult() + { + var text = @" +using System; +using System.Runtime.CompilerServices; + +int i = await new C(); +System.Console.Write(i); + +class C +{ + public D GetAwaiter() => new D(); +} + +class D : INotifyCompletion +{ + public void OnCompleted(Action continuation) => throw null; + public bool IsCompleted => true; +} + +static class E +{ + extension(D d) + { + public int GetResult() => 42; + } +} +"; + + var comp = CreateCompilation(text); + + // The error is consistent with classic extension methods + comp.VerifyEmitDiagnostics( + // (5,9): error CS0117: 'D' does not contain a definition for 'GetResult' + // int i = await new C(); + Diagnostic(ErrorCode.ERR_NoSuchMember, "await new C()").WithArguments("D", "GetResult").WithLocation(5, 9) + ); + + text = """ +using System; +using System.Runtime.CompilerServices; + +int i = await new C(); +System.Console.Write(i); + +class C +{ + public D GetAwaiter() => new D(); +} + +class D : INotifyCompletion +{ + public void OnCompleted(Action continuation) => throw null; + public bool IsCompleted => true; +} + +static class E +{ + public static int GetResult(this D d) => 42; +} +"""; + + comp = CreateCompilation(text); + comp.VerifyEmitDiagnostics( + // (4,9): error CS0117: 'D' does not contain a definition for 'GetResult' + // int i = await new C(); + Diagnostic(ErrorCode.ERR_NoSuchMember, "await new C()").WithArguments("D", "GetResult").WithLocation(4, 9) + ); + } + + [Fact] + public void ExtensionMemberLookup_PatternBased_Await_ExtensionGetResult_DelegateTypeProperty() + { + var text = @" +using System; +using System.Runtime.CompilerServices; + +int i = await new C(); +System.Console.Write(i); + +class C +{ + public D GetAwaiter() => new D(); +} + +class D : INotifyCompletion +{ + public void OnCompleted(Action continuation) => throw null; + public bool IsCompleted => true; +} + +static class E +{ + extension(D d) + { + public System.Func GetResult => () => 42; + } +} +"; + var comp = CreateCompilation(text); + comp.VerifyEmitDiagnostics( + // (5,9): error CS0117: 'D' does not contain a definition for 'GetResult' + // int i = await new C(); + Diagnostic(ErrorCode.ERR_NoSuchMember, "await new C()").WithArguments("D", "GetResult").WithLocation(5, 9)); + + text = """ +using System; +using System.Runtime.CompilerServices; + +int i = await new C(); +System.Console.Write(i); + +class C +{ + public D GetAwaiter() => new D(); +} + +class D : INotifyCompletion +{ + public void OnCompleted(Action continuation) => throw null; + public bool IsCompleted => true; + public System.Func GetResult => () => 42; +} +"""; + + comp = CreateCompilation(text); + comp.VerifyEmitDiagnostics( + // (4,9): error CS0118: 'GetResult' is a property but is used like a method + // int i = await new C(); + Diagnostic(ErrorCode.ERR_BadSKknown, "await new C()").WithArguments("GetResult", "property", "method").WithLocation(4, 9)); + } + + [Fact] + public void ExtensionMemberLookup_PatternBased_Await_ExtensionGetResult_DynamicTypeProperty() + { + var text = @" +using System; +using System.Runtime.CompilerServices; + +int i = await new C(); +System.Console.Write(i); + +class C +{ + public D GetAwaiter() => new D(); +} + +class D : INotifyCompletion +{ + public void OnCompleted(Action continuation) => throw null; + public bool IsCompleted => true; +} + +static class E +{ + extension(D d) + { + public dynamic GetResult => throw null; + } +} +"; + + var comp = CreateCompilation(text); + comp.VerifyEmitDiagnostics( + // (5,9): error CS0117: 'D' does not contain a definition for 'GetResult' + // int i = await new C(); + Diagnostic(ErrorCode.ERR_NoSuchMember, "await new C()").WithArguments("D", "GetResult").WithLocation(5, 9)); + + text = """ +using System; +using System.Runtime.CompilerServices; + +int i = await new C(); +System.Console.Write(i); + +class C +{ + public D GetAwaiter() => new D(); +} + +class D : INotifyCompletion +{ + public void OnCompleted(Action continuation) => throw null; + public bool IsCompleted => true; + public dynamic GetResult => throw null; +} +"""; + + comp = CreateCompilation(text); + comp.VerifyEmitDiagnostics( + // (4,9): error CS0118: 'GetResult' is a property but is used like a method + // int i = await new C(); + Diagnostic(ErrorCode.ERR_BadSKknown, "await new C()").WithArguments("GetResult", "property", "method").WithLocation(4, 9)); + } + + [Fact] + public void ExtensionMemberLookup_PatternBased_IndexIndexer_Length() + { + var src = """ +var c = new C(); + +/**/ +_ = c[^1]; +/**/ + +class C +{ + public int this[int i] => throw null; +} + +static class E +{ + extension(C c) + { + public int Length => throw null; + } +} +"""; + DiagnosticDescription[] expectedDiagnostics = [ + // (4,7): error CS1503: Argument 1: cannot convert from 'System.Index' to 'int' + // _ = c[^1]; + Diagnostic(ErrorCode.ERR_BadArgType, "^1").WithArguments("1", "System.Index", "int").WithLocation(4, 7)]; + + var comp = CreateCompilation(src, targetFramework: TargetFramework.Net70); + comp.VerifyEmitDiagnostics(expectedDiagnostics); + + string expectedOperationTree = """ +ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsInvalid) (Syntax: '_ = c[^1]') +Left: + IDiscardOperation (Symbol: System.Int32 _) (OperationKind.Discard, Type: System.Int32) (Syntax: '_') +Right: + IInvalidOperation (OperationKind.Invalid, Type: System.Int32, IsInvalid) (Syntax: 'c[^1]') + Children(2): + ILocalReferenceOperation: c (OperationKind.LocalReference, Type: C) (Syntax: 'c') + IUnaryOperation (UnaryOperatorKind.Hat) (OperationKind.Unary, Type: System.Index, IsInvalid) (Syntax: '^1') + Operand: + ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsInvalid) (Syntax: '1') +"""; + + VerifyOperationTreeAndDiagnosticsForTest(src, expectedOperationTree, expectedDiagnostics, targetFramework: TargetFramework.Net70); + + src = """ +var c = new C(); +_ = c[^1]; + +class C +{ + public int this[int i] => throw null; + public int Length => throw null; +} +"""; + comp = CreateCompilation(src, targetFramework: TargetFramework.Net70); + comp.VerifyEmitDiagnostics(); + } + + [Fact] + public void ExtensionMemberLookup_PatternBased_IndexIndexer_Count() + { + var src = """ +var c = new C(); +_ = c[^1]; + +class C +{ + public int this[int i] => throw null; +} + +static class E +{ + extension(C c) + { + public int Count => throw null; + } +} +"""; + + var comp = CreateCompilation(src, targetFramework: TargetFramework.Net70); + comp.VerifyEmitDiagnostics( + // (2,7): error CS1503: Argument 1: cannot convert from 'System.Index' to 'int' + // _ = c[^1]; + Diagnostic(ErrorCode.ERR_BadArgType, "^1").WithArguments("1", "System.Index", "int").WithLocation(2, 7)); + + src = """ +var c = new C(); +_ = c[^1]; + +class C +{ + public int this[int i] => throw null; + public int Count => throw null; +} +"""; + comp = CreateCompilation(src, targetFramework: TargetFramework.Net70); + comp.VerifyEmitDiagnostics(); + } + + [Fact] + public void ExtensionMemberLookup_PatternBased_IndexIndexer_IntIndexer() + { + var src = """ +var c = new C(); +_ = c[^1]; + +class C +{ + public int Length => throw null; +} + +static class E +{ + extension(C c) + { + public int this[int i] => throw null; + } +} +"""; + var comp = CreateCompilation(src, targetFramework: TargetFramework.Net70); + comp.VerifyEmitDiagnostics( + // (2,5): error CS0021: Cannot apply indexing with [] to an expression of type 'C' + // _ = c[^1]; + Diagnostic(ErrorCode.ERR_BadIndexLHS, "c[^1]").WithArguments("C").WithLocation(2, 5)); + } + + [Fact] + public void ExtensionMemberLookup_PatternBased_IndexIndexer_RegularIndexer() + { + var src = """ +var c = new C(); +_ = c[^1]; + +class C +{ + public int Length => throw null; +} + +static class E +{ + extension(C c) + { + public int this[System.Index i] => throw null; + } +} +"""; + // Tracked by https://github.com/dotnet/roslyn/issues/76130 : revisit when implementing extension indexers + var comp = CreateCompilation(src, targetFramework: TargetFramework.Net70); + comp.VerifyEmitDiagnostics( + // (2,5): error CS0021: Cannot apply indexing with [] to an expression of type 'C' + // _ = c[^1]; + Diagnostic(ErrorCode.ERR_BadIndexLHS, "c[^1]").WithArguments("C").WithLocation(2, 5)); + + src = """ +var c = new C(); +_ = c[^1]; + +class C +{ + public int Length => throw null; + public int this[System.Index i] => throw null; +} +"""; + comp = CreateCompilation(src, targetFramework: TargetFramework.Net70); + comp.VerifyEmitDiagnostics(); + } + + [Fact] + public void ExtensionMemberLookup_PatternBased_RangeIndexer_Slice() + { + var src = """ +var c = new C(); + +/**/ +_ = c[1..^1]; +/**/ + +class C +{ + public int Length => throw null; +} + +static class E +{ + extension(C c) + { + public int Slice(int i, int j) => throw null; + } +} +"""; + + DiagnosticDescription[] expectedDiagnostics = [ + // (4,5): error CS0021: Cannot apply indexing with [] to an expression of type 'C' + // _ = c[1..^1]; + Diagnostic(ErrorCode.ERR_BadIndexLHS, "c[1..^1]").WithArguments("C").WithLocation(4, 5)]; + + var comp = CreateCompilation(src, targetFramework: TargetFramework.Net70); + comp.VerifyEmitDiagnostics(expectedDiagnostics); + + string expectedOperationTree = """ +ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: ?, IsInvalid) (Syntax: '_ = c[1..^1]') +Left: + IDiscardOperation (Symbol: ? _) (OperationKind.Discard, Type: ?) (Syntax: '_') +Right: + IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'c[1..^1]') + Children(2): + IRangeOperation (OperationKind.Range, Type: System.Range, IsInvalid) (Syntax: '1..^1') + LeftOperand: + IConversionOperation (TryCast: False, Unchecked) (OperatorMethod: System.Index System.Index.op_Implicit(System.Int32 value)) (OperationKind.Conversion, Type: System.Index, IsInvalid, IsImplicit) (Syntax: '1') + Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: True) (MethodSymbol: System.Index System.Index.op_Implicit(System.Int32 value)) + Operand: + ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsInvalid) (Syntax: '1') + RightOperand: + IUnaryOperation (UnaryOperatorKind.Hat) (OperationKind.Unary, Type: System.Index, IsInvalid) (Syntax: '^1') + Operand: + ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsInvalid) (Syntax: '1') + ILocalReferenceOperation: c (OperationKind.LocalReference, Type: C, IsInvalid) (Syntax: 'c') +"""; + + VerifyOperationTreeAndDiagnosticsForTest(src, expectedOperationTree, expectedDiagnostics, targetFramework: TargetFramework.Net70); + + src = """ +var c = new C(); +_ = c[1..^1]; + +class C +{ + public int Length => throw null; + public int Slice(int i, int j) => throw null; +} +"""; + + comp = CreateCompilation(src, targetFramework: TargetFramework.Net70); + comp.VerifyEmitDiagnostics(); + } + + [Fact] + public void ExtensionMemberLookup_PatternBased_RangeIndexer_Length() + { + var src = """ +var c = new C(); +_ = c[1..^1]; + +class C { - public MyDelegate GetPinnableReference => throw null; + public int Slice(int i, int j) => throw null; } -delegate ref int MyDelegate(); - static class E { - extension(Fixable1 f) + extension(C c) { - public MyDelegate GetPinnableReference => throw null; + public int Length => throw null; } } -"; - var comp = CreateCompilation(text, options: TestOptions.UnsafeReleaseExe); - // Tracked by https://github.com/dotnet/roslyn/issues/76130 : confirm when spec'ing pattern-based fixed +"""; + + var comp = CreateCompilation(src, targetFramework: TargetFramework.Net70); comp.VerifyEmitDiagnostics( - // (6,25): error CS8385: The given expression cannot be used in a fixed statement - // fixed (int* p = new Fixable1()) - Diagnostic(ErrorCode.ERR_ExprCannotBeFixed, "new Fixable1()").WithLocation(6, 25), - // (11,25): error CS8385: The given expression cannot be used in a fixed statement - // fixed (int* p = new Fixable2()) - Diagnostic(ErrorCode.ERR_ExprCannotBeFixed, "new Fixable2()").WithLocation(11, 25) - ); + // (2,5): error CS0021: Cannot apply indexing with [] to an expression of type 'C' + // _ = c[1..^1]; + Diagnostic(ErrorCode.ERR_BadIndexLHS, "c[1..^1]").WithArguments("C").WithLocation(2, 5)); } [Fact] - public void ExtensionMemberLookup_PatternBased_Fixed_NoApplicableMethod() + public void ExtensionMemberLookup_PatternBased_RangeIndexer_RegularIndexer() { var src = """ -unsafe class C -{ - public static void Main() - { - fixed (int* p = new Fixable()) - { - System.Console.WriteLine(p[1]); - } - } -} +var c = new C(); +_ = c[1..^1]; -class Fixable +class C { - public ref int GetPinnableReference(int notApplicable) => throw null; // not applicable + public int Length => throw null; } static class E { - extension(Fixable f) + extension(C c) { - public ref int GetPinnableReference() { return ref (new int[] { 1, 2, 3 })[0]; } + public int this[System.Range r] => throw null; } } """; - // Tracked by https://github.com/dotnet/roslyn/issues/76130 : confirm when spec'ing pattern-based fixed - var comp = CreateCompilation(src, options: TestOptions.UnsafeReleaseExe); - comp.VerifyEmitDiagnostics(); - // Tracked by https://github.com/dotnet/roslyn/issues/76130 : metadata is undone + // Tracked by https://github.com/dotnet/roslyn/issues/76130 : revisit when implementing extension indexers + var comp = CreateCompilation(src, targetFramework: TargetFramework.Net70); + comp.VerifyEmitDiagnostics( + // (2,5): error CS0021: Cannot apply indexing with [] to an expression of type 'C' + // _ = c[1..^1]; + Diagnostic(ErrorCode.ERR_BadIndexLHS, "c[1..^1]").WithArguments("C").WithLocation(2, 5)); - // Tracked by https://github.com/dotnet/roslyn/issues/76130 : verify IOperation + src = """ +var c = new C(); +_ = c[1..^1]; + +class C +{ + public int Length => throw null; + public int this[System.Range r] => throw null; +} +"""; + + comp = CreateCompilation(src, targetFramework: TargetFramework.Net70); + comp.VerifyEmitDiagnostics(); } [Fact] - public void ExtensionMemberLookup_PatternBased_Fixed_Static() + public void ExtensionMemberLookup_PatternBased_ListPattern_Length() { - var text = @" -unsafe class C + var src = """ +_ = new C() is [1]; + +class C { - public static void Main() - { - fixed (int* p = new Fixable()) - { - } - } + public int this[int i] => throw null; } -class Fixable { } - static class E { - extension(Fixable f) + extension(C c) { - public static ref int GetPinnableReference() => throw null; + public int Length => throw null; } } -"; +"""; - var comp = CreateCompilation(text, options: TestOptions.UnsafeReleaseExe); - // Tracked by https://github.com/dotnet/roslyn/issues/76130 : confirm when spec'ing pattern-based fixed + var comp = CreateCompilation(src, targetFramework: TargetFramework.Net70); comp.VerifyEmitDiagnostics( - // (6,25): error CS0176: Member 'E.extension(Fixable).GetPinnableReference()' cannot be accessed with an instance reference; qualify it with a type name instead - // fixed (int* p = new Fixable()) - Diagnostic(ErrorCode.ERR_ObjectProhibited, "new Fixable()").WithArguments("E.extension(Fixable).GetPinnableReference()").WithLocation(6, 25), - // (6,25): error CS8385: The given expression cannot be used in a fixed statement - // fixed (int* p = new Fixable()) - Diagnostic(ErrorCode.ERR_ExprCannotBeFixed, "new Fixable()").WithLocation(6, 25)); - } - - [Fact] - public void ExtensionMemberLookup_PatternBased_Await_ExtensionIsCompleted() - { - var text = @" -using System; -using System.Runtime.CompilerServices; + // (1,16): error CS8985: List patterns may not be used for a value of type 'C'. No suitable 'Length' or 'Count' property was found. + // _ = new C() is [1]; + Diagnostic(ErrorCode.ERR_ListPatternRequiresLength, "[1]").WithArguments("C").WithLocation(1, 16), + // (1,16): error CS1503: Argument 1: cannot convert from 'System.Index' to 'int' + // _ = new C() is [1]; + Diagnostic(ErrorCode.ERR_BadArgType, "[1]").WithArguments("1", "System.Index", "int").WithLocation(1, 16)); -int i = await new C(); -System.Console.Write(i); + src = """ +_ = new C() is [1]; class C { - public D GetAwaiter() => new D(); + public int this[int i] => throw null; + public int Length => throw null; } +"""; + comp = CreateCompilation(src, targetFramework: TargetFramework.Net70); + comp.VerifyEmitDiagnostics(); + } -class D : INotifyCompletion + [Fact] + public void ExtensionMemberLookup_PatternBased_ListPattern_IntIndexer() + { + var src = """ +_ = new C() is [1]; + +class C { - public int GetResult() => 42; - public void OnCompleted(Action continuation) => throw null; + public int Length => throw null; } static class E { - extension(D d) + extension(C c) { - public bool IsCompleted => true; + public int this[int i] => throw null; } } -"; - - // Tracked by https://github.com/dotnet/roslyn/issues/76130 : confirm when spec'ing pattern-based await - var comp = CreateCompilation(text); +"""; + var comp = CreateCompilation(src, targetFramework: TargetFramework.Net70); comp.VerifyEmitDiagnostics( - // (5,9): error CS0117: 'D' does not contain a definition for 'IsCompleted' - // int i = await new C(); - Diagnostic(ErrorCode.ERR_NoSuchMember, "await new C()").WithArguments("D", "IsCompleted").WithLocation(5, 9) - ); - // Tracked by https://github.com/dotnet/roslyn/issues/76130 : metadata is undone + // (1,16): error CS0021: Cannot apply indexing with [] to an expression of type 'C' + // _ = new C() is [1]; + Diagnostic(ErrorCode.ERR_BadIndexLHS, "[1]").WithArguments("C").WithLocation(1, 16)); } [Fact] - public void ExtensionMemberLookup_PatternBased_Await_ExtensionGetAwaiter() + public void ExtensionMemberLookup_PatternBased_ListPattern_RegularIndexer() { - var text = @" -using System; -using System.Runtime.CompilerServices; - -int i = await new C(); -System.Console.Write(i); + var src = """ +_ = new C() is [1]; class C { -} - -class D : INotifyCompletion -{ - public int GetResult() => 42; - public void OnCompleted(Action continuation) => throw null; - public bool IsCompleted => true; + public int Length => throw null; } static class E { extension(C c) { - public D GetAwaiter() => new D(); + public int this[System.Index i] => throw null; } } -"; +"""; - // Tracked by https://github.com/dotnet/roslyn/issues/76130 : confirm when spec'ing pattern-based await - var comp = CreateCompilation(text); + // Tracked by https://github.com/dotnet/roslyn/issues/76130 : revisit when implementing extension indexers + var comp = CreateCompilation(src, targetFramework: TargetFramework.Net70); + comp.VerifyEmitDiagnostics( + // (1,16): error CS0021: Cannot apply indexing with [] to an expression of type 'C' + // _ = new C() is [1]; + Diagnostic(ErrorCode.ERR_BadIndexLHS, "[1]").WithArguments("C").WithLocation(1, 16)); + + src = """ +_ = new C() is [1]; + +class C +{ + public int Length => throw null; + public int this[System.Index i] => throw null; +} +"""; + + comp = CreateCompilation(src, targetFramework: TargetFramework.Net70); comp.VerifyEmitDiagnostics(); - // Tracked by https://github.com/dotnet/roslyn/issues/76130 : metadata is undone } [Fact] - public void ExtensionMemberLookup_PatternBased_Await_ExtensionGetResult() + public void ExtensionMemberLookup_PatternBased_SpreadPattern_Length() { - var text = @" -using System; -using System.Runtime.CompilerServices; - -int i = await new C(); -System.Console.Write(i); + var src = """ +_ = new C() is [_, .. var x]; class C { - public D GetAwaiter() => new D(); -} - -class D : INotifyCompletion -{ - public void OnCompleted(Action continuation) => throw null; - public bool IsCompleted => true; + public int this[System.Index i] => throw null; + public int Slice(int i, int j) => throw null; } static class E { - extension(D d) + extension(C c) { - public int GetResult() => 42; + public int Length => throw null; } } -"; - - // Tracked by https://github.com/dotnet/roslyn/issues/76130 : confirm when spec'ing pattern-based await - var comp = CreateCompilation(text); +"""; - // The error is consistent with classic extension methods + var comp = CreateCompilation(src, targetFramework: TargetFramework.Net70); comp.VerifyEmitDiagnostics( - // (5,9): error CS0117: 'D' does not contain a definition for 'GetResult' - // int i = await new C(); - Diagnostic(ErrorCode.ERR_NoSuchMember, "await new C()").WithArguments("D", "GetResult").WithLocation(5, 9) - ); + // (1,16): error CS8985: List patterns may not be used for a value of type 'C'. No suitable 'Length' or 'Count' property was found. + // _ = new C() is [_, .. var x]; + Diagnostic(ErrorCode.ERR_ListPatternRequiresLength, "[_, .. var x]").WithArguments("C").WithLocation(1, 16), + // (1,20): error CS1503: Argument 1: cannot convert from 'System.Range' to 'System.Index' + // _ = new C() is [_, .. var x]; + Diagnostic(ErrorCode.ERR_BadArgType, ".. var x").WithArguments("1", "System.Range", "System.Index").WithLocation(1, 20)); + + src = """ +_ = new C() is [_, .. var x]; + +class C +{ + public int this[System.Index i] => throw null; + public int Slice(int i, int j) => throw null; + public int Length => throw null; +} +"""; + comp = CreateCompilation(src, targetFramework: TargetFramework.Net70); + comp.VerifyEmitDiagnostics(); } [Fact] - public void ExtensionMemberLookup_PatternBased_IndexIndexer_NoLength() + public void ExtensionMemberLookup_PatternBased_SpreadPattern_Slice() { var src = """ -var c = new C(); - -/**/ -_ = c[^1]; -/**/ +_ = new C() is [_, .. var x]; class C { - public int this[int i] - { - get { System.Console.Write("indexer "); return 0; } - } + public int this[System.Index i] => throw null; + public int Length => throw null; } static class E { extension(C c) { - public int Length - { - get { System.Console.Write("length "); return 42; } - } + public int Slice(int i, int j) => throw null; } } """; - DiagnosticDescription[] expectedDiagnostics = [ - // (4,7): error CS1503: Argument 1: cannot convert from 'System.Index' to 'int' - // _ = c[^1]; - Diagnostic(ErrorCode.ERR_BadArgType, "^1").WithArguments("1", "System.Index", "int").WithLocation(4, 7)]; var comp = CreateCompilation(src, targetFramework: TargetFramework.Net70); - // Tracked by https://github.com/dotnet/roslyn/issues/76130 : revisit as part of "implicit indexer access" section - comp.VerifyEmitDiagnostics(expectedDiagnostics); - // Tracked by https://github.com/dotnet/roslyn/issues/76130 : metadata is undone - //CompileAndVerify(comp, expectedOutput: "length indexer"); - - string expectedOperationTree = """ -ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsInvalid) (Syntax: '_ = c[^1]') -Left: - IDiscardOperation (Symbol: System.Int32 _) (OperationKind.Discard, Type: System.Int32) (Syntax: '_') -Right: - IInvalidOperation (OperationKind.Invalid, Type: System.Int32, IsInvalid) (Syntax: 'c[^1]') - Children(2): - ILocalReferenceOperation: c (OperationKind.LocalReference, Type: C) (Syntax: 'c') - IUnaryOperation (UnaryOperatorKind.Hat) (OperationKind.Unary, Type: System.Index, IsInvalid) (Syntax: '^1') - Operand: - ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsInvalid) (Syntax: '1') -"""; - - VerifyOperationTreeAndDiagnosticsForTest(src, expectedOperationTree, expectedDiagnostics, targetFramework: TargetFramework.Net70); + comp.VerifyEmitDiagnostics( + // (1,20): error CS1503: Argument 1: cannot convert from 'System.Range' to 'System.Index' + // _ = new C() is [_, .. var x]; + Diagnostic(ErrorCode.ERR_BadArgType, ".. var x").WithArguments("1", "System.Range", "System.Index").WithLocation(1, 20)); } [Fact] - public void ExtensionMemberLookup_PatternBased_RangeIndexer_NoMethod() + public void ExtensionMemberLookup_PatternBased_SpreadPattern_RegularIndexer() { var src = """ -var c = new C(); - -/**/ -_ = c[1..^1]; -/**/ +_ = new C() is [_, .. var x]; -class C { } +class C +{ + public int this[System.Index i] => throw null; + public int Length => throw null; +} static class E { extension(C c) { - public int Slice(int i, int j) { System.Console.Write("slice "); return 0; } - - public int Length - { - get { System.Console.Write("length "); return 42; } - } + public int this[System.Range r] => throw null; } } """; - DiagnosticDescription[] expectedDiagnostics = [ - // (4,5): error CS0021: Cannot apply indexing with [] to an expression of type 'C' - // _ = c[1..^1]; - Diagnostic(ErrorCode.ERR_BadIndexLHS, "c[1..^1]").WithArguments("C").WithLocation(4, 5)]; - var comp = CreateCompilation(src, targetFramework: TargetFramework.Net70); - // Tracked by https://github.com/dotnet/roslyn/issues/76130 : revisit as part of "implicit indexer access" section - comp.VerifyEmitDiagnostics(expectedDiagnostics); - // Tracked by https://github.com/dotnet/roslyn/issues/76130 : metadata is undone - //CompileAndVerify(comp, expectedOutput: "length slice"); + comp.VerifyEmitDiagnostics( + // (1,20): error CS1503: Argument 1: cannot convert from 'System.Range' to 'System.Index' + // _ = new C() is [_, .. var x]; + Diagnostic(ErrorCode.ERR_BadArgType, ".. var x").WithArguments("1", "System.Range", "System.Index").WithLocation(1, 20)); - string expectedOperationTree = """ -ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: ?, IsInvalid) (Syntax: '_ = c[1..^1]') -Left: - IDiscardOperation (Symbol: ? _) (OperationKind.Discard, Type: ?) (Syntax: '_') -Right: - IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'c[1..^1]') - Children(2): - IRangeOperation (OperationKind.Range, Type: System.Range, IsInvalid) (Syntax: '1..^1') - LeftOperand: - IConversionOperation (TryCast: False, Unchecked) (OperatorMethod: System.Index System.Index.op_Implicit(System.Int32 value)) (OperationKind.Conversion, Type: System.Index, IsInvalid, IsImplicit) (Syntax: '1') - Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: True) (MethodSymbol: System.Index System.Index.op_Implicit(System.Int32 value)) - Operand: - ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsInvalid) (Syntax: '1') - RightOperand: - IUnaryOperation (UnaryOperatorKind.Hat) (OperationKind.Unary, Type: System.Index, IsInvalid) (Syntax: '^1') - Operand: - ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsInvalid) (Syntax: '1') - ILocalReferenceOperation: c (OperationKind.LocalReference, Type: C, IsInvalid) (Syntax: 'c') -"""; + src = """ +_ = new C() is [_, .. var x]; - VerifyOperationTreeAndDiagnosticsForTest(src, expectedOperationTree, expectedDiagnostics, targetFramework: TargetFramework.Net70); +class C +{ + public int this[System.Index i] => throw null; + public int this[System.Range r] => throw null; + public int Length => throw null; +} +"""; + comp = CreateCompilation(src, targetFramework: TargetFramework.Net70); + comp.VerifyEmitDiagnostics(); } [Fact] - public void ExtensionMemberLookup_PatternBased_RangeIndexer_NoApplicableMethod() + public void ExtensionMemberLookup_Patterns() { var src = """ var c = new C(); +_ = c is { Property: 42 }; -/**/ -_ = c[1..^1]; -/**/ - -class C -{ - public int Slice(int notApplicable) => throw null; // not applicable -} +class C { } static class E { extension(C c) { - public int Slice(int i, int j) { System.Console.Write("slice "); return 0; } - - public int Length + public int Property { - get { System.Console.Write("length "); return 42; } + get { System.Console.Write("property"); return 42; } } } } """; + var comp = CreateCompilation(src); + CompileAndVerify(comp, expectedOutput: "property").VerifyDiagnostics(); - // Tracked by https://github.com/dotnet/roslyn/issues/76130 : revisit as part of "implicit indexer access" section - var comp = CreateCompilation(src, targetFramework: TargetFramework.Net70); - comp.VerifyEmitDiagnostics( - // (4,5): error CS0021: Cannot apply indexing with [] to an expression of type 'C' - // _ = c[1..^1]; - Diagnostic(ErrorCode.ERR_BadIndexLHS, "c[1..^1]").WithArguments("C").WithLocation(4, 5)); + var tree = comp.SyntaxTrees.First(); + var model = comp.GetSemanticModel(tree); + var nameColon = GetSyntax(tree, "Property:"); + Assert.Equal("System.Int32 E.<>E__0.Property { get; }", model.GetSymbolInfo(nameColon.Name).Symbol.ToTestDisplayString()); } [Fact] - public void ExtensionMemberLookup_Patterns() + public void ExtensionMemberLookup_Patterns_Conversion() { var src = """ var c = new C(); - _ = c is { Property: 42 }; class C { } static class E { - extension(C c) + extension(object o) { public int Property { @@ -20815,11 +22201,6 @@ public int Property """; var comp = CreateCompilation(src); CompileAndVerify(comp, expectedOutput: "property").VerifyDiagnostics(); - - var tree = comp.SyntaxTrees.First(); - var model = comp.GetSemanticModel(tree); - var nameColon = GetSyntax(tree, "Property:"); - Assert.Equal("System.Int32 E.<>E__0.Property { get; }", model.GetSymbolInfo(nameColon.Name).Symbol.ToTestDisplayString()); } [Fact] @@ -20857,6 +22238,66 @@ static class E2 Assert.Equal("System.Int32 E2.<>E__0.Property2 { get; }", model.GetSymbolInfo(expressionColon.Expression).Symbol.ToTestDisplayString()); } + [Fact] + public void ExtensionMemberLookup_Patterns_ExtendedPropertyPattern_Conversion() + { + var src = """ +var c = new C(); + +_ = c is { Property.Property2: 43 }; + +class C { } + +static class E1 +{ + extension(object o) + { + public int Property { get { System.Console.Write("property "); return 42; } } + } +} + +static class E2 +{ + extension(int i) + { + public int Property2 { get { System.Console.Write("property2"); return 43; } } + } +} +"""; + var comp = CreateCompilation(src); + CompileAndVerify(comp, expectedOutput: "property property2").VerifyDiagnostics(); + } + + [Fact] + public void ExtensionMemberLookup_Patterns_ExtendedPropertyPattern_Conversion_02() + { + var src = """ +var c = new C(); + +_ = c is { Property.Property2: 43 }; + +class C { } + +static class E1 +{ + extension(C c) + { + public C Property { get { System.Console.Write("property "); return c; } } + } +} + +static class E2 +{ + extension(object o) + { + public int Property2 { get { System.Console.Write("property2"); return 43; } } + } +} +"""; + var comp = CreateCompilation(src); + CompileAndVerify(comp, expectedOutput: "property property2").VerifyDiagnostics(); + } + [Fact] public void ExtensionMemberLookup_Patterns_ListPattern_NoInstanceLength() { @@ -20884,23 +22325,19 @@ public int Length """; var comp = CreateCompilation(src, targetFramework: TargetFramework.Net70); - // Tracked by https://github.com/dotnet/roslyn/issues/76130 : confirm that we want extensions to contribute to list-patterns + // Tracked by https://github.com/dotnet/roslyn/issues/76130 : confirm whether we want extension Length/Count to contribute to list-patterns comp.VerifyEmitDiagnostics( // (1,33): error CS8985: List patterns may not be used for a value of type 'C'. No suitable 'Length' or 'Count' property was found. // System.Console.Write(new C() is ["hi"]); Diagnostic(ErrorCode.ERR_ListPatternRequiresLength, @"[""hi""]").WithArguments("C").WithLocation(1, 33) ); - // Tracked by https://github.com/dotnet/roslyn/issues/76130 : metadata is undone - //CompileAndVerify(comp, expectedOutput: "length indexer"); } - [ConditionalFact(typeof(NoUsedAssembliesValidation))] // Tracked by https://github.com/dotnet/roslyn/issues/76130 : metadata is undone + [Fact] public void ExtensionMemberLookup_ObjectInitializer() { var src = """ -/**/ _ = new C() { Property = 42 }; -/**/ class C { } @@ -20914,9 +22351,7 @@ static class E """; var comp = CreateCompilation(src); - comp.VerifyDiagnostics(); - // Tracked by https://github.com/dotnet/roslyn/issues/76130 : metadata is undone - //CompileAndVerify(comp, expectedOutput: "property"); + CompileAndVerify(comp, expectedOutput: "property").VerifyDiagnostics(); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); @@ -20924,7 +22359,28 @@ static class E Assert.Equal("System.Int32 E.<>E__0.Property { set; }", model.GetSymbolInfo(assignment.Left).Symbol.ToTestDisplayString()); } - [ConditionalFact(typeof(NoUsedAssembliesValidation))] // Tracked by https://github.com/dotnet/roslyn/issues/76130 : metadata is undone + [Fact] + public void ExtensionMemberLookup_ObjectInitializer_Conversion() + { + var src = """ +_ = new C() { Property = 42 }; + +class C { } + +static class E +{ + extension(object o) + { + public int Property { set { System.Console.Write("property"); } } + } +} +"""; + + var comp = CreateCompilation(src); + CompileAndVerify(comp, expectedOutput: "property").VerifyDiagnostics(); + } + + [Fact] public void ExtensionMemberLookup_With() { var src = """ @@ -20944,10 +22400,7 @@ static class E """; var comp = CreateCompilation(src); - // Tracked by https://github.com/dotnet/roslyn/issues/76130 : need to decide whether extensions apply here - comp.VerifyDiagnostics(); - // Tracked by https://github.com/dotnet/roslyn/issues/76130 : metadata is undone - //CompileAndVerify(comp, expectedOutput: "property"); + CompileAndVerify(comp, expectedOutput: "property").VerifyDiagnostics(); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); @@ -20956,7 +22409,7 @@ static class E } [Fact] - public void ExtensionMemberLookup_CollectionInitializer_NoMethod() + public void ExtensionMemberLookup_CollectionInitializer() { var src = """ using System.Collections; @@ -20982,7 +22435,6 @@ static class E """; var comp = CreateCompilation(src); - // Tracked by https://github.com/dotnet/roslyn/issues/76130 : confirm when spec'ing pattern-based collection initializer CompileAndVerify(comp, expectedOutput: "add").VerifyDiagnostics(); string expectedOperationTree = """ @@ -21009,6 +22461,62 @@ static class E VerifyOperationTreeAndDiagnosticsForTest(src, expectedOperationTree, expectedDiagnostics); } + [Fact] + public void ExtensionMemberLookup_CollectionInitializer_Conversion() + { + var src = """ +using System.Collections; +using System.Collections.Generic; + +/**/ +_ = new C() { 42 }; +/**/ + +class C : IEnumerable, IEnumerable +{ + IEnumerator IEnumerable.GetEnumerator() => throw null; + IEnumerator IEnumerable.GetEnumerator() => throw null; +} + +static class E +{ + extension(object o) + { + public void Add(int i) { System.Console.Write("add"); } + } +} +"""; + + var comp = CreateCompilation(src); + CompileAndVerify(comp, expectedOutput: "add").VerifyDiagnostics(); + + string expectedOperationTree = """ +ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: C) (Syntax: '_ = new C() { 42 }') +Left: + IDiscardOperation (Symbol: C _) (OperationKind.Discard, Type: C) (Syntax: '_') +Right: + IObjectCreationOperation (Constructor: C..ctor()) (OperationKind.ObjectCreation, Type: C) (Syntax: 'new C() { 42 }') + Arguments(0) + Initializer: + IObjectOrCollectionInitializerOperation (OperationKind.ObjectOrCollectionInitializer, Type: C) (Syntax: '{ 42 }') + Initializers(1): + IInvocationOperation ( void E.<>E__0.Add(System.Int32 i)) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: '42') + Instance Receiver: + IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: 'C') + Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) + Operand: + IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: C, IsImplicit) (Syntax: 'C') + Arguments(1): + IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: i) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: '42') + ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 42) (Syntax: '42') + InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) + OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) +"""; + var expectedDiagnostics = DiagnosticDescription.None; + + VerifyOperationTreeAndDiagnosticsForTest(src, expectedOperationTree, expectedDiagnostics); + } + [Fact] public void ExtensionMemberLookup_CollectionInitializer_NoApplicableMethod() { @@ -21042,7 +22550,6 @@ static class E } """; - // Tracked by https://github.com/dotnet/roslyn/issues/76130 : confirm when spec'ing pattern-based collection initializer var comp = CreateCompilation(src, options: TestOptions.DebugExe); CompileAndVerify(comp, expectedOutput: "add").VerifyDiagnostics(); @@ -21150,7 +22657,6 @@ static class E } """; - // Tracked by https://github.com/dotnet/roslyn/issues/76130 : confirm when spec'ing pattern-based collection initializer // Tracked by https://github.com/dotnet/roslyn/issues/76130 : expression trees var comp = CreateCompilation(src, targetFramework: TargetFramework.Net90); comp.VerifyEmitDiagnostics( @@ -21160,6 +22666,104 @@ static class E ); } + [Fact] + public void ResolveAll_CollectionInitializer_DelegateTypeProperty() + { + var source = """ +using System.Collections; +using System.Collections.Generic; + +MyCollection c = new MyCollection() { 42 }; + +static class E +{ + extension(MyCollection c) + { + public System.Action Add => (int i) => { }; + } +} + +public class MyCollection : IEnumerable +{ + IEnumerator IEnumerable.GetEnumerator() => throw null; + IEnumerator IEnumerable.GetEnumerator() => throw null; +} +"""; + var comp = CreateCompilation(source); + comp.VerifyEmitDiagnostics( + // (4,39): error CS1061: 'MyCollection' does not contain a definition for 'Add' and no accessible extension method 'Add' accepting a first argument of type 'MyCollection' could be found (are you missing a using directive or an assembly reference?) + // MyCollection c = new MyCollection() { 42 }; + Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "42").WithArguments("MyCollection", "Add").WithLocation(4, 39)); + + source = """ +using System.Collections; +using System.Collections.Generic; + +MyCollection c = new MyCollection() { 42 }; + +public class MyCollection : IEnumerable +{ + IEnumerator IEnumerable.GetEnumerator() => throw null; + IEnumerator IEnumerable.GetEnumerator() => throw null; + public System.Action Add => (int i) => { }; +} +"""; + comp = CreateCompilation(source); + comp.VerifyEmitDiagnostics( + // (4,39): error CS0118: 'Add' is a property but is used like a method + // MyCollection c = new MyCollection() { 42 }; + Diagnostic(ErrorCode.ERR_BadSKknown, "42").WithArguments("Add", "property", "method").WithLocation(4, 39)); + } + + [Fact] + public void ResolveAll_CollectionInitializer_DynamicTypeProperty() + { + var source = """ +using System.Collections; +using System.Collections.Generic; + +MyCollection c = new MyCollection() { 42 }; + +static class E +{ + extension(MyCollection c) + { + public dynamic Add => throw null; + } +} + +public class MyCollection : IEnumerable +{ + IEnumerator IEnumerable.GetEnumerator() => throw null; + IEnumerator IEnumerable.GetEnumerator() => throw null; +} +"""; + var comp = CreateCompilation(source); + comp.VerifyEmitDiagnostics( + // (4,39): error CS1061: 'MyCollection' does not contain a definition for 'Add' and no accessible extension method 'Add' accepting a first argument of type 'MyCollection' could be found (are you missing a using directive or an assembly reference?) + // MyCollection c = new MyCollection() { 42 }; + Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "42").WithArguments("MyCollection", "Add").WithLocation(4, 39)); + + source = """ +using System.Collections; +using System.Collections.Generic; + +MyCollection c = new MyCollection() { 42 }; + +public class MyCollection : IEnumerable +{ + IEnumerator IEnumerable.GetEnumerator() => throw null; + IEnumerator IEnumerable.GetEnumerator() => throw null; + public dynamic Add => throw null; +} +"""; + comp = CreateCompilation(source); + comp.VerifyEmitDiagnostics( + // (4,39): error CS0118: 'Add' is a property but is used like a method + // MyCollection c = new MyCollection() { 42 }; + Diagnostic(ErrorCode.ERR_BadSKknown, "42").WithArguments("Add", "property", "method").WithLocation(4, 39)); + } + [Fact] public void ExtensionMemberLookup_Query_NoMethod() { @@ -21414,7 +23018,7 @@ .locals init (delegate* V_0, //ptr IL_0011: calli "delegate*" IL_0016: nop IL_0017: ret -} +} """); var tree = comp.SyntaxTrees.First(); @@ -21724,7 +23328,6 @@ static class E } } """; - // Tracked by https://github.com/dotnet/roslyn/issues/76130 : should we get an error as with methods? var comp = CreateCompilation(src); CompileAndVerify(comp, expectedOutput: "Property").VerifyDiagnostics(); @@ -21734,6 +23337,32 @@ static class E Assert.Equal("System.String E.<>E__0.Property { get; }", model.GetSymbolInfo(memberAccess).Symbol.ToTestDisplayString()); } + [Fact(Skip = "Assertion in NullableWalker.AsMemberOfType")] // Tracked by https://github.com/dotnet/roslyn/issues/76130 : Nullability analysis of properties + public void Nameof_Instance_Property_Generic_01() + { + var src = """ +I i = null; +System.Console.Write(nameof(i.Property)); + +interface I { } + +static class E +{ + extension(I i) + { + public string Property => throw null; + } +} +"""; + var comp = CreateCompilation(src); + CompileAndVerify(comp, expectedOutput: "Property").VerifyDiagnostics(); + + var tree = comp.SyntaxTrees.Single(); + var model = comp.GetSemanticModel(tree); + var memberAccess = GetSyntax(tree, "i.Property"); + Assert.Equal("System.String E.<>E__0.Property { get; }", model.GetSymbolInfo(memberAccess).Symbol.ToTestDisplayString()); + } + [Fact] public void Nameof_Static_Property_Generic_01() { @@ -21789,6 +23418,31 @@ static class E Assert.Equal("System.String E.<>E__0.Property { get; }", model.GetSymbolInfo(memberAccess).Symbol.ToTestDisplayString()); } + [Fact] + public void Nameof_Static_Property_Generic_03() + { + var src = """ +System.Console.Write(nameof(I.Property)); + +interface I { } + +static class E +{ + extension(I i) + { + public static string Property => throw null; + } +} +"""; + var comp = CreateCompilation(src); + CompileAndVerify(comp, expectedOutput: "Property").VerifyDiagnostics(); + + var tree = comp.SyntaxTrees.Single(); + var model = comp.GetSemanticModel(tree); + var memberAccess = GetSyntax(tree, "I.Property"); + Assert.Equal("System.String E.<>E__0.Property { get; }", model.GetSymbolInfo(memberAccess).Symbol.ToTestDisplayString()); + } + [Fact] public void Nameof_Overloads_01() { @@ -22782,14 +24436,14 @@ static int T() } } -class C1 {} -class C2 {} -class C3 {} -class C4 {} -class C5 {} -class C6 {} -class C7 {} -class C8 {} +class C1 {} +class C2 {} +class C3 {} +class C4 {} +class C5 {} +class C6 {} +class C7 {} +class C8 {} """; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( @@ -23381,7 +25035,7 @@ static int M(T[] ts) { return T(ts); } - + static int T(U[] ts) => 0; } "; @@ -23419,7 +25073,7 @@ static int M(int P) { return P(P); } - + static int P(int P) => 0; } "; @@ -26574,8 +28228,8 @@ public void MethodInvocation_RemoveStaticInstanceMismatches_ColorColor_01() Color.M2(null); -class Color -{ +class Color +{ public static void M2(Color Color) { Color.M(); @@ -26624,8 +28278,8 @@ public void MethodInvocation_RemoveStaticInstanceMismatches_ColorColor_02() Color.M2(new Color()); -class Color -{ +class Color +{ public static void M2(Color Color) { Color.M(); @@ -27314,7 +28968,7 @@ public void MethodInvocation_ReceiverConversion_ColorColor() Color.M2(new Color(42)); class Color(int i) : Base(i) -{ +{ public static void M2(Color Color) { Color.M(); @@ -27372,7 +29026,7 @@ public void PropertyAccess_ReceiverConversion_ColorColor() Color.M2(new Color(42)); class Color(int i) : Base(i) -{ +{ public static void M2(Color Color) { _ = Color.P; @@ -27477,7 +29131,7 @@ static void Main() { dynamic d = 1; var result = new C().Test("name", d); - System.Console.Write(result); + System.Console.Write(result); } } @@ -27880,8 +29534,8 @@ .locals init (short V_0, //x C.M(x.ToString()); [ComImport, Guid("1234C65D-1234-447A-B786-64682CBEF136")] -class C -{ +class C +{ public extern static void M(ref string p); } """; @@ -27997,6 +29651,65 @@ static class E Assert.Equal("void E.<>E__0.M(System.String? t2)", model.GetSymbolInfo(memberAccess).Symbol.ToTestDisplayString()); } + [Fact] + public void Nullability_Method_03() + { + var src = """ +#nullable enable + +object oNotNull = new object(); + +oNotNull.M(out object x1, null).ToString(); // 1 +oNotNull.M(out object x2, oNotNull).ToString(); + +x1.ToString(); +x2.ToString(); + +static class E +{ + extension(T t1) + { + public T M(out U u, T t2) => throw null!; + } +} +"""; + var comp = CreateCompilation(src); + comp.VerifyEmitDiagnostics( + // (5,1): warning CS8602: Dereference of a possibly null reference. + // oNotNull.M(out object x1, null).ToString(); // 1 + Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "oNotNull.M(out object x1, null)").WithLocation(5, 1)); + } + + [Fact] + public void Nullability_Method_04() + { + var src = """ +#nullable enable + +object oNotNull = new object(); + +"".M(oNotNull, null).ToString(); // 1 +"".M(null, oNotNull).ToString(); // 2 +"".M(oNotNull, oNotNull).ToString(); + +static class E +{ + extension(T t) + { + public U M(U u1, U u2) => throw null!; + } +} +"""; + var comp = CreateCompilation(src); + comp.VerifyEmitDiagnostics( + // (5,1): warning CS8602: Dereference of a possibly null reference. + // "".M(oNotNull, null).ToString(); // 1 + Diagnostic(ErrorCode.WRN_NullReferenceReceiver, @""""".M(oNotNull, null)").WithLocation(5, 1), + // (6,1): warning CS8602: Dereference of a possibly null reference. + // "".M(null, oNotNull).ToString(); // 2 + Diagnostic(ErrorCode.WRN_NullReferenceReceiver, @""""".M(null, oNotNull)").WithLocation(6, 1)); + } + [Fact] public void PropertyAccess_RemoveWorseMembers_01() { @@ -28822,20 +30535,20 @@ .class nested public auto ansi sealed beforefieldinit '<>E__0' extends System.Object { // Methods - .method private hidebysig specialname static void '$' ( int32[] i ) cil managed + .method private hidebysig specialname static void '$' ( int32[] i ) cil managed { .param [1] .custom instance void [mscorlib]System.ParamArrayAttribute::.ctor() = ( 01 00 00 00) IL_0000: ret } - .method public hidebysig instance void M () cil managed + .method public hidebysig instance void M () cil managed { IL_0000: ldnull IL_0001: throw } } - .method public hidebysig static void 'M' ( int32[] i ) cil managed + .method public hidebysig static void 'M' ( int32[] i ) cil managed { .custom instance void [mscorlib]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 @@ -28892,14 +30605,14 @@ 01 00 00 00 .class nested public auto ansi sealed beforefieldinit '<>E__0' extends System.Object { - .method private hidebysig specialname static void '$' ( int32[] i ) cil managed + .method private hidebysig specialname static void '$' ( int32[] i ) cil managed { .param [1] .custom instance void [mscorlib]System.ParamArrayAttribute::.ctor() = ( 01 00 00 00) IL_0000: ret } - .method public hidebysig specialname instance int32 get_P () cil managed + .method public hidebysig specialname instance int32 get_P () cil managed { IL_0000: ldnull IL_0001: throw @@ -28909,7 +30622,7 @@ .property instance int32 P() .get instance int32 E/'<>E__0'::get_P() } } - .method public hidebysig static int32 'get_P' ( int32[] i ) cil managed + .method public hidebysig static int32 'get_P' ( int32[] i ) cil managed { .param [1] .custom instance void [mscorlib]System.ParamArrayAttribute::.ctor() = ( 01 00 00 00) @@ -31905,7 +33618,7 @@ public static class Extensions public C.Enumerator GetEnumerator(int x = 1) => new C.Enumerator(x); } }"; - var verifier = CompileAndVerify(source, expectedOutput: "23", parseOptions: TestOptions.RegularPreview.WithFeature("run-nullable-analysis", "never")); // Tracked by https://github.com/dotnet/roslyn/issues/76130: Nullable analysis asserts + var verifier = CompileAndVerify(source, expectedOutput: "23", parseOptions: TestOptions.RegularPreview.WithFeature("run-nullable-analysis", "never")); // Tracked by https://github.com/dotnet/roslyn/issues/76130: Nullable analysis asserts VerifyFlowGraphAndDiagnosticsForTest((CSharpCompilation)verifier.Compilation, @" @@ -32018,6 +33731,248 @@ public static class Extensions // foreach (var i in new C()) Diagnostic(ErrorCode.ERR_BadGetEnumerator, "new C()").WithArguments("C.Enumerator", "C.GetEnumerator()").WithLocation(7, 27) ); + + source = """ +using System; +public class C +{ + public static void Main() + { + foreach (var i in new C()) + { + Console.Write(i); + } + } + public sealed class Enumerator + { + public int Current { get; private set; } + } + + public C.Enumerator GetEnumerator() => new C.Enumerator(); +} +public static class Extensions +{ + public static bool MoveNext(this C.Enumerator e) => false; +} +"""; + CreateCompilation(source) + .VerifyDiagnostics( + // (6,27): error CS0117: 'C.Enumerator' does not contain a definition for 'MoveNext' + // foreach (var i in new C()) + Diagnostic(ErrorCode.ERR_NoSuchMember, "new C()").WithArguments("C.Enumerator", "MoveNext").WithLocation(6, 27), + // (6,27): error CS0202: foreach requires that the return type 'C.Enumerator' of 'C.GetEnumerator()' must have a suitable public 'MoveNext' method and public 'Current' property + // foreach (var i in new C()) + Diagnostic(ErrorCode.ERR_BadGetEnumerator, "new C()").WithArguments("C.Enumerator", "C.GetEnumerator()").WithLocation(6, 27) + ); + } + + [Fact] + public void TestMoveNextPatternViaExtensions_DelegateTypeProperty() + { + var src = """ +using System; + +foreach (var i in new C()) +{ + Console.Write(i); +} + +public class C +{ + public sealed class Enumerator + { + public int Current { get; private set; } + } + + public C.Enumerator GetEnumerator() => new C.Enumerator(); +} + +public static class Extensions +{ + extension(C.Enumerator e) + { + public System.Func MoveNext => throw null; + } +} +"""; + var comp = CreateCompilation(src); + comp.VerifyDiagnostics( + // (3,19): error CS0117: 'C.Enumerator' does not contain a definition for 'MoveNext' + // foreach (var i in new C()) + Diagnostic(ErrorCode.ERR_NoSuchMember, "new C()").WithArguments("C.Enumerator", "MoveNext").WithLocation(3, 19), + // (3,19): error CS0202: foreach requires that the return type 'C.Enumerator' of 'C.GetEnumerator()' must have a suitable public 'MoveNext' method and public 'Current' property + // foreach (var i in new C()) + Diagnostic(ErrorCode.ERR_BadGetEnumerator, "new C()").WithArguments("C.Enumerator", "C.GetEnumerator()").WithLocation(3, 19)); + + src = """ +using System; + +foreach (var i in new C()) +{ + Console.Write(i); +} + +public class C +{ + public sealed class Enumerator + { + public int Current { get; private set; } + public System.Func MoveNext => throw null; + } + + public C.Enumerator GetEnumerator() => new C.Enumerator(); +} +"""; + comp = CreateCompilation(src); + comp.VerifyDiagnostics( + // (3,19): error CS0202: foreach requires that the return type 'C.Enumerator' of 'C.GetEnumerator()' must have a suitable public 'MoveNext' method and public 'Current' property + // foreach (var i in new C()) + Diagnostic(ErrorCode.ERR_BadGetEnumerator, "new C()").WithArguments("C.Enumerator", "C.GetEnumerator()").WithLocation(3, 19)); + } + + [Fact] + public void TestMoveNextPatternViaExtensions_DynamicTypeProperty() + { + var src = """ +using System; + +foreach (var i in new C()) +{ + Console.Write(i); +} + +public class C +{ + public sealed class Enumerator + { + public int Current { get; private set; } + } + + public C.Enumerator GetEnumerator() => new C.Enumerator(); +} + +public static class Extensions +{ + extension(C.Enumerator e) + { + public System.Func MoveNext => throw null; + } +} +"""; + var comp = CreateCompilation(src); + comp.VerifyDiagnostics( + // (3,19): error CS0117: 'C.Enumerator' does not contain a definition for 'MoveNext' + // foreach (var i in new C()) + Diagnostic(ErrorCode.ERR_NoSuchMember, "new C()").WithArguments("C.Enumerator", "MoveNext").WithLocation(3, 19), + // (3,19): error CS0202: foreach requires that the return type 'C.Enumerator' of 'C.GetEnumerator()' must have a suitable public 'MoveNext' method and public 'Current' property + // foreach (var i in new C()) + Diagnostic(ErrorCode.ERR_BadGetEnumerator, "new C()").WithArguments("C.Enumerator", "C.GetEnumerator()").WithLocation(3, 19)); + + src = """ +using System; + +foreach (var i in new C()) +{ + Console.Write(i); +} + +public class C +{ + public sealed class Enumerator + { + public int Current { get; private set; } + public System.Func MoveNext => throw null; + } + + public C.Enumerator GetEnumerator() => new C.Enumerator(); +} +"""; + comp = CreateCompilation(src); + comp.VerifyDiagnostics( + // (3,19): error CS0202: foreach requires that the return type 'C.Enumerator' of 'C.GetEnumerator()' must have a suitable public 'MoveNext' method and public 'Current' property + // foreach (var i in new C()) + Diagnostic(ErrorCode.ERR_BadGetEnumerator, "new C()").WithArguments("C.Enumerator", "C.GetEnumerator()").WithLocation(3, 19)); + } + + [Fact] + public void TestMoveNextAsyncPatternViaExtensions_01() + { + var src = """ +await foreach (var i in new C()) +{ +} + +public class C +{ + public sealed class Enumerator + { + public int Current { get; private set; } + } + + public C.Enumerator GetAsyncEnumerator() => new C.Enumerator(); +} + +public static class E +{ + extension(C.Enumerator e) + { + public System.Threading.Tasks.Task MoveNextAsync() => throw null; + } +} +"""; + CreateCompilation(src).VerifyEmitDiagnostics( + // (1,25): error CS0117: 'C.Enumerator' does not contain a definition for 'MoveNextAsync' + // await foreach (var i in new C()) + Diagnostic(ErrorCode.ERR_NoSuchMember, "new C()").WithArguments("C.Enumerator", "MoveNextAsync").WithLocation(1, 25), + // (1,25): error CS8412: Asynchronous foreach requires that the return type 'C.Enumerator' of 'C.GetAsyncEnumerator()' must have a suitable public 'MoveNextAsync' method and public 'Current' property + // await foreach (var i in new C()) + Diagnostic(ErrorCode.ERR_BadGetAsyncEnumerator, "new C()").WithArguments("C.Enumerator", "C.GetAsyncEnumerator()").WithLocation(1, 25)); + + src = """ +await foreach (var i in new C()) +{ +} + +public class C +{ + public sealed class Enumerator + { + public int Current { get; private set; } + } + + public C.Enumerator GetAsyncEnumerator() => new C.Enumerator(); +} + +public static class E +{ + public static System.Threading.Tasks.Task MoveNextAsync(this C.Enumerator e) => throw null; +} +"""; + CreateCompilation(src).VerifyEmitDiagnostics( + // (1,25): error CS0117: 'C.Enumerator' does not contain a definition for 'MoveNextAsync' + // await foreach (var i in new C()) + Diagnostic(ErrorCode.ERR_NoSuchMember, "new C()").WithArguments("C.Enumerator", "MoveNextAsync").WithLocation(1, 25), + // (1,25): error CS8412: Asynchronous foreach requires that the return type 'C.Enumerator' of 'C.GetAsyncEnumerator()' must have a suitable public 'MoveNextAsync' method and public 'Current' property + // await foreach (var i in new C()) + Diagnostic(ErrorCode.ERR_BadGetAsyncEnumerator, "new C()").WithArguments("C.Enumerator", "C.GetAsyncEnumerator()").WithLocation(1, 25)); + + src = """ +await foreach (var i in new C()) +{ +} + +public class C +{ + public sealed class Enumerator + { + public int Current { get; private set; } + public System.Threading.Tasks.Task MoveNextAsync() => throw null; + } + + public C.Enumerator GetAsyncEnumerator() => new C.Enumerator(); +} +"""; + CreateCompilation(src).VerifyEmitDiagnostics(); } [Fact] @@ -33053,27 +35008,27 @@ extends [mscorlib]System.Object .class nested public auto ansi sealed beforefieldinit '<>E__0' extends [mscorlib]System.Object { - .method private hidebysig specialname static void '$' ( int32 '' ) cil managed + .method private hidebysig specialname static void '$' ( int32 '' ) cil managed { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) IL_0000: ret } - .method public hidebysig instance void M3 () cil managed + .method public hidebysig instance void M3 () cil managed { IL_0000: ldnull IL_0001: throw } - .method public hidebysig static void M4 () cil managed + .method public hidebysig static void M4 () cil managed { IL_0000: ldnull IL_0001: throw } - .method public hidebysig specialname instance int32 get_P3 () cil managed + .method public hidebysig specialname instance int32 get_P3 () cil managed { IL_0000: ldnull IL_0001: throw } - .method public hidebysig specialname static int32 get_P4 () cil managed + .method public hidebysig specialname static int32 get_P4 () cil managed { IL_0000: ldnull IL_0001: throw @@ -33087,21 +35042,21 @@ .property int32 P4() .get int32 E/'<>E__0'::get_P4() } } - .method public hidebysig static void M3 ( int32 '' ) cil managed + .method public hidebysig static void M3 ( int32 '' ) cil managed { .custom instance void [mscorlib]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) IL_0000: ret } - .method public hidebysig static void M4 () cil managed + .method public hidebysig static void M4 () cil managed { IL_0000: ret } - .method public hidebysig static int32 get_P3 ( int32 '' ) cil managed + .method public hidebysig static int32 get_P3 ( int32 '' ) cil managed { IL_0000: ldc.i4.0 IL_0001: ret } - .method public hidebysig static int32 get_P4 () cil managed + .method public hidebysig static int32 get_P4 () cil managed { IL_0000: ldc.i4.0 IL_0001: ret @@ -35139,6 +37094,243 @@ static class E Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterNotNullConstraint, "oNull").WithArguments("E.extension(T)", "T", "object?").WithLocation(4, 16)); } + [Fact] + public void Nullability_Deconstruct_05() + { + var src = """ +#nullable enable + +object o = new object(); +var (x1, x2) = o; +x1.ToString(); // 1 +x2.ToString(); + +var (y1, y2, y3) = o; +y1.ToString(); // 2 +y2.ToString(); + +static class E +{ + extension(object o) + { + public void Deconstruct(out object? o1, out object o2) => throw null!; + } + + public static void Deconstruct(this object o, out object? o1, out object o2, out int i3) => throw null!; +} +"""; + var comp = CreateCompilation(src); + comp.VerifyEmitDiagnostics( + // (5,1): warning CS8602: Dereference of a possibly null reference. + // x1.ToString(); // 1 + Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x1").WithLocation(5, 1), + // (9,1): warning CS8602: Dereference of a possibly null reference. + // y1.ToString(); // 2 + Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y1").WithLocation(9, 1)); + } + + [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/78022")] + public void Nullability_PositionalPattern_01() + { + var src = """ +#nullable enable + +object? oNull = null; +if (oNull is var (x1, x2)) +{ + x1.ToString(); +} + +object oNotNull = new object(); +if (oNotNull is var (y1, y2)) +{ + y1.ToString(); +} + +if (oNull is var (z1, z2, z3)) +{ + z1.ToString(); +} + +static class E +{ + extension(T t) + { + public void Deconstruct(out T t1, out T t2) => throw null!; + } + + public static void Deconstruct(this T t, out T t1, out T t2, out T t3) => throw null!; +} +"""; + var comp = CreateCompilation(src); + comp.VerifyEmitDiagnostics(); + + // Tracked by https://github.com/dotnet/roslyn/issues/78022 : verify nullability in the semantic model, possibly in IOperation + } + + [Fact] + public void Nullability_PositionalPattern_02() + { + var src = """ +#nullable enable + +object? oNull = null; +if (oNull is var (x1, x2)) +{ +} + +object oNotNull = new object(); +if (oNotNull is var (y1, y2)) +{ +} + +object? oNull2 = null; +if (oNull2 is var (z1, z2, z3)) +{ +} + +if (oNotNull is var (t1, t2, t3)) +{ +} + + +static class E +{ + extension(object o) + { + public void Deconstruct(out int i1, out int i2) => throw null!; + } + + public static void Deconstruct(this object o, out int i1, out int i2, out int i3) => throw null!; +} +"""; + var comp = CreateCompilation(src); + comp.VerifyEmitDiagnostics(); + // Tracked by https://github.com/dotnet/roslyn/issues/78022 : verify nullability in the semantic model, possibly in IOperation + } + + [Fact] + public void Nullability_PositionalPattern_03() + { + var src = """ +#nullable enable + +(object?, object?) oNull = default; +if (oNull is var ((x1, x2), _)) +{ +} + +(object, object) oNotNull = (new object(), new object()); +if (oNotNull is var ((y1, y2), _)) +{ +} + +(object?, object?) oNull2 = default; +if (oNull2 is var ((z1, z2, z3), _)) +{ +} + +if (oNotNull is var ((t1, t2, t3), _)) +{ +} + +static class E +{ + extension(object o) + { + public void Deconstruct(out int i1, out int i2) => throw null!; + } + public static void Deconstruct(this object o, out int i1, out int i2, out int i3) => throw null!; +} +"""; + var comp = CreateCompilation(src); + comp.VerifyEmitDiagnostics(); + } + + [Fact] + public void Nullability_PositionalPattern_04() + { + var src = """ +#nullable enable + +object? oNull = default; +if (oNull is var (x1, x2)) +{ +} +else +{ + System.Console.Write("skipped "); +} + +object oNotNull = new object(); +if (oNotNull is var (y1, y2)) +{ +} + +object? oNull2 = default; +if (oNull2 is var (z1, z2, z3)) +{ +} +else +{ + System.Console.Write(" skipped "); +} + +if (oNotNull is var (t1, t2, t3)) +{ +} + +static class E +{ + extension(T t) where T : notnull + { + public void Deconstruct(out int i1, out int i2) { System.Console.Write(t is not null); i1 = i2 = 0; } + } + public static void Deconstruct(this T t, out int i1, out int i2, out int i3) where T : notnull { System.Console.Write(t is not null); i1 = i2 = i3 = 0; } +} +"""; + var comp = CreateCompilation(src); + CompileAndVerify(comp, expectedOutput: "skipped True skipped True").VerifyDiagnostics(); + } + + [Fact] + public void Nullability_PositionalPattern_05() + { + var src = """ +#nullable enable + +object o = new object(); +if (o is var (x1, x2)) +{ + x1.ToString(); // 1 + x2.ToString(); +} + +if (o is var (y1, y2, y3)) +{ + y1.ToString(); // 2 + y2.ToString(); +} + +static class E +{ + extension(object o) + { + public void Deconstruct(out object? o1, out object o2) => throw null!; + } + public static void Deconstruct(this object o, out object? o1, out object o2, out int i3) => throw null!; +} +"""; + var comp = CreateCompilation(src); + comp.VerifyEmitDiagnostics( + // (6,5): warning CS8602: Dereference of a possibly null reference. + // x1.ToString(); // 1 + Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x1").WithLocation(6, 5), + // (12,5): warning CS8602: Dereference of a possibly null reference. + // y1.ToString(); // 2 + Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y1").WithLocation(12, 5)); + } + [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/78022")] public void Nullability_ForeachDeconstruct_01() { @@ -35279,6 +37471,45 @@ static class E Diagnostic(ErrorCode.WRN_NullReferenceArgument, "oNull").WithArguments("o", "extension(object)").WithLocation(5, 23)); } + [Fact] + public void Nullability_ForeachDeconstruct_05() + { + var src = """ +#nullable enable + +object[] o = new object[] { }; +foreach (var (x1, x2) in o) +{ + x1.ToString(); // 1 + x2.ToString(); +} + +foreach (var (y1, y2, y3) in o) +{ + y1.ToString(); // 2 + y2.ToString(); +} + +static class E +{ + extension(object o) + { + public void Deconstruct(out object? o1, out object o2) => throw null!; + } + + public static void Deconstruct(this object o, out object? o1, out object o2, out int i3) => throw null!; +} +"""; + var comp = CreateCompilation(src); + comp.VerifyEmitDiagnostics( + // (6,5): warning CS8602: Dereference of a possibly null reference. + // x1.ToString(); // 1 + Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x1").WithLocation(6, 5), + // (12,5): warning CS8602: Dereference of a possibly null reference. + // y1.ToString(); // 2 + Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y1").WithLocation(12, 5)); + } + [Fact] public void Nullability_Parameter_01() { @@ -35451,7 +37682,7 @@ static class E { extension([System.Diagnostics.CodeAnalysis.DisallowNull] object? o) { - public void M() + public void M() { o.ToString(); } @@ -35481,7 +37712,7 @@ static class E { extension([System.Diagnostics.CodeAnalysis.DisallowNull] int? i) { - public void M() + public void M() { i.Value.ToString(); } @@ -35511,7 +37742,7 @@ static class E { extension([System.Diagnostics.CodeAnalysis.AllowNull] object o) { - public void M() + public void M() { o.ToString(); } @@ -35543,7 +37774,7 @@ static class E { extension([System.Diagnostics.CodeAnalysis.NotNull] object? o) { - public void M() + public void M() { } // 1 } @@ -35581,11 +37812,11 @@ static class E { extension([System.Diagnostics.CodeAnalysis.NotNull] ref int? o) { - public void M() + public void M() { } // 1 - public void M3() + public void M3() { o = 42; } @@ -35624,7 +37855,7 @@ static class E { extension([System.Diagnostics.CodeAnalysis.NotNull] ref int? o) { - public void M(bool b = false) + public void M(bool b = false) { if (b) return; // 1 @@ -36005,6 +38236,70 @@ static class E // (13,73): error CS0103: The name 'P' does not exist in the current context // [System.Diagnostics.CodeAnalysis.MemberNotNullWhen(true, nameof(P))] Diagnostic(ErrorCode.ERR_NameNotInContext, "P").WithArguments("P").WithLocation(13, 73)); + + src = """ +#nullable enable + +object o = new object(); +if (o.M()) + o.P.ToString(); // 1 +else + o.P.ToString(); // 2 + +static class E +{ + extension(object o) + { + [System.Diagnostics.CodeAnalysis.MemberNotNullWhen(true, nameof(object.P))] + public bool M() => throw null!; + + public object? P => null; + } +} +"""; + comp = CreateCompilation(src, targetFramework: TargetFramework.Net90); + comp.VerifyEmitDiagnostics( + // (5,5): warning CS8602: Dereference of a possibly null reference. + // o.P.ToString(); // 1 + Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "o.P").WithLocation(5, 5), + // (7,5): warning CS8602: Dereference of a possibly null reference. + // o.P.ToString(); // 2 + Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "o.P").WithLocation(7, 5), + // (13,73): error CS9286: 'object' does not contain a definition for 'P' and no accessible extension member 'P' for receiver of type 'object' could be found (are you missing a using directive or an assembly reference?) + // [System.Diagnostics.CodeAnalysis.MemberNotNullWhen(true, nameof(object.P))] + Diagnostic(ErrorCode.ERR_ExtensionResolutionFailed, "object.P").WithArguments("object", "P").WithLocation(13, 73)); + + src = """ +#nullable enable + +object o = new object(); +if (o.M()) + o.P.ToString(); // 1 +else + o.P.ToString(); // 2 + +static class E +{ + extension(object o) + { + [System.Diagnostics.CodeAnalysis.MemberNotNullWhen(true, nameof(new object().P))] + public bool M() => throw null!; + + public object? P => null; + } +} +"""; + comp = CreateCompilation(src, targetFramework: TargetFramework.Net90); + comp.VerifyEmitDiagnostics( + // (5,5): warning CS8602: Dereference of a possibly null reference. + // o.P.ToString(); // 1 + Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "o.P").WithLocation(5, 5), + // (7,5): warning CS8602: Dereference of a possibly null reference. + // o.P.ToString(); // 2 + Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "o.P").WithLocation(7, 5), + // (13,73): error CS8082: Sub-expression cannot be used in an argument to nameof. + // [System.Diagnostics.CodeAnalysis.MemberNotNullWhen(true, nameof(new object().P))] + Diagnostic(ErrorCode.ERR_SubexpressionNotInNameof, "new object()").WithLocation(13, 73)); } [Fact] @@ -36233,6 +38528,470 @@ static class E Diagnostic(ErrorCode.WRN_NullReferenceArgument, "y").WithArguments("o", "void C.M(object o)").WithLocation(4, 34)); } + [Fact] + public void Nullability_ForEach_01() + { + var src = """ +#nullable enable +using System.Collections.Generic; + +object? oNull = null; +foreach (var x in oNull) { x.ToString(); } + +object? oNotNull = new object(); +foreach (var y in oNotNull) { y.ToString(); } + +static class E +{ + extension(T t) + { + public IEnumerator GetEnumerator() + { + yield return t; + } + } +} +"""; + var comp = CreateCompilation(src); + comp.VerifyEmitDiagnostics( + // (5,19): warning CS8602: Dereference of a possibly null reference. + // foreach (var x in oNull) { x.ToString(); } + Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "oNull").WithLocation(5, 19)); + + var tree = comp.SyntaxTrees.Single(); + var model = comp.GetSemanticModel(tree); + var loop = tree.GetRoot().DescendantNodes().OfType().First(); + // Tracked by https://github.com/dotnet/roslyn/issues/78022 : incorrect nullability + Assert.Equal("System.Collections.Generic.IEnumerator! E.extension(System.Object).GetEnumerator()", + model.GetForEachStatementInfo(loop).GetEnumeratorMethod.ToTestDisplayString(includeNonNullable: true)); + + src = """ +#nullable enable +using System.Collections.Generic; + +object? oNull = null; +foreach (var x in oNull) { x.ToString(); } + +object? oNotNull = new object(); +foreach (var y in oNotNull) { y.ToString(); } + +static class E +{ + public static IEnumerator GetEnumerator(this T t) + { + yield return t; + } +} +"""; + comp = CreateCompilation(src); + comp.VerifyEmitDiagnostics( + // (5,28): warning CS8602: Dereference of a possibly null reference. + // foreach (var x in oNull) { x.ToString(); } + Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(5, 28)); + + // Tracked by https://github.com/dotnet/roslyn/issues/78022 : incorrect nullability + tree = comp.SyntaxTrees.Single(); + model = comp.GetSemanticModel(tree); + loop = tree.GetRoot().DescendantNodes().OfType().First(); + Assert.Equal("System.Collections.Generic.IEnumerator! E.GetEnumerator(this System.Object t)", + model.GetForEachStatementInfo(loop).GetEnumeratorMethod.ToTestDisplayString(includeNonNullable: true)); + } + + [Fact] + public void Nullability_CollectionInitializer_01() + { + var src = """ +#nullable enable +using System.Collections; +using System.Collections.Generic; + +object? oNull = null; +object oNotNull = new object(); +MyCollection c = new MyCollection() { oNull, oNotNull }; + +static class E +{ + extension(MyCollection c) + { + public void Add(object o) { } + } +} + +public class MyCollection : IEnumerable +{ + IEnumerator IEnumerable.GetEnumerator() => throw null!; + IEnumerator IEnumerable.GetEnumerator() => throw null!; +} +"""; + var comp = CreateCompilation(src); + comp.VerifyEmitDiagnostics( + // (7,39): warning CS8604: Possible null reference argument for parameter 'o' in 'void extension(MyCollection).Add(object o)'. + // MyCollection c = new MyCollection() { oNull, oNotNull }; + Diagnostic(ErrorCode.WRN_NullReferenceArgument, "oNull").WithArguments("o", "void extension(MyCollection).Add(object o)").WithLocation(7, 39)); + } + + [Fact] + public void Nullability_CollectionExpression_Add_01() + { + var src = """ +#nullable enable +using System.Collections; +using System.Collections.Generic; + +object? oNull = null; +object oNotNull = new object(); +MyCollection c = [oNull, oNotNull]; + +static class E +{ + extension(MyCollection c) + { + public void Add(object o) { } + } +} + +public class MyCollection : IEnumerable +{ + IEnumerator IEnumerable.GetEnumerator() => throw null!; + IEnumerator IEnumerable.GetEnumerator() => throw null!; +} +"""; + // Tracked by https://github.com/dotnet/roslyn/issues/76130 : missing nullability diagnostic + var comp = CreateCompilation(src); + comp.VerifyEmitDiagnostics(); + + src = """ +#nullable enable +using System.Collections; +using System.Collections.Generic; + +object? oNull = null; +object oNotNull = new object(); +MyCollection c = [oNull, oNotNull]; + +static class E +{ + public static void Add(this MyCollection c, object o) { } +} + +public class MyCollection : IEnumerable +{ + IEnumerator IEnumerable.GetEnumerator() => throw null!; + IEnumerator IEnumerable.GetEnumerator() => throw null!; +} +"""; + // Tracked by https://github.com/dotnet/roslyn/issues/78452 : assertion hit during nullability analysis + try + { + comp = CreateCompilation(src); + comp.VerifyEmitDiagnostics(); + } + catch (InvalidOperationException) + { + } + } + + [Fact] + public void Nullability_ObjectInitializer_01() + { + var src = """ +#nullable enable + +object? oNull = null; +_ = new object() { Property = oNull }; + +object oNotNull = new object(); +_ = new object() { Property = oNotNull }; + +static class E +{ + extension(object o) + { + public object Property { set { } } + } +} +"""; + var comp = CreateCompilation(src); + comp.VerifyEmitDiagnostics( + // (4,31): warning CS8601: Possible null reference assignment. + // _ = new object() { Property = oNull }; + Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "oNull").WithLocation(4, 31)); + } + + [Fact] + public void Nullability_ObjectInitializer_02() + { + var src = """ +#nullable enable + +_ = new object() { Property = 42 }; + +static class E +{ + extension(T t) + { + public int Property { set { } } + } +} +"""; + var comp = CreateCompilation(src); + comp.VerifyEmitDiagnostics(); + + // Tracked by https://github.com/dotnet/roslyn/issues/76130 : incorrect nullability + var tree = comp.SyntaxTrees.Single(); + var model = comp.GetSemanticModel(tree); + var assignment = GetSyntax(tree, "Property = 42"); + Assert.Equal("System.Int32 E.extension(System.Object).Property { set; }", + model.GetSymbolInfo(assignment.Left).Symbol.ToTestDisplayString(includeNonNullable: true)); + } + + [Fact] + public void Nullability_With_01() + { + var src = """ +#nullable enable + +object? oNull = null; +_ = new S() with { Property = oNull }; + +object oNotNull = new object(); +_ = new S() with { Property = oNotNull }; + +struct S { } + +static class E +{ + extension(object o) + { + public object Property { set { } } + } +} +"""; + + var comp = CreateCompilation(src); + comp.VerifyEmitDiagnostics( + // (4,31): warning CS8601: Possible null reference assignment. + // _ = new S() with { Property = oNull }; + Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "oNull").WithLocation(4, 31)); + } + + [Fact] + public void Nullability_With_02() + { + var src = """ +#nullable enable + +C? cNull = null; +_ = cNull with { Property = 42 }; + +C cNotNull = new C(); +_ = cNotNull with { Property = 42 }; + +record C { } + +static class E +{ + extension(object o) + { + public int Property { set { } } + } +} +"""; + + var comp = CreateCompilation(src); + comp.VerifyEmitDiagnostics( + // (4,5): warning CS8602: Dereference of a possibly null reference. + // _ = cNull with { Property = 42 }; + Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "cNull").WithLocation(4, 5)); + } + + [Fact] + public void Nullability_With_03() + { + var src = """ +#nullable enable + +C? cNull = null; +_ = cNull with { Property = 42 }; + +C cNotNull = new C(); +_ = cNotNull with { Property = 42 }; + +record C { } + +static class E +{ + extension(object? o) + { + public int Property { set { } } + } +} +"""; + + // Tracked by https://github.com/dotnet/roslyn/issues/76130 : unexpected nullability warning + var comp = CreateCompilation(src); + comp.VerifyEmitDiagnostics( + // (4,5): warning CS8602: Dereference of a possibly null reference. + // _ = cNull with { Property = 42 }; + Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "cNull").WithLocation(4, 5)); + } + + [Fact] + public void Nullability_With_04() + { + var src = """ +#nullable enable + +C? cNull = null; +_ = cNull with { Property = 42 }; + +C cNotNull = new C(); +_ = cNotNull with { Property = 42 }; + +record C { } + +static class E +{ + extension(T t) + { + public int Property { set { } } + } +} +"""; + // Tracked by https://github.com/dotnet/roslyn/issues/76130 : unexpected nullability warning + var comp = CreateCompilation(src); + comp.VerifyEmitDiagnostics( + // (4,5): warning CS8602: Dereference of a possibly null reference. + // _ = cNull with { Property = 42 }; + Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "cNull").WithLocation(4, 5)); + } + + [Fact] + public void Nullability_With_05() + { + var src = """ +#nullable enable + +C? cNull = null; +_ = cNull with { Property = 42 }; + +C cNotNull = new C(); +_ = cNotNull with { Property = 42 }; + +record C { } + +static class E +{ + extension(T t) where T : notnull + { + public int Property { set { } } + } +} +"""; + + var comp = CreateCompilation(src); + comp.VerifyEmitDiagnostics( + // (4,5): warning CS8602: Dereference of a possibly null reference. + // _ = cNull with { Property = 42 }; + Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "cNull").WithLocation(4, 5)); + } + + [Fact] + public void Nullability_Fixed_01() + { + var src = """ +#nullable enable + +unsafe class C +{ + public static void M() + { + fixed (S* p = new Fixable()) { } // 1 + fixed (S* p = new Fixable()) { } + } +} + +class Fixable { } + +struct S { } + +static class E +{ + extension(Fixable f) + { + public ref S GetPinnableReference() => throw null!; + } +} +"""; + // We don't yet analyze the nullability of `fixed` statements for extension methods + var comp = CreateCompilation(src, options: TestOptions.UnsafeDebugDll); + comp.VerifyEmitDiagnostics(); + + src = """ +#nullable enable + +unsafe class C +{ + public static void M() + { + fixed (S* p = new Fixable()) { } // 1 + fixed (S* p = new Fixable()) { } + } +} + +class Fixable { } + +struct S { } + +static class E +{ + public static ref S GetPinnableReference(this Fixable f) => throw null!; +} +"""; + comp = CreateCompilation(src, options: TestOptions.UnsafeDebugDll); + comp.VerifyEmitDiagnostics(); + } + + [Fact] + public void Nullability_Await_GetAwaiter_01() + { + var src = """ +#nullable enable + +using System; +using System.Runtime.CompilerServices; + +C? cNull = null; +_ = await cNull; + +C cNotNull = new C(); +_ = await cNotNull; + +class C { } + +class D : INotifyCompletion +{ + public int GetResult() => 42; + public void OnCompleted(Action continuation) => throw null!; + public bool IsCompleted => true; +} + +static class E +{ + extension(C c) + { + public D GetAwaiter() => new D(); + } +} +"""; + + var comp = CreateCompilation(src); + comp.VerifyEmitDiagnostics( + // (7,11): warning CS8604: Possible null reference argument for parameter 'c' in 'extension(C)'. + // _ = await cNull; + Diagnostic(ErrorCode.WRN_NullReferenceArgument, "cNull").WithArguments("c", "extension(C)").WithLocation(7, 11)); + } + [Fact] public void BuildArgumentsForErrorRecovery_01() { @@ -36389,17 +39148,17 @@ extends [mscorlib]System.Object .class nested public auto ansi sealed beforefieldinit '<>E__0' extends [mscorlib]System.Object { - .method private hidebysig static void '$' ( int32 '' ) cil managed + .method private hidebysig static void '$' ( int32 '' ) cil managed { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) IL_0000: ret } - .method public hidebysig instance void M () cil managed + .method public hidebysig instance void M () cil managed { IL_0000: ldnull IL_0001: throw } - .method public hidebysig specialname instance int32 get_P () cil managed + .method public hidebysig specialname instance int32 get_P () cil managed { IL_0000: ldnull IL_0001: throw @@ -36409,12 +39168,12 @@ .property instance int32 P() .get instance int32 E/'<>E__0'::get_P() } } - .method public hidebysig static void M ( int32 '' ) cil managed + .method public hidebysig static void M ( int32 '' ) cil managed { .custom instance void [mscorlib]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) IL_0000: ret } - .method public hidebysig static int32 get_P ( int32 '' ) cil managed + .method public hidebysig static int32 get_P ( int32 '' ) cil managed { IL_0000: ldc.i4.0 IL_0001: ret @@ -36452,27 +39211,27 @@ extends [mscorlib]System.Object .class nested public auto ansi sealed beforefieldinit '<>E__0' extends [mscorlib]System.Object { - .method private hidebysig specialname static void '$' ( int32 '' ) cil managed + .method private hidebysig specialname static void '$' ( int32 '' ) cil managed { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) IL_0000: ret } - .method public hidebysig instance void M () cil managed + .method public hidebysig instance void M () cil managed { IL_0000: ldnull IL_0001: throw } - .method public hidebysig specialname instance void M2 () cil managed + .method public hidebysig specialname instance void M2 () cil managed { IL_0000: ldnull IL_0001: throw } - .method public hidebysig specialname instance int32 get_P () cil managed + .method public hidebysig specialname instance int32 get_P () cil managed { IL_0000: ldnull IL_0001: throw } - .method public hidebysig instance int32 get_P2 () cil managed + .method public hidebysig instance int32 get_P2 () cil managed { IL_0000: ldnull IL_0001: throw @@ -36486,22 +39245,22 @@ .property instance int32 P2() .get instance int32 E/'<>E__0'::get_P2() } } - .method public hidebysig specialname static void M ( int32 '' ) cil managed + .method public hidebysig specialname static void M ( int32 '' ) cil managed { .custom instance void [mscorlib]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) IL_0000: ret } - .method public hidebysig static void M2 ( int32 '' ) cil managed + .method public hidebysig static void M2 ( int32 '' ) cil managed { .custom instance void [mscorlib]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) IL_0000: ret } - .method public hidebysig static int32 get_P ( int32 '' ) cil managed + .method public hidebysig static int32 get_P ( int32 '' ) cil managed { IL_0000: ldc.i4.0 IL_0001: ret } - .method public hidebysig specialname static int32 get_P2 ( int32 '' ) cil managed + .method public hidebysig specialname static int32 get_P2 ( int32 '' ) cil managed { IL_0000: ldc.i4.0 IL_0001: ret @@ -37523,4 +40282,33 @@ void handleEnd(SymbolAnalysisContext context) } } } + + [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/78487")] + public void Async_01() + { + string source = """ +await System.Threading.Tasks.Task.FromResult(true).M(); +await System.Threading.Tasks.Task.M2(); + +static class E +{ + extension(System.Threading.Tasks.Task source) + { + public async System.Threading.Tasks.Task M() + { + System.Console.Write(await source); + System.Console.Write(" ran "); + } + + public static async System.Threading.Tasks.Task M2() + { + await System.Threading.Tasks.Task.FromResult(default(T)); + System.Console.Write("ran2"); + } + } +} +"""; + var comp = CreateCompilation(source); + CompileAndVerify(comp, expectedOutput: "True ran ran2").VerifyDiagnostics(); + } } diff --git a/src/roslyn/src/Compilers/CSharp/Test/Emit3/Semantics/ExtensionTests2.cs b/src/roslyn/src/Compilers/CSharp/Test/Emit3/Semantics/ExtensionTests2.cs new file mode 100644 index 00000000000..764c7a9e8c1 --- /dev/null +++ b/src/roslyn/src/Compilers/CSharp/Test/Emit3/Semantics/ExtensionTests2.cs @@ -0,0 +1,636 @@ +// 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. +#nullable disable + +using System; +using Microsoft.CodeAnalysis.CSharp.Test.Utilities; +using Microsoft.CodeAnalysis.Test.Utilities; +using Roslyn.Test.Utilities; +using Xunit; + +namespace Microsoft.CodeAnalysis.CSharp.UnitTests.Semantics; + +[CompilerTrait(CompilerFeature.Extensions)] +public partial class ExtensionTests : CompilingTestBase +{ + [Fact] + public void Deconstruct_01() + { + var src = """ +var (x, y) = ""; + +static class E +{ + extension(object o) + { + public void Deconstruct(out int i, out int j, params int[] k) => throw null; + } +} +"""; + var comp = CreateCompilation(src); + comp.VerifyEmitDiagnostics( + // (1,6): error CS8130: Cannot infer the type of implicitly-typed deconstruction variable 'x'. + // var (x, y) = ""; + Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedDeconstructionVariable, "x").WithArguments("x").WithLocation(1, 6), + // (1,9): error CS8130: Cannot infer the type of implicitly-typed deconstruction variable 'y'. + // var (x, y) = ""; + Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedDeconstructionVariable, "y").WithArguments("y").WithLocation(1, 9), + // (1,14): error CS8129: No suitable 'Deconstruct' instance or extension method was found for type 'string', with 2 out parameters and a void return type. + // var (x, y) = ""; + Diagnostic(ErrorCode.ERR_MissingDeconstruct, @"""""").WithArguments("string", "2").WithLocation(1, 14)); + } + + [Fact] + public void Deconstruct_02() + { + var src = """ +var (x, y) = ""; + +static class E +{ + extension(object o) + { + public void Deconstruct(out int i, out int j, int k = 0) => throw null; + } +} +"""; + var comp = CreateCompilation(src); + comp.VerifyEmitDiagnostics( + // (1,6): error CS8130: Cannot infer the type of implicitly-typed deconstruction variable 'x'. + // var (x, y) = ""; + Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedDeconstructionVariable, "x").WithArguments("x").WithLocation(1, 6), + // (1,9): error CS8130: Cannot infer the type of implicitly-typed deconstruction variable 'y'. + // var (x, y) = ""; + Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedDeconstructionVariable, "y").WithArguments("y").WithLocation(1, 9), + // (1,14): error CS8129: No suitable 'Deconstruct' instance or extension method was found for type 'string', with 2 out parameters and a void return type. + // var (x, y) = ""; + Diagnostic(ErrorCode.ERR_MissingDeconstruct, @"""""").WithArguments("string", "2").WithLocation(1, 14)); + } + + [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/75484")] + public void Deconstruction_UnscopedRef_ExtensionMethod() + { + var source = """ +class C +{ + R M1() + { + new S().Deconstruct(out var x, out _); + return x; // 1 + } + R M2() + { + (var x, _) = new S(); + return x; // 2 + } + R M3() + { + if (new S() is (var x, _)) + return x; // 3 + return default; + } +} +struct S; +ref struct R; +static class E +{ + extension(in S s) + { + public void Deconstruct(out R x, out int y) => throw null; + } +} +"""; + CreateCompilation(source).VerifyDiagnostics( + // (6,16): error CS8352: Cannot use variable 'x' in this context because it may expose referenced variables outside of their declaration scope + // return x; // 1 + Diagnostic(ErrorCode.ERR_EscapeVariable, "x").WithArguments("x").WithLocation(6, 16), + // (11,16): error CS8352: Cannot use variable 'x' in this context because it may expose referenced variables outside of their declaration scope + // return x; // 2 + Diagnostic(ErrorCode.ERR_EscapeVariable, "x").WithArguments("x").WithLocation(11, 16), + // (16,20): error CS8352: Cannot use variable 'x' in this context because it may expose referenced variables outside of their declaration scope + // return x; // 3 + Diagnostic(ErrorCode.ERR_EscapeVariable, "x").WithArguments("x").WithLocation(16, 20)); + } + + [Fact] + public void Deconstruction_ScopedRef_ExtensionMethod() + { + var source = """ +class C +{ + R M1() + { + new S().Deconstruct(out var x, out _); + return x; + } + R M2() + { + (var x, _) = new S(); + return x; + } + R M3() + { + if (new S() is (var x, _)) + return x; + return default; + } +} +struct S; +ref struct R; +static class E +{ + extension(scoped in S s) + { + public void Deconstruct(out R x, out int y) => throw null; + } +} +"""; + CreateCompilation(source).VerifyDiagnostics(); + } + + [Fact] + public void ForeachDeconstruct_Conversion() + { + var src = """ +C[] c = new C[] { new C() }; +foreach (var (x1, x2) in c) +{ + System.Console.Write(x1.ToString()); +} + +class C { } + +static class E +{ + extension(object o) + { + public void Deconstruct(out int i1, out int i2) { i1 = i2 = 42; } + } +} +"""; + var comp = CreateCompilation(src); + comp.VerifyEmitDiagnostics(); + CompileAndVerify(comp, expectedOutput: "42").VerifyDiagnostics(); + } + + [Fact] + public void PositionalPattern_01() + { + var src = """ +_ = "" is (i: 42, other: 43); + +static class E +{ + extension(object o) + { + public void Deconstruct(out int i, out int j) => throw null; + } +} +"""; + var comp = CreateCompilation(src); + comp.VerifyEmitDiagnostics( + // (1,19): error CS8517: The name 'other' does not match the corresponding 'Deconstruct' parameter 'j'. + // _ = "" is (i: 42, other: 43); + Diagnostic(ErrorCode.ERR_DeconstructParameterNameMismatch, "other").WithArguments("other", "j").WithLocation(1, 19)); + } + + [Fact] + public void PositionalPattern_02() + { + var src = """ +_ = new C() is var (x, y); + +class C { } + +static class E +{ + extension(object o) + { + public void Deconstruct(out int i, out int j) => throw null; + } +} +"""; + var comp = CreateCompilation(src); + comp.VerifyEmitDiagnostics(); + } + + [Fact] + public void InvocationOnNull() + { + var src = """ +null.M1(""); +null.M2(""); + +static class E +{ + extension(T t1) + { + public void M1(T t2) => throw null!; + } + + public static void M2(this T t1, T t2) => throw null!; +} +"""; + var comp = CreateCompilation(src); + comp.VerifyEmitDiagnostics( + // (1,1): error CS0023: Operator '.' cannot be applied to operand of type '' + // null.M1(""); + Diagnostic(ErrorCode.ERR_BadUnaryOp, "null.M1").WithArguments(".", "").WithLocation(1, 1), + // (2,1): error CS0023: Operator '.' cannot be applied to operand of type '' + // null.M2(""); + Diagnostic(ErrorCode.ERR_BadUnaryOp, "null.M2").WithArguments(".", "").WithLocation(2, 1)); + } + + [Fact] + public void RemoveLowerPriorityMembers_Deconstruct() + { + var src = """ +var (x, y) = ""; + +public static class E +{ + extension(object o) + { + [System.Runtime.CompilerServices.OverloadResolutionPriority(1)] + public void Deconstruct(out int i2, out int i3) { System.Console.Write("ran"); i2 = i3 = 43; } + } + extension(string s) + { + public void Deconstruct(out int i2, out int i3) => throw null; + } +} +"""; + var comp = CreateCompilation([src, OverloadResolutionPriorityAttributeDefinition]); + CompileAndVerify(comp, expectedOutput: "ran").VerifyDiagnostics(); + + src = """ +var (x, y) = ""; + +public static class E +{ + extension(object o) + { + public void Deconstruct(out int i2, out int i3) => throw null; + } + extension(string s) + { + public void Deconstruct(out int i2, out int i3) { System.Console.Write("ran"); i2 = i3 = 43; } + } +} +"""; + comp = CreateCompilation([src, OverloadResolutionPriorityAttributeDefinition]); + CompileAndVerify(comp, expectedOutput: "ran").VerifyDiagnostics(); + } + + [Fact] + public void RemoveLowerPriorityMembers_Foreach_GetEnumerator() + { + var src = """ +using System.Collections.Generic; + +foreach (var x in new C()) { System.Console.Write(x); } + +public class C { } + +public static class E +{ + extension(object o) + { + [System.Runtime.CompilerServices.OverloadResolutionPriority(1)] + public IEnumerator GetEnumerator() { yield return 42; } + } + + extension(C c) + { + public IEnumerator GetEnumerator() => throw null; + } +} +"""; + try + { + var comp = CreateCompilation([src, OverloadResolutionPriorityAttributeDefinition]); + // Tracked by https://github.com/dotnet/roslyn/issues/76130 : assertion in NullableWalker + CompileAndVerify(comp, expectedOutput: "42").VerifyDiagnostics(); + } + catch (InvalidOperationException) + { + } + } + + [Fact] + public void RemoveLowerPriorityMembers_CollectionInitializer() + { + var src = """ +using System.Collections; +using System.Collections.Generic; + +_ = new C() { 42 }; + +public class C : IEnumerable, IEnumerable +{ + IEnumerator IEnumerable.GetEnumerator() => throw null; + IEnumerator IEnumerable.GetEnumerator() => throw null; +} + +public static class E +{ + extension(object o) + { + [System.Runtime.CompilerServices.OverloadResolutionPriority(1)] + public void Add(int i) { System.Console.Write("add"); } + } + + extension(C c) + { + public void Add(int i) => throw null; + } +} +"""; + var comp = CreateCompilation([src, OverloadResolutionPriorityAttributeDefinition]); + CompileAndVerify(comp, expectedOutput: "add").VerifyDiagnostics(); + } + + [Fact] + public void RemoveLowerPriorityMembers_Fixed() + { + var src = """ +unsafe class C +{ + public static void Main() + { + fixed (int* p = new Fixable()) { } + } +} + +public class Fixable { } + +public static class E +{ + extension(object o) + { + [System.Runtime.CompilerServices.OverloadResolutionPriority(1)] + public ref int GetPinnableReference() { System.Console.Write("ran"); return ref (new int[] { 1, 2, 3 })[0]; } + } + + extension(Fixable f) + { + public ref int GetPinnableReference() => throw null; + } +} +"""; + var comp = CreateCompilation([src, OverloadResolutionPriorityAttributeDefinition], options: TestOptions.UnsafeDebugExe); + CompileAndVerify(comp, expectedOutput: "ran", verify: Verification.Skipped).VerifyDiagnostics(); + } + + [Fact] + public void RemoveLowerPriorityMembers_Await() + { + var src = """ +using System; +using System.Runtime.CompilerServices; + +int i = await new C(); +System.Console.Write(i); + +public class C { } + +public class D : INotifyCompletion +{ + public int GetResult() => 42; + public void OnCompleted(Action continuation) => throw null; + public bool IsCompleted => true; +} + +public static class E +{ + extension(object o) + { + [System.Runtime.CompilerServices.OverloadResolutionPriority(1)] + public D GetAwaiter() => new D(); + } + + extension(C c) + { + public D GetAwaiter() => throw null; + } +} +"""; + var comp = CreateCompilation([src, OverloadResolutionPriorityAttributeDefinition]); + CompileAndVerify(comp, expectedOutput: "42").VerifyDiagnostics(); + } + + [Fact] + public void RemoveLowerPriorityMembers_ObjectInitializer() + { + var src = """ +_ = new C() { Property = 42 }; + +public class C { } + +public static class E +{ + extension(object o) + { + [System.Runtime.CompilerServices.OverloadResolutionPriority(1)] + public int Property { set { System.Console.Write("property"); } } + } + + extension(C c) + { + public int Property => throw null; + } +} +"""; + var comp = CreateCompilation([src, OverloadResolutionPriorityAttributeDefinition]); + CompileAndVerify(comp, expectedOutput: "property").VerifyDiagnostics(); + } + + [Fact] + public void RemoveLowerPriorityMembers_With() + { + var src = """ +_ = new S() with { Property = 42 }; + +public struct S { } + +public static class E +{ + extension(object o) + { + [System.Runtime.CompilerServices.OverloadResolutionPriority(1)] + public int Property { set { System.Console.Write("property"); } } + } + + extension(S s) + { + public int Property { set => throw null; } + } +} +"""; + var comp = CreateCompilation([src, OverloadResolutionPriorityAttributeDefinition]); + CompileAndVerify(comp, expectedOutput: "property").VerifyDiagnostics(); + } + + [Fact] + public void RemoveLowerPriorityMembers_PropertyPattern() + { + var src = """ +_ = new C() is { Property: 42 }; + +public class C{ } + +public static class E +{ + extension(object o) + { + [System.Runtime.CompilerServices.OverloadResolutionPriority(1)] + public int Property { get { System.Console.Write("property"); return 42; } } + } + + extension(C c) + { + public int Property => throw null; + } +} +"""; + var comp = CreateCompilation([src, OverloadResolutionPriorityAttributeDefinition]); + CompileAndVerify(comp, expectedOutput: "property").VerifyDiagnostics(); + } + + [Fact] + public void AnonymousType_01() + { + var src = """ +var person = new { Name = "John", Age = 30 }; +person.M(); +person.M2(); +_ = person.P; + +public static class E +{ + extension(T t) + { + public void M() { System.Console.Write("method "); } + public int Property { get { System.Console.Write("property"); return 42; } } + } + + public static void M2(this T t) { System.Console.Write("method2 "); } +} +"""; + // Tracked by https://github.com/dotnet/roslyn/issues/76130 : should work + var comp = CreateCompilation(src); + comp.VerifyEmitDiagnostics( + // (4,12): error CS1061: '' does not contain a definition for 'P' and no accessible extension method 'P' accepting a first argument of type '' could be found (are you missing a using directive or an assembly reference?) + // _ = person.P; + Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "P").WithArguments("", "P").WithLocation(4, 12)); + } + + [Fact] + public void Attribute_01() + { + var src = """ +[My(Property = 42)] +class C { } + +public class MyAttribute : System.Attribute { } + +public static class E +{ + extension(MyAttribute a) + { + public int Property { get => throw null; set => throw null; } + } +} +"""; + var comp = CreateCompilation(src); + comp.VerifyEmitDiagnostics( + // (1,5): error CS0246: The type or namespace name 'Property' could not be found (are you missing a using directive or an assembly reference?) + // [My(Property = 42)] + Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Property").WithArguments("Property").WithLocation(1, 5)); + } + + [Fact] + public void Lock_01() + { + var src = """ +System.Threading.Lock x = new System.Threading.Lock(); +lock (x) { } + +namespace System.Threading +{ + public sealed class Lock + { + public Scope EnterScope() { System.Console.Write("ran "); return new Scope(); } + + public ref struct Scope + { + public void Dispose() { System.Console.Write("disposed"); } + } + } +} +"""; + var comp = CreateCompilation(src); + comp.VerifyEmitDiagnostics(); + CompileAndVerify(comp, expectedOutput: "ran disposed", verify: Verification.Skipped).VerifyDiagnostics(); + + src = """ +System.Threading.Lock x = new System.Threading.Lock(); +lock (x) { } + +namespace System.Threading +{ + public sealed class Lock + { + public ref struct Scope + { + public void Dispose() => throw null; + } + } +} + +public static class E +{ + extension(System.Threading.Lock x) + { + public System.Threading.Lock.Scope EnterScope() => throw null; + } +} +"""; + comp = CreateCompilation(src); + comp.VerifyEmitDiagnostics( + // (2,7): error CS0656: Missing compiler required member 'System.Threading.Lock.EnterScope' + // lock (x) { } + Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "x").WithArguments("System.Threading.Lock", "EnterScope").WithLocation(2, 7)); + + src = """ +System.Threading.Lock x = new System.Threading.Lock(); +lock (x) { } + +namespace System.Threading +{ + public sealed class Lock + { + public Scope EnterScope() => throw null; + public ref struct Scope + { + } + } +} + +public static class E +{ + extension(System.Threading.Lock.Scope x) + { + public void Dispose() => throw null; + } +} +"""; + comp = CreateCompilation(src); + comp.VerifyEmitDiagnostics( + // (2,7): error CS0656: Missing compiler required member 'System.Threading.Lock+Scope.Dispose' + // lock (x) { } + Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "x").WithArguments("System.Threading.Lock+Scope", "Dispose").WithLocation(2, 7)); + } +} + diff --git a/src/roslyn/src/Compilers/CSharp/Test/Symbol/Symbols/IndexerTests.cs b/src/roslyn/src/Compilers/CSharp/Test/Symbol/Symbols/IndexerTests.cs index 1b89d582db2..59a1be63fdb 100644 --- a/src/roslyn/src/Compilers/CSharp/Test/Symbol/Symbols/IndexerTests.cs +++ b/src/roslyn/src/Compilers/CSharp/Test/Symbol/Symbols/IndexerTests.cs @@ -10,7 +10,9 @@ using System.Linq; using System.Threading; using System.Threading.Tasks; +using Basic.Reference.Assemblies; using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE; using Microsoft.CodeAnalysis.CSharp.Syntax; @@ -19,7 +21,6 @@ using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; -using Basic.Reference.Assemblies; namespace Microsoft.CodeAnalysis.CSharp.UnitTests.Symbols { diff --git a/src/roslyn/src/Compilers/CSharp/Test/Symbol/Symbols/MockNamedTypeSymbol.cs b/src/roslyn/src/Compilers/CSharp/Test/Symbol/Symbols/MockNamedTypeSymbol.cs index 924559fed58..dc34fd235ad 100644 --- a/src/roslyn/src/Compilers/CSharp/Test/Symbol/Symbols/MockNamedTypeSymbol.cs +++ b/src/roslyn/src/Compilers/CSharp/Test/Symbol/Symbols/MockNamedTypeSymbol.cs @@ -8,6 +8,7 @@ using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.CSharp.Symbols; using Roslyn.Utilities; diff --git a/src/roslyn/src/Compilers/CSharp/Test/Symbol/Symbols/Source/BaseClassTests.cs b/src/roslyn/src/Compilers/CSharp/Test/Symbol/Symbols/Source/BaseClassTests.cs index 91342c3aa1a..3c2db5bf9e9 100644 --- a/src/roslyn/src/Compilers/CSharp/Test/Symbol/Symbols/Source/BaseClassTests.cs +++ b/src/roslyn/src/Compilers/CSharp/Test/Symbol/Symbols/Source/BaseClassTests.cs @@ -7,9 +7,10 @@ using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.CSharp.Emit; -using Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE; using Microsoft.CodeAnalysis.CSharp.Symbols; +using Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Emit; diff --git a/src/roslyn/src/Compilers/CSharp/Test/Symbol/Symbols/Source/MethodTests.cs b/src/roslyn/src/Compilers/CSharp/Test/Symbol/Symbols/Source/MethodTests.cs index d5295d03679..fd31ba1327d 100644 --- a/src/roslyn/src/Compilers/CSharp/Test/Symbol/Symbols/Source/MethodTests.cs +++ b/src/roslyn/src/Compilers/CSharp/Test/Symbol/Symbols/Source/MethodTests.cs @@ -7,6 +7,7 @@ using System; using System.Collections.Generic; using System.Linq; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.CSharp.Emit; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; diff --git a/src/roslyn/src/Compilers/CSharp/Test/Symbol/Symbols/Source/PropertyTests.cs b/src/roslyn/src/Compilers/CSharp/Test/Symbol/Symbols/Source/PropertyTests.cs index cccb6ac427a..d47c46b4a4b 100644 --- a/src/roslyn/src/Compilers/CSharp/Test/Symbol/Symbols/Source/PropertyTests.cs +++ b/src/roslyn/src/Compilers/CSharp/Test/Symbol/Symbols/Source/PropertyTests.cs @@ -6,15 +6,16 @@ using System; using System.Linq; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.CSharp.Emit; -using Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE; using Microsoft.CodeAnalysis.CSharp.Symbols; +using Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; +using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; -using Microsoft.CodeAnalysis.Emit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests.Symbols.Source { diff --git a/src/roslyn/src/Compilers/CSharp/Test/Syntax/Parsing/ExtensionsParsingTests.cs b/src/roslyn/src/Compilers/CSharp/Test/Syntax/Parsing/ExtensionsParsingTests.cs index dbd2ceed5f1..ddd91722878 100644 --- a/src/roslyn/src/Compilers/CSharp/Test/Syntax/Parsing/ExtensionsParsingTests.cs +++ b/src/roslyn/src/Compilers/CSharp/Test/Syntax/Parsing/ExtensionsParsingTests.cs @@ -752,7 +752,6 @@ class extension } EOF(); - // Tracked by https://github.com/dotnet/roslyn/issues/76130 : report error for declaring type named "extension" // Note: break from C# 13 UsingTree(""" class extension diff --git a/src/roslyn/src/Compilers/Core/AnalyzerDriver/DeclarationComputer.cs b/src/roslyn/src/Compilers/Core/AnalyzerDriver/DeclarationComputer.cs index 6ec58792e51..8d7083ebc99 100644 --- a/src/roslyn/src/Compilers/Core/AnalyzerDriver/DeclarationComputer.cs +++ b/src/roslyn/src/Compilers/Core/AnalyzerDriver/DeclarationComputer.cs @@ -7,6 +7,7 @@ using System.Diagnostics; using System.Linq; using System.Threading; +using Microsoft.CodeAnalysis.Collections; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { diff --git a/src/roslyn/src/Compilers/Core/CodeAnalysisTest/Collections/EnumerableExtensionsTests.cs b/src/roslyn/src/Compilers/Core/CodeAnalysisTest/Collections/EnumerableExtensionsTests.cs index 1258b2b53fc..34b62435ccf 100644 --- a/src/roslyn/src/Compilers/Core/CodeAnalysisTest/Collections/EnumerableExtensionsTests.cs +++ b/src/roslyn/src/Compilers/Core/CodeAnalysisTest/Collections/EnumerableExtensionsTests.cs @@ -9,6 +9,7 @@ using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; +using Microsoft.CodeAnalysis.Collections; using Roslyn.Utilities; using Xunit; diff --git a/src/roslyn/src/Compilers/Core/CodeAnalysisTest/InternalUtilities/SpecializedCollectionsTests.cs b/src/roslyn/src/Compilers/Core/CodeAnalysisTest/InternalUtilities/SpecializedCollectionsTests.cs index 74ac02e753b..f98c56efdec 100644 --- a/src/roslyn/src/Compilers/Core/CodeAnalysisTest/InternalUtilities/SpecializedCollectionsTests.cs +++ b/src/roslyn/src/Compilers/Core/CodeAnalysisTest/InternalUtilities/SpecializedCollectionsTests.cs @@ -4,11 +4,12 @@ #nullable disable -using Roslyn.Utilities; using System; using System.Collections; using System.Collections.Generic; using System.Collections.Immutable; +using Microsoft.CodeAnalysis.Collections; +using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.UnitTests.InternalUtilities diff --git a/src/roslyn/src/Compilers/Core/MSBuildTask/ManagedCompiler.cs b/src/roslyn/src/Compilers/Core/MSBuildTask/ManagedCompiler.cs index 45064b14b5a..a7b069e5641 100644 --- a/src/roslyn/src/Compilers/Core/MSBuildTask/ManagedCompiler.cs +++ b/src/roslyn/src/Compilers/Core/MSBuildTask/ManagedCompiler.cs @@ -487,10 +487,11 @@ public bool ReportIVTs get { return _store.GetOrDefault(nameof(ReportIVTs), false); } } + // Keeping this for a while to avoid failures if someone uses sdk targets that still set this. public string? CompilerType { - set { _store[nameof(CompilerType)] = value; } - get { return (string?)_store[nameof(CompilerType)]; } + set { } + get { return null; } } #endregion diff --git a/src/roslyn/src/Compilers/Core/MSBuildTask/Microsoft.CSharp.Core.targets b/src/roslyn/src/Compilers/Core/MSBuildTask/Microsoft.CSharp.Core.targets index 73990d0e430..d388befc43a 100644 --- a/src/roslyn/src/Compilers/Core/MSBuildTask/Microsoft.CSharp.Core.targets +++ b/src/roslyn/src/Compilers/Core/MSBuildTask/Microsoft.CSharp.Core.targets @@ -94,7 +94,6 @@ ChecksumAlgorithm="$(ChecksumAlgorithm)" CodeAnalysisRuleSet="$(ResolvedCodeAnalysisRuleSet)" CodePage="$(CodePage)" - CompilerType="$(RoslynCompilerType)" DebugType="$(DebugType)" DefineConstants="$(DefineConstants)" DelaySign="$(DelaySign)" diff --git a/src/roslyn/src/Compilers/Core/MSBuildTask/Microsoft.VisualBasic.Core.targets b/src/roslyn/src/Compilers/Core/MSBuildTask/Microsoft.VisualBasic.Core.targets index 865b9c099d3..768655d8e4f 100644 --- a/src/roslyn/src/Compilers/Core/MSBuildTask/Microsoft.VisualBasic.Core.targets +++ b/src/roslyn/src/Compilers/Core/MSBuildTask/Microsoft.VisualBasic.Core.targets @@ -51,7 +51,6 @@ ChecksumAlgorithm="$(ChecksumAlgorithm)" CodeAnalysisRuleSet="$(ResolvedCodeAnalysisRuleSet)" CodePage="$(CodePage)" - CompilerType="$(RoslynCompilerType)" DebugType="$(DebugType)" DefineConstants="$(FinalDefineConstants)" DelaySign="$(DelaySign)" diff --git a/src/roslyn/src/Compilers/Core/Portable/AdditionalTextFile.cs b/src/roslyn/src/Compilers/Core/Portable/AdditionalTextFile.cs index 15269be4eff..f49b6d897cf 100644 --- a/src/roslyn/src/Compilers/Core/Portable/AdditionalTextFile.cs +++ b/src/roslyn/src/Compilers/Core/Portable/AdditionalTextFile.cs @@ -5,6 +5,7 @@ using System; using System.Collections.Generic; using System.Threading; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; diff --git a/src/roslyn/src/Compilers/Core/Portable/CodeGen/ArrayMembers.cs b/src/roslyn/src/Compilers/Core/Portable/CodeGen/ArrayMembers.cs index 39662c00c56..e8993f8ba2a 100644 --- a/src/roslyn/src/Compilers/Core/Portable/CodeGen/ArrayMembers.cs +++ b/src/roslyn/src/Compilers/Core/Portable/CodeGen/ArrayMembers.cs @@ -2,12 +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.PooledObjects; -using Roslyn.Utilities; using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Collections.Immutable; +using Microsoft.CodeAnalysis.Collections; +using Microsoft.CodeAnalysis.PooledObjects; +using Roslyn.Utilities; using EmitContext = Microsoft.CodeAnalysis.Emit.EmitContext; // Contains support for pseudo-methods on multidimensional arrays. diff --git a/src/roslyn/src/Compilers/Core/Portable/Collections/TopologicalSort.cs b/src/roslyn/src/Compilers/Core/Portable/Collections/TopologicalSort.cs index e77263c01a9..63af270c3a8 100644 --- a/src/roslyn/src/Compilers/Core/Portable/Collections/TopologicalSort.cs +++ b/src/roslyn/src/Compilers/Core/Portable/Collections/TopologicalSort.cs @@ -5,6 +5,7 @@ using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Collections; using Roslyn.Utilities; diff --git a/src/roslyn/src/Compilers/Core/Portable/Collections/UnionCollection.cs b/src/roslyn/src/Compilers/Core/Portable/Collections/UnionCollection.cs index b903f907bf7..96fe931ec8a 100644 --- a/src/roslyn/src/Compilers/Core/Portable/Collections/UnionCollection.cs +++ b/src/roslyn/src/Compilers/Core/Portable/Collections/UnionCollection.cs @@ -4,11 +4,12 @@ using System; using System.Collections.Generic; +using System.Collections.Immutable; +using System.Diagnostics; using System.Linq; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.Text; -using System.Diagnostics; using Roslyn.Utilities; -using System.Collections.Immutable; namespace Microsoft.CodeAnalysis { diff --git a/src/roslyn/src/Compilers/Core/Portable/CommandLine/CommandLineParser.cs b/src/roslyn/src/Compilers/Core/Portable/CommandLine/CommandLineParser.cs index 2b49341df72..f591e49836d 100644 --- a/src/roslyn/src/Compilers/Core/Portable/CommandLine/CommandLineParser.cs +++ b/src/roslyn/src/Compilers/Core/Portable/CommandLine/CommandLineParser.cs @@ -11,6 +11,7 @@ using System.IO; using System.Linq; using System.Text; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; diff --git a/src/roslyn/src/Compilers/Core/Portable/Diagnostic/Diagnostic.cs b/src/roslyn/src/Compilers/Core/Portable/Diagnostic/Diagnostic.cs index 5e678820799..b0be6ffa7db 100644 --- a/src/roslyn/src/Compilers/Core/Portable/Diagnostic/Diagnostic.cs +++ b/src/roslyn/src/Compilers/Core/Portable/Diagnostic/Diagnostic.cs @@ -7,6 +7,7 @@ using System.Collections.Immutable; using System.Diagnostics; using System.Globalization; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; diff --git a/src/roslyn/src/Compilers/Core/Portable/Diagnostic/DiagnosticBag.cs b/src/roslyn/src/Compilers/Core/Portable/Diagnostic/DiagnosticBag.cs index 60905d04829..84ae26dbc45 100644 --- a/src/roslyn/src/Compilers/Core/Portable/Diagnostic/DiagnosticBag.cs +++ b/src/roslyn/src/Compilers/Core/Portable/Diagnostic/DiagnosticBag.cs @@ -3,13 +3,14 @@ // See the LICENSE file in the project root for more information. using System; +using System.Collections; using System.Collections.Concurrent; using System.Collections.Generic; -using System.Collections; using System.Collections.Immutable; using System.Diagnostics; using System.Text; using System.Threading; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; diff --git a/src/roslyn/src/Compilers/Core/Portable/Diagnostic/DiagnosticInfo.cs b/src/roslyn/src/Compilers/Core/Portable/Diagnostic/DiagnosticInfo.cs index a5f7c0a2303..9ab00b1f838 100644 --- a/src/roslyn/src/Compilers/Core/Portable/Diagnostic/DiagnosticInfo.cs +++ b/src/roslyn/src/Compilers/Core/Portable/Diagnostic/DiagnosticInfo.cs @@ -9,8 +9,9 @@ using System.Globalization; using System.Reflection; using System.Text.RegularExpressions; -using Roslyn.Utilities; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.Symbols; +using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { diff --git a/src/roslyn/src/Compilers/Core/Portable/Diagnostic/Diagnostic_SimpleDiagnostic.cs b/src/roslyn/src/Compilers/Core/Portable/Diagnostic/Diagnostic_SimpleDiagnostic.cs index ea1a1a02a71..fbf5d7174aa 100644 --- a/src/roslyn/src/Compilers/Core/Portable/Diagnostic/Diagnostic_SimpleDiagnostic.cs +++ b/src/roslyn/src/Compilers/Core/Portable/Diagnostic/Diagnostic_SimpleDiagnostic.cs @@ -6,6 +6,7 @@ using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.Diagnostics; using Roslyn.Utilities; diff --git a/src/roslyn/src/Compilers/Core/Portable/DiagnosticAnalyzer/AnalysisResult.cs b/src/roslyn/src/Compilers/Core/Portable/DiagnosticAnalyzer/AnalysisResult.cs index 21072149854..db297b2118b 100644 --- a/src/roslyn/src/Compilers/Core/Portable/DiagnosticAnalyzer/AnalysisResult.cs +++ b/src/roslyn/src/Compilers/Core/Portable/DiagnosticAnalyzer/AnalysisResult.cs @@ -6,6 +6,7 @@ using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.Diagnostics.Telemetry; using Roslyn.Utilities; diff --git a/src/roslyn/src/Compilers/Core/Portable/DiagnosticAnalyzer/AnalyzerManager.cs b/src/roslyn/src/Compilers/Core/Portable/DiagnosticAnalyzer/AnalyzerManager.cs index 7d27857248c..6c84f365516 100644 --- a/src/roslyn/src/Compilers/Core/Portable/DiagnosticAnalyzer/AnalyzerManager.cs +++ b/src/roslyn/src/Compilers/Core/Portable/DiagnosticAnalyzer/AnalyzerManager.cs @@ -8,6 +8,7 @@ using System.Diagnostics; using System.Threading; using System.Threading.Tasks; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; diff --git a/src/roslyn/src/Compilers/Core/Portable/Emit/CommonPEModuleBuilder.cs b/src/roslyn/src/Compilers/Core/Portable/Emit/CommonPEModuleBuilder.cs index e128038c6aa..d693f2b79a6 100644 --- a/src/roslyn/src/Compilers/Core/Portable/Emit/CommonPEModuleBuilder.cs +++ b/src/roslyn/src/Compilers/Core/Portable/Emit/CommonPEModuleBuilder.cs @@ -14,6 +14,7 @@ using System.Security.Cryptography; using System.Threading; using Microsoft.CodeAnalysis.CodeGen; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.Emit.NoPia; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Symbols; diff --git a/src/roslyn/src/Compilers/Core/Portable/Emit/ErrorType.cs b/src/roslyn/src/Compilers/Core/Portable/Emit/ErrorType.cs index 1c844f2f448..35ad9d89ffd 100644 --- a/src/roslyn/src/Compilers/Core/Portable/Emit/ErrorType.cs +++ b/src/roslyn/src/Compilers/Core/Portable/Emit/ErrorType.cs @@ -9,6 +9,7 @@ using System.Collections.Immutable; using System.Reflection; using System.Reflection.Metadata; +using Microsoft.CodeAnalysis.Collections; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Emit diff --git a/src/roslyn/src/Compilers/Core/Portable/Emit/NoPia/CommonEmbeddedMethod.cs b/src/roslyn/src/Compilers/Core/Portable/Emit/NoPia/CommonEmbeddedMethod.cs index 7f25d17f66b..84b955053a0 100644 --- a/src/roslyn/src/Compilers/Core/Portable/Emit/NoPia/CommonEmbeddedMethod.cs +++ b/src/roslyn/src/Compilers/Core/Portable/Emit/NoPia/CommonEmbeddedMethod.cs @@ -6,10 +6,11 @@ using System.Collections.Generic; using System.Collections.Immutable; -using Roslyn.Utilities; using Microsoft.CodeAnalysis.CodeGen; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.Debugging; using Microsoft.CodeAnalysis.Symbols; +using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Emit.NoPia { diff --git a/src/roslyn/src/Compilers/Core/Portable/Emit/NoPia/CommonEmbeddedType.cs b/src/roslyn/src/Compilers/Core/Portable/Emit/NoPia/CommonEmbeddedType.cs index d0e77b098a1..cee54243fa8 100644 --- a/src/roslyn/src/Compilers/Core/Portable/Emit/NoPia/CommonEmbeddedType.cs +++ b/src/roslyn/src/Compilers/Core/Portable/Emit/NoPia/CommonEmbeddedType.cs @@ -4,13 +4,14 @@ #nullable disable -using System.Collections.Immutable; -using Microsoft.CodeAnalysis.PooledObjects; -using Roslyn.Utilities; using System.Collections.Generic; +using System.Collections.Immutable; using System.Diagnostics; using System.Reflection.Metadata; +using Microsoft.CodeAnalysis.Collections; +using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Symbols; +using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Emit.NoPia { diff --git a/src/roslyn/src/Compilers/Core/Portable/Emit/NoPia/CommonEmbeddedTypeParameter.cs b/src/roslyn/src/Compilers/Core/Portable/Emit/NoPia/CommonEmbeddedTypeParameter.cs index b7d19bd66f3..36134d5d001 100644 --- a/src/roslyn/src/Compilers/Core/Portable/Emit/NoPia/CommonEmbeddedTypeParameter.cs +++ b/src/roslyn/src/Compilers/Core/Portable/Emit/NoPia/CommonEmbeddedTypeParameter.cs @@ -4,10 +4,11 @@ #nullable disable -using Roslyn.Utilities; using System; using System.Collections.Generic; using System.Reflection.Metadata; +using Microsoft.CodeAnalysis.Collections; +using Roslyn.Utilities; using Cci = Microsoft.Cci; namespace Microsoft.CodeAnalysis.Emit.NoPia diff --git a/src/roslyn/src/Compilers/Core/Portable/Emit/NoPia/VtblGap.cs b/src/roslyn/src/Compilers/Core/Portable/Emit/NoPia/VtblGap.cs index 12fe6d43652..8a00917a67f 100644 --- a/src/roslyn/src/Compilers/Core/Portable/Emit/NoPia/VtblGap.cs +++ b/src/roslyn/src/Compilers/Core/Portable/Emit/NoPia/VtblGap.cs @@ -2,9 +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. +using System.Collections.Generic; using System.Collections.Immutable; +using Microsoft.CodeAnalysis.Collections; using Roslyn.Utilities; -using System.Collections.Generic; namespace Microsoft.CodeAnalysis.Emit.NoPia { diff --git a/src/roslyn/src/Compilers/Core/Portable/MetadataReader/PEAssembly.cs b/src/roslyn/src/Compilers/Core/Portable/MetadataReader/PEAssembly.cs index 8cb21b21b3a..a3fc6af057a 100644 --- a/src/roslyn/src/Compilers/Core/Portable/MetadataReader/PEAssembly.cs +++ b/src/roslyn/src/Compilers/Core/Portable/MetadataReader/PEAssembly.cs @@ -10,6 +10,7 @@ using System.Diagnostics; using System.Reflection.Metadata; using System.Threading; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; diff --git a/src/roslyn/src/Compilers/Core/Portable/MetadataReader/PEModule.cs b/src/roslyn/src/Compilers/Core/Portable/MetadataReader/PEModule.cs index 201dc23f946..afac6f99cde 100644 --- a/src/roslyn/src/Compilers/Core/Portable/MetadataReader/PEModule.cs +++ b/src/roslyn/src/Compilers/Core/Portable/MetadataReader/PEModule.cs @@ -18,6 +18,7 @@ using System.Runtime.InteropServices; using System.Security.Cryptography; using System.Threading; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Symbols; using Roslyn.Utilities; diff --git a/src/roslyn/src/Compilers/Core/Portable/Operations/IOperation.OperationList.Reversed.cs b/src/roslyn/src/Compilers/Core/Portable/Operations/IOperation.OperationList.Reversed.cs index 2f8b0d32ff6..27744996d79 100644 --- a/src/roslyn/src/Compilers/Core/Portable/Operations/IOperation.OperationList.Reversed.cs +++ b/src/roslyn/src/Compilers/Core/Portable/Operations/IOperation.OperationList.Reversed.cs @@ -1,4 +1,4 @@ -// Licensed to the .NET Foundation under one or more agreements. +// 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. @@ -7,6 +7,7 @@ using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.Operations; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; diff --git a/src/roslyn/src/Compilers/Core/Portable/Operations/IOperation.OperationList.cs b/src/roslyn/src/Compilers/Core/Portable/Operations/IOperation.OperationList.cs index b1437b0cd1f..3a9badb836b 100644 --- a/src/roslyn/src/Compilers/Core/Portable/Operations/IOperation.OperationList.cs +++ b/src/roslyn/src/Compilers/Core/Portable/Operations/IOperation.OperationList.cs @@ -7,6 +7,7 @@ using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.Operations; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; diff --git a/src/roslyn/src/Compilers/Core/Portable/PEWriter/ManagedResource.cs b/src/roslyn/src/Compilers/Core/Portable/PEWriter/ManagedResource.cs index 098d7eac6a2..73f4fb06200 100644 --- a/src/roslyn/src/Compilers/Core/Portable/PEWriter/ManagedResource.cs +++ b/src/roslyn/src/Compilers/Core/Portable/PEWriter/ManagedResource.cs @@ -9,6 +9,7 @@ using System.IO; using System.Reflection.Metadata; using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.Collections; using Roslyn.Utilities; namespace Microsoft.Cci diff --git a/src/roslyn/src/Compilers/Core/Portable/PEWriter/MethodDefinitionBase.cs b/src/roslyn/src/Compilers/Core/Portable/PEWriter/MethodDefinitionBase.cs index 3e5e4814c3b..0e1a8b52ebf 100644 --- a/src/roslyn/src/Compilers/Core/Portable/PEWriter/MethodDefinitionBase.cs +++ b/src/roslyn/src/Compilers/Core/Portable/PEWriter/MethodDefinitionBase.cs @@ -7,6 +7,7 @@ using System.Reflection; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CodeGen; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.Debugging; using Microsoft.CodeAnalysis.Emit; using Roslyn.Utilities; diff --git a/src/roslyn/src/Compilers/Core/Portable/PEWriter/ModifiedTypeReference.cs b/src/roslyn/src/Compilers/Core/Portable/PEWriter/ModifiedTypeReference.cs index 5dfc45e1360..15a16f3b167 100644 --- a/src/roslyn/src/Compilers/Core/Portable/PEWriter/ModifiedTypeReference.cs +++ b/src/roslyn/src/Compilers/Core/Portable/PEWriter/ModifiedTypeReference.cs @@ -7,6 +7,7 @@ using System.Diagnostics; using System.Reflection.Metadata; using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.Collections; using Roslyn.Utilities; using EmitContext = Microsoft.CodeAnalysis.Emit.EmitContext; diff --git a/src/roslyn/src/Compilers/Core/Portable/PEWriter/RootModuleType.cs b/src/roslyn/src/Compilers/Core/Portable/PEWriter/RootModuleType.cs index e6f49eafe85..9b267ad0f0f 100644 --- a/src/roslyn/src/Compilers/Core/Portable/PEWriter/RootModuleType.cs +++ b/src/roslyn/src/Compilers/Core/Portable/PEWriter/RootModuleType.cs @@ -8,6 +8,7 @@ using System.Reflection.Metadata; using System.Runtime.InteropServices; using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.Collections; using Roslyn.Utilities; using EmitContext = Microsoft.CodeAnalysis.Emit.EmitContext; diff --git a/src/roslyn/src/Compilers/Core/Portable/ReferenceManager/CommonReferenceManager.Resolution.cs b/src/roslyn/src/Compilers/Core/Portable/ReferenceManager/CommonReferenceManager.Resolution.cs index c0f4b3802ff..04cfe2dcc65 100644 --- a/src/roslyn/src/Compilers/Core/Portable/ReferenceManager/CommonReferenceManager.Resolution.cs +++ b/src/roslyn/src/Compilers/Core/Portable/ReferenceManager/CommonReferenceManager.Resolution.cs @@ -11,6 +11,7 @@ using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Symbols; using Roslyn.Utilities; diff --git a/src/roslyn/src/Compilers/Core/Portable/SpecialTypeExtensions.cs b/src/roslyn/src/Compilers/Core/Portable/SpecialTypeExtensions.cs index bcca9e8a525..637192b0e06 100644 --- a/src/roslyn/src/Compilers/Core/Portable/SpecialTypeExtensions.cs +++ b/src/roslyn/src/Compilers/Core/Portable/SpecialTypeExtensions.cs @@ -273,8 +273,6 @@ public static int VBForToShiftBits(this SpecialType specialType) public static SpecialType FromRuntimeTypeOfLiteralValue(object value) { - RoslynDebug.Assert(value != null); - // Perf: Note that JIT optimizes each expression val.GetType() == typeof(T) to a single register comparison. // Also the checks are sorted by commonality of the checked types. @@ -371,7 +369,6 @@ public static bool CanOptimizeBehavior(this SpecialType specialType) /// internal static ulong ConvertUnderlyingValueToUInt64(this SpecialType enumUnderlyingType, object value) { - RoslynDebug.Assert(value != null); Debug.Assert(value.GetType().IsPrimitive); unchecked diff --git a/src/roslyn/src/Compilers/Core/Portable/Syntax/ChildSyntaxList.Reversed.cs b/src/roslyn/src/Compilers/Core/Portable/Syntax/ChildSyntaxList.Reversed.cs index 19ece1a0437..6dff7f7d53a 100644 --- a/src/roslyn/src/Compilers/Core/Portable/Syntax/ChildSyntaxList.Reversed.cs +++ b/src/roslyn/src/Compilers/Core/Portable/Syntax/ChildSyntaxList.Reversed.cs @@ -7,6 +7,7 @@ using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; +using Microsoft.CodeAnalysis.Collections; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis diff --git a/src/roslyn/src/Compilers/Core/Portable/Syntax/ChildSyntaxList.cs b/src/roslyn/src/Compilers/Core/Portable/Syntax/ChildSyntaxList.cs index 2baa5f5db30..1e807b97deb 100644 --- a/src/roslyn/src/Compilers/Core/Portable/Syntax/ChildSyntaxList.cs +++ b/src/roslyn/src/Compilers/Core/Portable/Syntax/ChildSyntaxList.cs @@ -7,6 +7,7 @@ using System.Collections.Generic; using System.Diagnostics; using System.Linq; +using Microsoft.CodeAnalysis.Collections; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis diff --git a/src/roslyn/src/Compilers/Core/Portable/Syntax/GreenNode.cs b/src/roslyn/src/Compilers/Core/Portable/Syntax/GreenNode.cs index 222883bf0ed..b5a1b4fe5ba 100644 --- a/src/roslyn/src/Compilers/Core/Portable/Syntax/GreenNode.cs +++ b/src/roslyn/src/Compilers/Core/Portable/Syntax/GreenNode.cs @@ -9,6 +9,7 @@ using System.IO; using System.Linq; using System.Runtime.CompilerServices; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Syntax.InternalSyntax; using Roslyn.Utilities; diff --git a/src/roslyn/src/Compilers/Core/Portable/Syntax/SeparatedSyntaxList.cs b/src/roslyn/src/Compilers/Core/Portable/Syntax/SeparatedSyntaxList.cs index 2322f771a3b..35678f16f4f 100644 --- a/src/roslyn/src/Compilers/Core/Portable/Syntax/SeparatedSyntaxList.cs +++ b/src/roslyn/src/Compilers/Core/Portable/Syntax/SeparatedSyntaxList.cs @@ -9,6 +9,7 @@ using System.Diagnostics; using System.Linq; using System.Runtime.CompilerServices; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; diff --git a/src/roslyn/src/Compilers/Core/Portable/Syntax/SyntaxDiffer.cs b/src/roslyn/src/Compilers/Core/Portable/Syntax/SyntaxDiffer.cs index 8768bbe40fa..803c6c33b70 100644 --- a/src/roslyn/src/Compilers/Core/Portable/Syntax/SyntaxDiffer.cs +++ b/src/roslyn/src/Compilers/Core/Portable/Syntax/SyntaxDiffer.cs @@ -7,6 +7,7 @@ using System.Diagnostics; using System.Linq; using System.Text; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; diff --git a/src/roslyn/src/Compilers/Core/Portable/Syntax/SyntaxList`1.cs b/src/roslyn/src/Compilers/Core/Portable/Syntax/SyntaxList`1.cs index f2dd5ad3ed9..e422dbd747b 100644 --- a/src/roslyn/src/Compilers/Core/Portable/Syntax/SyntaxList`1.cs +++ b/src/roslyn/src/Compilers/Core/Portable/Syntax/SyntaxList`1.cs @@ -9,6 +9,7 @@ using System.Diagnostics; using System.Linq; using System.Runtime.CompilerServices; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.Syntax; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; diff --git a/src/roslyn/src/Compilers/Core/Portable/Syntax/SyntaxNode.cs b/src/roslyn/src/Compilers/Core/Portable/Syntax/SyntaxNode.cs index dc8bddd5e1d..9274cc9d1c0 100644 --- a/src/roslyn/src/Compilers/Core/Portable/Syntax/SyntaxNode.cs +++ b/src/roslyn/src/Compilers/Core/Portable/Syntax/SyntaxNode.cs @@ -10,6 +10,7 @@ using System.Linq; using System.Text; using System.Threading; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; diff --git a/src/roslyn/src/Compilers/Core/Portable/Syntax/SyntaxNodeOrToken.cs b/src/roslyn/src/Compilers/Core/Portable/Syntax/SyntaxNodeOrToken.cs index f629a92eea7..daf3c6f763f 100644 --- a/src/roslyn/src/Compilers/Core/Portable/Syntax/SyntaxNodeOrToken.cs +++ b/src/roslyn/src/Compilers/Core/Portable/Syntax/SyntaxNodeOrToken.cs @@ -7,6 +7,7 @@ using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Runtime.InteropServices; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; diff --git a/src/roslyn/src/Compilers/Core/Portable/Syntax/SyntaxNodeOrTokenList.cs b/src/roslyn/src/Compilers/Core/Portable/Syntax/SyntaxNodeOrTokenList.cs index dec95dcb9a1..e3cea843dc4 100644 --- a/src/roslyn/src/Compilers/Core/Portable/Syntax/SyntaxNodeOrTokenList.cs +++ b/src/roslyn/src/Compilers/Core/Portable/Syntax/SyntaxNodeOrTokenList.cs @@ -9,6 +9,7 @@ using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Runtime.CompilerServices; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.Syntax; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; diff --git a/src/roslyn/src/Compilers/Core/Portable/Syntax/SyntaxToken.cs b/src/roslyn/src/Compilers/Core/Portable/Syntax/SyntaxToken.cs index af0129e4e54..1da40d13c9a 100644 --- a/src/roslyn/src/Compilers/Core/Portable/Syntax/SyntaxToken.cs +++ b/src/roslyn/src/Compilers/Core/Portable/Syntax/SyntaxToken.cs @@ -8,6 +8,7 @@ using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Runtime.InteropServices; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; diff --git a/src/roslyn/src/Compilers/Core/Portable/Syntax/SyntaxTokenList.Reversed.cs b/src/roslyn/src/Compilers/Core/Portable/Syntax/SyntaxTokenList.Reversed.cs index 6ebe6704d8f..fbc8ceeb7e3 100644 --- a/src/roslyn/src/Compilers/Core/Portable/Syntax/SyntaxTokenList.Reversed.cs +++ b/src/roslyn/src/Compilers/Core/Portable/Syntax/SyntaxTokenList.Reversed.cs @@ -8,6 +8,7 @@ using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Runtime.InteropServices; +using Microsoft.CodeAnalysis.Collections; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis diff --git a/src/roslyn/src/Compilers/Core/Portable/Syntax/SyntaxTokenList.cs b/src/roslyn/src/Compilers/Core/Portable/Syntax/SyntaxTokenList.cs index 13f561171b8..c182a9e5f01 100644 --- a/src/roslyn/src/Compilers/Core/Portable/Syntax/SyntaxTokenList.cs +++ b/src/roslyn/src/Compilers/Core/Portable/Syntax/SyntaxTokenList.cs @@ -9,6 +9,7 @@ using System.Linq; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.Syntax; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; diff --git a/src/roslyn/src/Compilers/Core/Portable/Syntax/SyntaxTrivia.cs b/src/roslyn/src/Compilers/Core/Portable/Syntax/SyntaxTrivia.cs index 690f543f1d2..42875730b38 100644 --- a/src/roslyn/src/Compilers/Core/Portable/Syntax/SyntaxTrivia.cs +++ b/src/roslyn/src/Compilers/Core/Portable/Syntax/SyntaxTrivia.cs @@ -7,6 +7,7 @@ using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Runtime.InteropServices; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; diff --git a/src/roslyn/src/Compilers/Core/Portable/Syntax/SyntaxTriviaList.Reversed.cs b/src/roslyn/src/Compilers/Core/Portable/Syntax/SyntaxTriviaList.Reversed.cs index 1636674f929..a2b9734a968 100644 --- a/src/roslyn/src/Compilers/Core/Portable/Syntax/SyntaxTriviaList.Reversed.cs +++ b/src/roslyn/src/Compilers/Core/Portable/Syntax/SyntaxTriviaList.Reversed.cs @@ -7,6 +7,7 @@ using System.Collections.Generic; using System.Diagnostics; using System.Runtime.InteropServices; +using Microsoft.CodeAnalysis.Collections; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis diff --git a/src/roslyn/src/Compilers/Core/Portable/Syntax/SyntaxTriviaList.cs b/src/roslyn/src/Compilers/Core/Portable/Syntax/SyntaxTriviaList.cs index b0d3fed6093..c5a8dd43a3e 100644 --- a/src/roslyn/src/Compilers/Core/Portable/Syntax/SyntaxTriviaList.cs +++ b/src/roslyn/src/Compilers/Core/Portable/Syntax/SyntaxTriviaList.cs @@ -9,6 +9,7 @@ using System.Linq; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Syntax; using Microsoft.CodeAnalysis.Text; diff --git a/src/roslyn/src/Compilers/Core/Portable/Text/TextChange.cs b/src/roslyn/src/Compilers/Core/Portable/Text/TextChange.cs index c6ca7b96b24..a8b72a2e504 100644 --- a/src/roslyn/src/Compilers/Core/Portable/Text/TextChange.cs +++ b/src/roslyn/src/Compilers/Core/Portable/Text/TextChange.cs @@ -6,6 +6,7 @@ using System.Collections.Generic; using System.Diagnostics; using System.Runtime.Serialization; +using Microsoft.CodeAnalysis.Collections; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Text diff --git a/src/roslyn/src/Compilers/Core/Portable/Text/TextChangeRange.cs b/src/roslyn/src/Compilers/Core/Portable/Text/TextChangeRange.cs index 3e2bcaf8dc8..48562b41f74 100644 --- a/src/roslyn/src/Compilers/Core/Portable/Text/TextChangeRange.cs +++ b/src/roslyn/src/Compilers/Core/Portable/Text/TextChangeRange.cs @@ -5,6 +5,7 @@ using System; using System.Collections.Generic; using System.Diagnostics; +using Microsoft.CodeAnalysis.Collections; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Text diff --git a/src/roslyn/src/Compilers/Core/Portable/TreeDumper.cs b/src/roslyn/src/Compilers/Core/Portable/TreeDumper.cs index fc3cf6fbabd..e6ee9ca4313 100644 --- a/src/roslyn/src/Compilers/Core/Portable/TreeDumper.cs +++ b/src/roslyn/src/Compilers/Core/Portable/TreeDumper.cs @@ -7,9 +7,10 @@ using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; -using System.Reflection; using System.Linq; +using System.Reflection; using System.Text; +using Microsoft.CodeAnalysis.Collections; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis diff --git a/src/roslyn/src/Compilers/Server/VBCSCompiler/AnalyzerConsistencyChecker.cs b/src/roslyn/src/Compilers/Server/VBCSCompiler/AnalyzerConsistencyChecker.cs index 2fdf0b39c73..1b64036cc5a 100644 --- a/src/roslyn/src/Compilers/Server/VBCSCompiler/AnalyzerConsistencyChecker.cs +++ b/src/roslyn/src/Compilers/Server/VBCSCompiler/AnalyzerConsistencyChecker.cs @@ -5,13 +5,14 @@ using System; using System.Collections.Generic; using System.Collections.Immutable; +using System.Diagnostics.CodeAnalysis; using System.IO; using System.Linq; using System.Reflection; -using Roslyn.Utilities; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.CommandLine; -using System.Diagnostics.CodeAnalysis; using Microsoft.CodeAnalysis.VisualBasic; +using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CompilerServer { diff --git a/src/roslyn/src/Compilers/Shared/GlobalAssemblyCacheHelpers/ClrGlobalAssemblyCache.cs b/src/roslyn/src/Compilers/Shared/GlobalAssemblyCacheHelpers/ClrGlobalAssemblyCache.cs index 34e8eee25ca..8975d278725 100644 --- a/src/roslyn/src/Compilers/Shared/GlobalAssemblyCacheHelpers/ClrGlobalAssemblyCache.cs +++ b/src/roslyn/src/Compilers/Shared/GlobalAssemblyCacheHelpers/ClrGlobalAssemblyCache.cs @@ -13,6 +13,7 @@ using System.Linq; using System.Reflection; using System.Runtime.InteropServices; +using Microsoft.CodeAnalysis.Collections; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis diff --git a/src/roslyn/src/Compilers/Shared/GlobalAssemblyCacheHelpers/MonoGlobalAssemblyCache.cs b/src/roslyn/src/Compilers/Shared/GlobalAssemblyCacheHelpers/MonoGlobalAssemblyCache.cs index 781683e318c..02a3bb92056 100644 --- a/src/roslyn/src/Compilers/Shared/GlobalAssemblyCacheHelpers/MonoGlobalAssemblyCache.cs +++ b/src/roslyn/src/Compilers/Shared/GlobalAssemblyCacheHelpers/MonoGlobalAssemblyCache.cs @@ -12,6 +12,7 @@ using System.Linq; using System.Reflection; using System.Text; +using Microsoft.CodeAnalysis.Collections; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis diff --git a/src/roslyn/src/Compilers/Test/Core/Compilation/TestOperationVisitor.cs b/src/roslyn/src/Compilers/Test/Core/Compilation/TestOperationVisitor.cs index 4a48fc7fe5c..895618188c2 100644 --- a/src/roslyn/src/Compilers/Test/Core/Compilation/TestOperationVisitor.cs +++ b/src/roslyn/src/Compilers/Test/Core/Compilation/TestOperationVisitor.cs @@ -9,6 +9,7 @@ using System.Collections.Immutable; using System.Diagnostics; using System.Linq; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.FlowAnalysis; using Microsoft.CodeAnalysis.Operations; using Microsoft.CodeAnalysis.PooledObjects; diff --git a/src/roslyn/src/Compilers/Test/Core/CompilationVerifier.cs b/src/roslyn/src/Compilers/Test/Core/CompilationVerifier.cs index 1571316a1a1..47d24f1c728 100644 --- a/src/roslyn/src/Compilers/Test/Core/CompilationVerifier.cs +++ b/src/roslyn/src/Compilers/Test/Core/CompilationVerifier.cs @@ -21,6 +21,7 @@ using ICSharpCode.Decompiler.Metadata; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CodeGen; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.DiaSymReader.Tools; diff --git a/src/roslyn/src/Compilers/Test/Utilities/CSharp/CSharpTestBase.cs b/src/roslyn/src/Compilers/Test/Utilities/CSharp/CSharpTestBase.cs index 0611918d426..0402daf5a45 100644 --- a/src/roslyn/src/Compilers/Test/Utilities/CSharp/CSharpTestBase.cs +++ b/src/roslyn/src/Compilers/Test/Utilities/CSharp/CSharpTestBase.cs @@ -725,7 +725,7 @@ public CompilerFeatureRequiredAttribute(string featureName) #pragma warning restore CS1591 // Missing XML comment for publicly visible type or member """; - internal const string CompilerFeatureRequiredAttributeIL = @" + internal static readonly string CompilerFeatureRequiredAttributeIL = @" .class public auto ansi sealed beforefieldinit System.Runtime.CompilerServices.CompilerFeatureRequiredAttribute extends [mscorlib]System.Attribute { @@ -813,7 +813,7 @@ public CollectionBuilderAttribute(Type builderType, string methodName) { } } """; - internal const string OverloadResolutionPriorityAttributeDefinition = """ + internal static readonly string OverloadResolutionPriorityAttributeDefinition = """ namespace System.Runtime.CompilerServices; [AttributeUsage(AttributeTargets.Method | AttributeTargets.Constructor | AttributeTargets.Property, AllowMultiple = false, Inherited = false)] @@ -823,7 +823,7 @@ public sealed class OverloadResolutionPriorityAttribute(int priority) : Attribut } """; - internal const string OverloadResolutionPriorityAttributeILDefinition = """ + internal static readonly string OverloadResolutionPriorityAttributeILDefinition = """ .class public auto ansi sealed beforefieldinit System.Runtime.CompilerServices.OverloadResolutionPriorityAttribute extends [mscorlib]System.Attribute { @@ -865,7 +865,7 @@ .property instance int32 Priority() /// /// The shape of the attribute comes from https://github.com/dotnet/runtime/issues/103430 /// - internal const string CompilerLoweringPreserveAttributeDefinition = """ + internal static readonly string CompilerLoweringPreserveAttributeDefinition = """ namespace System.Runtime.CompilerServices { [AttributeUsage(AttributeTargets.Class, Inherited = false)] @@ -876,6 +876,360 @@ public CompilerLoweringPreserveAttribute() { } } """; + #region A string containing expression-tree dumping utilities + protected static readonly string ExpressionTestLibrary = """ +using System; +using System.Globalization; +using System.Linq.Expressions; +using System.Text; + +public class TestBase +{ + protected static void DCheck(Expression e, string expected) { Check(e.Dump(), expected); } + protected static void Check(Expression> e, string expected) { Check(e.Dump(), expected); } + protected static void Check(Expression> e, string expected) { Check(e.Dump(), expected); } + protected static void Check(Expression> e, string expected) { Check(e.Dump(), expected); } + protected static void Check(Expression> e, string expected) { Check(e.Dump(), expected); } + protected static string ToString(Expression> e) { return e.Dump(); } + protected static string ToString(Expression> e) { return e.Dump(); } + protected static string ToString(Expression> e) { return e.Dump(); } + private static void Check(string actual, string expected) + { + if (expected != actual) + { + Console.WriteLine("FAIL"); + Console.WriteLine("expected: " + expected); + Console.WriteLine("actual: " + actual); + } + } +} + +public static class ExpressionExtensions +{ + public static string Dump(this Expression self) + { + return ExpressionPrinter.Print(self.Body); + } +} + +class ExpressionPrinter : System.Linq.Expressions.ExpressionVisitor +{ + private StringBuilder s = new StringBuilder(); + + public static string Print(Expression e) + { + var p = new ExpressionPrinter(); + p.Visit(e); + return p.s.ToString(); + } + + public override Expression Visit(Expression node) + { + if (node == null) { s.Append("null"); return null; } + s.Append(node.NodeType.ToString()); + s.Append("("); + base.Visit(node); + s.Append(" Type:" + node.Type); + s.Append(")"); + return null; + } + + protected override MemberBinding VisitMemberBinding(MemberBinding node) + { + if (node == null) { s.Append("null"); return null; } + return base.VisitMemberBinding(node); + } + + protected override MemberMemberBinding VisitMemberMemberBinding(MemberMemberBinding node) + { + s.Append("MemberMemberBinding(Member="); + s.Append(node.Member.ToString()); + foreach (var b in node.Bindings) + { + s.Append(" "); + VisitMemberBinding(b); + } + s.Append(")"); + return null; + } + + protected override MemberListBinding VisitMemberListBinding(MemberListBinding node) + { + s.Append("MemberListBinding(Member="); + s.Append(node.Member.ToString()); + foreach (var i in node.Initializers) + { + s.Append(" "); + VisitElementInit(i); + } + s.Append(")"); + return null; + } + + protected override MemberAssignment VisitMemberAssignment(MemberAssignment node) + { + s.Append("MemberAssignment(Member="); + s.Append(node.Member.ToString()); + s.Append(" Expression="); + Visit(node.Expression); + s.Append(")"); + return null; + } + + protected override Expression VisitMemberInit(MemberInitExpression node) + { + s.Append("NewExpression: "); + Visit(node.NewExpression); + s.Append(" Bindings:["); + bool first = true; + foreach (var b in node.Bindings) + { + if (!first) s.Append(" "); + VisitMemberBinding(b); + first = false; + } + s.Append("]"); + return null; + } + + protected override Expression VisitBinary(BinaryExpression node) + { + Visit(node.Left); + s.Append(" "); + Visit(node.Right); + if (node.Conversion != null) + { + s.Append(" Conversion:"); + Visit(node.Conversion); + } + if (node.IsLifted) s.Append(" Lifted"); + if (node.IsLiftedToNull) s.Append(" LiftedToNull"); + if (node.Method != null) s.Append(" Method:[" + node.Method + "]"); + return null; + } + + protected override Expression VisitConditional(ConditionalExpression node) + { + Visit(node.Test); + s.Append(" ? "); + Visit(node.IfTrue); + s.Append(" : "); + Visit(node.IfFalse); + return null; + } + + protected override Expression VisitConstant(ConstantExpression node) + { + s.Append(node.Value == null ? "null" : GetCultureInvariantString(node.Value)); + return null; + } + + protected override Expression VisitDefault(DefaultExpression node) + { + return null; + } + + protected override Expression VisitIndex(IndexExpression node) + { + Visit(node.Object); + s.Append("["); + int n = node.Arguments.Count; + for (int i = 0; i < n; i++) + { + if (i != 0) s.Append(" "); + Visit(node.Arguments[i]); + } + s.Append("]"); + if (node.Indexer != null) s.Append(" Indexer:" + node.Indexer); + return null; + } + + protected override Expression VisitInvocation(InvocationExpression node) + { + Visit(node.Expression); + s.Append("("); + int n = node.Arguments.Count; + for (int i = 0; i < n; i++) + { + if (i != 0) s.Append(" "); + Visit(node.Arguments[i]); + } + s.Append(")"); + return null; + } + + protected override Expression VisitLambda(Expression node) + { + s.Append("("); + int n = node.Parameters.Count; + for (int i = 0; i < n; i++) + { + if (i != 0) s.Append(" "); + Visit(node.Parameters[i]); + } + s.Append(") => "); + if (node.Name != null) s.Append(node.Name); + Visit(node.Body); + if (node.ReturnType != null) s.Append(" ReturnType:" + node.ReturnType); + if (node.TailCall) s.Append(" TailCall"); + return null; + } + + protected override Expression VisitListInit(ListInitExpression node) + { + Visit(node.NewExpression); + s.Append("{"); + int n = node.Initializers.Count; + for (int i = 0; i < n; i++) + { + if (i != 0) s.Append(" "); + Visit(node.Initializers[i]); + } + s.Append("}"); + return null; + } + + protected override ElementInit VisitElementInit(ElementInit node) + { + Visit(node); + return null; + } + + private void Visit(ElementInit node) + { + s.Append("ElementInit("); + s.Append(node.AddMethod); + int n = node.Arguments.Count; + for (int i = 0; i < n; i++) + { + s.Append(" "); + Visit(node.Arguments[i]); + } + s.Append(")"); + } + + protected override Expression VisitMember(MemberExpression node) + { + Visit(node.Expression); + s.Append("."); + s.Append(node.Member.Name); + return null; + } + + protected override Expression VisitMethodCall(MethodCallExpression node) + { + Visit(node.Object); + s.Append(".[" + node.Method + "]"); + s.Append("("); + int n = node.Arguments.Count; + for (int i = 0; i < n; i++) + { + if (i != 0) s.Append(", "); + Visit(node.Arguments[i]); + } + s.Append(")"); + return null; + } + + protected override Expression VisitNew(NewExpression node) + { + s.Append((node.Constructor != null) ? "[" + node.Constructor + "]" : "<.ctor>"); + s.Append("("); + int n = node.Arguments.Count; + for (int i = 0; i < n; i++) + { + if (i != 0) s.Append(", "); + Visit(node.Arguments[i]); + } + s.Append(")"); + if (node.Members != null) + { + n = node.Members.Count; + if (n != 0) + { + s.Append("{"); + for (int i = 0; i < n; i++) + { + var info = node.Members[i]; + if (i != 0) s.Append(" "); + s.Append(info); + } + s.Append("}"); + } + } + return null; + } + + protected override Expression VisitNewArray(NewArrayExpression node) + { + s.Append("["); + int n = node.Expressions.Count; + for (int i = 0; i < n; i++) + { + if (i != 0) s.Append(" "); + Visit(node.Expressions[i]); + } + s.Append("]"); + return null; + } + + protected override Expression VisitParameter(ParameterExpression node) + { + s.Append(node.Name); + if (node.IsByRef) s.Append(" ByRef"); + return null; + } + + protected override Expression VisitTypeBinary(TypeBinaryExpression node) + { + Visit(node.Expression); + s.Append(" TypeOperand:" + node.TypeOperand); + return null; + } + + protected override Expression VisitUnary(UnaryExpression node) + { + Visit(node.Operand); + if (node.IsLifted) s.Append(" Lifted"); + if (node.IsLiftedToNull) s.Append(" LiftedToNull"); + if (node.Method != null) s.Append(" Method:[" + node.Method + "]"); + return null; + } + + public static string GetCultureInvariantString(object value) + { + var valueType = value.GetType(); + if (valueType == typeof(string)) + { + return value as string; + } + + if (valueType == typeof(DateTime)) + { + return ((DateTime)value).ToString("M/d/yyyy h:mm:ss tt", CultureInfo.InvariantCulture); + } + + if (valueType == typeof(float)) + { + return ((float)value).ToString(CultureInfo.InvariantCulture); + } + + if (valueType == typeof(double)) + { + return ((double)value).ToString(CultureInfo.InvariantCulture); + } + + if (valueType == typeof(decimal)) + { + return ((decimal)value).ToString(CultureInfo.InvariantCulture); + } + + return value.ToString(); + } +} +"""; + #endregion A string containing expression-tree dumping utilities + protected static T GetSyntax(SyntaxTree tree, string text) where T : notnull { diff --git a/src/roslyn/src/Compilers/Test/Utilities/VisualBasic/MockSymbols.vb b/src/roslyn/src/Compilers/Test/Utilities/VisualBasic/MockSymbols.vb index 37798a724c3..9d0a014f5b5 100644 --- a/src/roslyn/src/Compilers/Test/Utilities/VisualBasic/MockSymbols.vb +++ b/src/roslyn/src/Compilers/Test/Utilities/VisualBasic/MockSymbols.vb @@ -6,6 +6,7 @@ Imports System.Collections.Immutable Imports System.Reflection Imports System.Runtime.InteropServices Imports System.Threading +Imports Microsoft.CodeAnalysis.Collections Imports Microsoft.CodeAnalysis.PooledObjects Friend Interface IMockSymbol diff --git a/src/roslyn/src/Compilers/VisualBasic/BasicAnalyzerDriver/VisualBasicDeclarationComputer.vb b/src/roslyn/src/Compilers/VisualBasic/BasicAnalyzerDriver/VisualBasicDeclarationComputer.vb index d42d491c978..c35a580baef 100644 --- a/src/roslyn/src/Compilers/VisualBasic/BasicAnalyzerDriver/VisualBasicDeclarationComputer.vb +++ b/src/roslyn/src/Compilers/VisualBasic/BasicAnalyzerDriver/VisualBasicDeclarationComputer.vb @@ -4,6 +4,7 @@ Imports System.Collections.Immutable Imports System.Threading +Imports Microsoft.CodeAnalysis.Collections Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Syntax diff --git a/src/roslyn/src/Compilers/VisualBasic/Portable/Analysis/FlowAnalysis/AlwaysAssignedWalker.vb b/src/roslyn/src/Compilers/VisualBasic/Portable/Analysis/FlowAnalysis/AlwaysAssignedWalker.vb index 369b843e530..0eb0e947546 100644 --- a/src/roslyn/src/Compilers/VisualBasic/Portable/Analysis/FlowAnalysis/AlwaysAssignedWalker.vb +++ b/src/roslyn/src/Compilers/VisualBasic/Portable/Analysis/FlowAnalysis/AlwaysAssignedWalker.vb @@ -3,6 +3,7 @@ ' See the LICENSE file in the project root for more information. Imports System.Collections.Generic +Imports Microsoft.CodeAnalysis.Collections Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax diff --git a/src/roslyn/src/Compilers/VisualBasic/Portable/Analysis/FlowAnalysis/EntryPointsWalker.vb b/src/roslyn/src/Compilers/VisualBasic/Portable/Analysis/FlowAnalysis/EntryPointsWalker.vb index 5ea7919d9c2..52f957e84af 100644 --- a/src/roslyn/src/Compilers/VisualBasic/Portable/Analysis/FlowAnalysis/EntryPointsWalker.vb +++ b/src/roslyn/src/Compilers/VisualBasic/Portable/Analysis/FlowAnalysis/EntryPointsWalker.vb @@ -4,6 +4,7 @@ Imports System.Collections.Generic Imports System.Linq +Imports Microsoft.CodeAnalysis.Collections Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax diff --git a/src/roslyn/src/Compilers/VisualBasic/Portable/Analysis/FlowAnalysis/ExitPointsWalker.vb b/src/roslyn/src/Compilers/VisualBasic/Portable/Analysis/FlowAnalysis/ExitPointsWalker.vb index 0cc61ad2899..3e29e2922a4 100644 --- a/src/roslyn/src/Compilers/VisualBasic/Portable/Analysis/FlowAnalysis/ExitPointsWalker.vb +++ b/src/roslyn/src/Compilers/VisualBasic/Portable/Analysis/FlowAnalysis/ExitPointsWalker.vb @@ -4,6 +4,7 @@ Imports System.Collections.Generic Imports System.Diagnostics +Imports Microsoft.CodeAnalysis.Collections Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols diff --git a/src/roslyn/src/Compilers/VisualBasic/Portable/Analysis/FlowAnalysis/VariablesDeclaredWalker.vb b/src/roslyn/src/Compilers/VisualBasic/Portable/Analysis/FlowAnalysis/VariablesDeclaredWalker.vb index 214ab51441f..4911b4b01e1 100644 --- a/src/roslyn/src/Compilers/VisualBasic/Portable/Analysis/FlowAnalysis/VariablesDeclaredWalker.vb +++ b/src/roslyn/src/Compilers/VisualBasic/Portable/Analysis/FlowAnalysis/VariablesDeclaredWalker.vb @@ -3,6 +3,7 @@ ' See the LICENSE file in the project root for more information. Imports System.Collections.Generic +Imports Microsoft.CodeAnalysis.Collections Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax diff --git a/src/roslyn/src/Compilers/VisualBasic/Portable/CommandLine/VisualBasicCommandLineParser.vb b/src/roslyn/src/Compilers/VisualBasic/Portable/CommandLine/VisualBasicCommandLineParser.vb index 1911ad1aab9..70dfaf80e5c 100644 --- a/src/roslyn/src/Compilers/VisualBasic/Portable/CommandLine/VisualBasicCommandLineParser.vb +++ b/src/roslyn/src/Compilers/VisualBasic/Portable/CommandLine/VisualBasicCommandLineParser.vb @@ -8,6 +8,7 @@ Imports System.IO Imports System.Runtime.InteropServices Imports System.Security.Cryptography Imports System.Text +Imports Microsoft.CodeAnalysis.Collections Imports Microsoft.CodeAnalysis.Emit Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.Text diff --git a/src/roslyn/src/Compilers/VisualBasic/Portable/Compilation/VisualBasicCompilation.vb b/src/roslyn/src/Compilers/VisualBasic/Portable/Compilation/VisualBasicCompilation.vb index 78216504415..a69866bb64c 100644 --- a/src/roslyn/src/Compilers/VisualBasic/Portable/Compilation/VisualBasicCompilation.vb +++ b/src/roslyn/src/Compilers/VisualBasic/Portable/Compilation/VisualBasicCompilation.vb @@ -14,6 +14,7 @@ Imports System.Threading.Tasks Imports Microsoft.Cci Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.CodeGen +Imports Microsoft.CodeAnalysis.Collections Imports Microsoft.CodeAnalysis.Diagnostics Imports Microsoft.CodeAnalysis.Emit Imports Microsoft.CodeAnalysis.InternalUtilities diff --git a/src/roslyn/src/Compilers/VisualBasic/Portable/Emit/AssemblyReference.vb b/src/roslyn/src/Compilers/VisualBasic/Portable/Emit/AssemblyReference.vb index 640bb432aae..ca26a015617 100644 --- a/src/roslyn/src/Compilers/VisualBasic/Portable/Emit/AssemblyReference.vb +++ b/src/roslyn/src/Compilers/VisualBasic/Portable/Emit/AssemblyReference.vb @@ -4,6 +4,7 @@ Imports System.Collections.Immutable Imports System.Reflection +Imports Microsoft.CodeAnalysis.Collections Imports Microsoft.CodeAnalysis.Emit Imports Microsoft.CodeAnalysis.VisualBasic.Symbols diff --git a/src/roslyn/src/Compilers/VisualBasic/Portable/Emit/EditAndContinue/EmitHelpers.vb b/src/roslyn/src/Compilers/VisualBasic/Portable/Emit/EditAndContinue/EmitHelpers.vb index c8447c76414..3d7544b5909 100644 --- a/src/roslyn/src/Compilers/VisualBasic/Portable/Emit/EditAndContinue/EmitHelpers.vb +++ b/src/roslyn/src/Compilers/VisualBasic/Portable/Emit/EditAndContinue/EmitHelpers.vb @@ -8,6 +8,7 @@ Imports System.Reflection.Metadata Imports System.Runtime.InteropServices Imports System.Threading Imports Microsoft.CodeAnalysis.CodeGen +Imports Microsoft.CodeAnalysis.Collections Imports Microsoft.CodeAnalysis.Emit Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.VisualBasic.Symbols diff --git a/src/roslyn/src/Compilers/VisualBasic/Portable/Emit/ModuleReference.vb b/src/roslyn/src/Compilers/VisualBasic/Portable/Emit/ModuleReference.vb index 0466f5c29bd..0869a3ed2fb 100644 --- a/src/roslyn/src/Compilers/VisualBasic/Portable/Emit/ModuleReference.vb +++ b/src/roslyn/src/Compilers/VisualBasic/Portable/Emit/ModuleReference.vb @@ -4,6 +4,7 @@ Imports System.Collections.Immutable Imports System.Reflection +Imports Microsoft.CodeAnalysis.Collections Imports Microsoft.CodeAnalysis.Emit Imports Microsoft.CodeAnalysis.VisualBasic.Symbols diff --git a/src/roslyn/src/Compilers/VisualBasic/Portable/Emit/NamedTypeReference.vb b/src/roslyn/src/Compilers/VisualBasic/Portable/Emit/NamedTypeReference.vb index 81e2608acb9..255440952c2 100644 --- a/src/roslyn/src/Compilers/VisualBasic/Portable/Emit/NamedTypeReference.vb +++ b/src/roslyn/src/Compilers/VisualBasic/Portable/Emit/NamedTypeReference.vb @@ -3,6 +3,7 @@ ' See the LICENSE file in the project root for more information. Imports System.Reflection.Metadata +Imports Microsoft.CodeAnalysis.Collections Imports Microsoft.CodeAnalysis.Emit Imports Microsoft.CodeAnalysis.VisualBasic.Symbols diff --git a/src/roslyn/src/Compilers/VisualBasic/Portable/Emit/NamedTypeSymbolAdapter.vb b/src/roslyn/src/Compilers/VisualBasic/Portable/Emit/NamedTypeSymbolAdapter.vb index 480f0e324e3..d443dd442e4 100644 --- a/src/roslyn/src/Compilers/VisualBasic/Portable/Emit/NamedTypeSymbolAdapter.vb +++ b/src/roslyn/src/Compilers/VisualBasic/Portable/Emit/NamedTypeSymbolAdapter.vb @@ -6,6 +6,7 @@ Imports System.Collections.Immutable Imports System.Reflection.Metadata Imports System.Runtime.InteropServices Imports Microsoft.Cci +Imports Microsoft.CodeAnalysis.Collections Imports Microsoft.CodeAnalysis.Emit Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.VisualBasic.Emit diff --git a/src/roslyn/src/Compilers/VisualBasic/Portable/Emit/PEModuleBuilder.vb b/src/roslyn/src/Compilers/VisualBasic/Portable/Emit/PEModuleBuilder.vb index 488e727e9be..faefdac0799 100644 --- a/src/roslyn/src/Compilers/VisualBasic/Portable/Emit/PEModuleBuilder.vb +++ b/src/roslyn/src/Compilers/VisualBasic/Portable/Emit/PEModuleBuilder.vb @@ -7,6 +7,7 @@ Imports System.Collections.Immutable Imports System.Reflection.PortableExecutable Imports System.Runtime.InteropServices Imports Microsoft.CodeAnalysis.CodeGen +Imports Microsoft.CodeAnalysis.Collections Imports Microsoft.CodeAnalysis.Emit Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.Symbols diff --git a/src/roslyn/src/Compilers/VisualBasic/Portable/Emit/PENetModuleBuilder.vb b/src/roslyn/src/Compilers/VisualBasic/Portable/Emit/PENetModuleBuilder.vb index e120c58453b..5627931e3ab 100644 --- a/src/roslyn/src/Compilers/VisualBasic/Portable/Emit/PENetModuleBuilder.vb +++ b/src/roslyn/src/Compilers/VisualBasic/Portable/Emit/PENetModuleBuilder.vb @@ -4,6 +4,7 @@ Imports System.Collections.Immutable Imports System.Runtime.InteropServices +Imports Microsoft.CodeAnalysis.Collections Imports Microsoft.CodeAnalysis.Emit Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.Symbols diff --git a/src/roslyn/src/Compilers/VisualBasic/Portable/Emit/SymbolAdapter.vb b/src/roslyn/src/Compilers/VisualBasic/Portable/Emit/SymbolAdapter.vb index 24f1d61b763..c1cfe59e007 100644 --- a/src/roslyn/src/Compilers/VisualBasic/Portable/Emit/SymbolAdapter.vb +++ b/src/roslyn/src/Compilers/VisualBasic/Portable/Emit/SymbolAdapter.vb @@ -3,6 +3,7 @@ ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable +Imports Microsoft.CodeAnalysis.Collections Imports Microsoft.CodeAnalysis.Emit Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.VisualBasic.Emit diff --git a/src/roslyn/src/Compilers/VisualBasic/Portable/Emit/TypeMemberReference.vb b/src/roslyn/src/Compilers/VisualBasic/Portable/Emit/TypeMemberReference.vb index 0071a89ee60..725755aff90 100644 --- a/src/roslyn/src/Compilers/VisualBasic/Portable/Emit/TypeMemberReference.vb +++ b/src/roslyn/src/Compilers/VisualBasic/Portable/Emit/TypeMemberReference.vb @@ -2,6 +2,7 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. +Imports Microsoft.CodeAnalysis.Collections Imports Microsoft.CodeAnalysis.Emit Namespace Microsoft.CodeAnalysis.VisualBasic.Emit diff --git a/src/roslyn/src/Compilers/VisualBasic/Portable/Lowering/LambdaRewriter/LambdaFrame.vb b/src/roslyn/src/Compilers/VisualBasic/Portable/Lowering/LambdaRewriter/LambdaFrame.vb index 93314cd1171..d703e55539d 100644 --- a/src/roslyn/src/Compilers/VisualBasic/Portable/Lowering/LambdaRewriter/LambdaFrame.vb +++ b/src/roslyn/src/Compilers/VisualBasic/Portable/Lowering/LambdaRewriter/LambdaFrame.vb @@ -4,6 +4,7 @@ Imports System.Collections.Immutable Imports Microsoft.CodeAnalysis.CodeGen +Imports Microsoft.CodeAnalysis.Collections Imports Microsoft.CodeAnalysis.Emit Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.Symbols diff --git a/src/roslyn/src/Compilers/VisualBasic/Portable/Lowering/LocalRewriter/LocalRewriter.vb b/src/roslyn/src/Compilers/VisualBasic/Portable/Lowering/LocalRewriter/LocalRewriter.vb index 9af1c39240d..f0578456d30 100644 --- a/src/roslyn/src/Compilers/VisualBasic/Portable/Lowering/LocalRewriter/LocalRewriter.vb +++ b/src/roslyn/src/Compilers/VisualBasic/Portable/Lowering/LocalRewriter/LocalRewriter.vb @@ -4,6 +4,7 @@ Imports System.Collections.Immutable Imports System.Runtime.InteropServices +Imports Microsoft.CodeAnalysis.Collections Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.VisualBasic.Emit Imports Microsoft.CodeAnalysis.VisualBasic.Symbols diff --git a/src/roslyn/src/Compilers/VisualBasic/Portable/Lowering/Rewriter.vb b/src/roslyn/src/Compilers/VisualBasic/Portable/Lowering/Rewriter.vb index 6026efc4c42..61ff9f9faa3 100644 --- a/src/roslyn/src/Compilers/VisualBasic/Portable/Lowering/Rewriter.vb +++ b/src/roslyn/src/Compilers/VisualBasic/Portable/Lowering/Rewriter.vb @@ -6,6 +6,7 @@ Imports System.Collections.Immutable Imports System.Diagnostics.CodeAnalysis Imports System.Runtime.InteropServices Imports Microsoft.CodeAnalysis.CodeGen +Imports Microsoft.CodeAnalysis.Collections Imports Microsoft.CodeAnalysis.Emit Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.VisualBasic.Symbols diff --git a/src/roslyn/src/Compilers/VisualBasic/Portable/Symbols/AnonymousTypes/PublicSymbols/AnonymousTypeOrDelegatePublicSymbol.vb b/src/roslyn/src/Compilers/VisualBasic/Portable/Symbols/AnonymousTypes/PublicSymbols/AnonymousTypeOrDelegatePublicSymbol.vb index bc857323df1..2a9bca8aabd 100644 --- a/src/roslyn/src/Compilers/VisualBasic/Portable/Symbols/AnonymousTypes/PublicSymbols/AnonymousTypeOrDelegatePublicSymbol.vb +++ b/src/roslyn/src/Compilers/VisualBasic/Portable/Symbols/AnonymousTypes/PublicSymbols/AnonymousTypeOrDelegatePublicSymbol.vb @@ -5,6 +5,7 @@ Imports System.Collections.Immutable Imports System.Runtime.InteropServices Imports System.Threading +Imports Microsoft.CodeAnalysis.Collections Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols Partial Friend NotInheritable Class AnonymousTypeManager diff --git a/src/roslyn/src/Compilers/VisualBasic/Portable/Symbols/AnonymousTypes/SynthesizedSymbols/AnonymousDelegate_TemplateSymbol.vb b/src/roslyn/src/Compilers/VisualBasic/Portable/Symbols/AnonymousTypes/SynthesizedSymbols/AnonymousDelegate_TemplateSymbol.vb index 886a32095f4..898f7c26c9a 100644 --- a/src/roslyn/src/Compilers/VisualBasic/Portable/Symbols/AnonymousTypes/SynthesizedSymbols/AnonymousDelegate_TemplateSymbol.vb +++ b/src/roslyn/src/Compilers/VisualBasic/Portable/Symbols/AnonymousTypes/SynthesizedSymbols/AnonymousDelegate_TemplateSymbol.vb @@ -5,6 +5,7 @@ Imports System.Collections.Generic Imports System.Collections.Immutable Imports Microsoft.CodeAnalysis +Imports Microsoft.CodeAnalysis.Collections Imports Microsoft.CodeAnalysis.Emit Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.VisualBasic.Emit diff --git a/src/roslyn/src/Compilers/VisualBasic/Portable/Symbols/AnonymousTypes/SynthesizedSymbols/AnonymousTypeOrDelegateTemplateSymbol.vb b/src/roslyn/src/Compilers/VisualBasic/Portable/Symbols/AnonymousTypes/SynthesizedSymbols/AnonymousTypeOrDelegateTemplateSymbol.vb index 5ded985e984..1f552361c02 100644 --- a/src/roslyn/src/Compilers/VisualBasic/Portable/Symbols/AnonymousTypes/SynthesizedSymbols/AnonymousTypeOrDelegateTemplateSymbol.vb +++ b/src/roslyn/src/Compilers/VisualBasic/Portable/Symbols/AnonymousTypes/SynthesizedSymbols/AnonymousTypeOrDelegateTemplateSymbol.vb @@ -7,6 +7,7 @@ Imports System.Runtime.InteropServices Imports System.Threading Imports Microsoft.Cci Imports Microsoft.CodeAnalysis +Imports Microsoft.CodeAnalysis.Collections Imports Microsoft.CodeAnalysis.Emit Imports Microsoft.CodeAnalysis.Symbols diff --git a/src/roslyn/src/Compilers/VisualBasic/Portable/Symbols/ErrorMethodSymbol.vb b/src/roslyn/src/Compilers/VisualBasic/Portable/Symbols/ErrorMethodSymbol.vb index 59659fd3c12..44aafa2bfea 100644 --- a/src/roslyn/src/Compilers/VisualBasic/Portable/Symbols/ErrorMethodSymbol.vb +++ b/src/roslyn/src/Compilers/VisualBasic/Portable/Symbols/ErrorMethodSymbol.vb @@ -3,6 +3,7 @@ ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable +Imports Microsoft.CodeAnalysis.Collections Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols diff --git a/src/roslyn/src/Compilers/VisualBasic/Portable/Symbols/ErrorTypeSymbol.vb b/src/roslyn/src/Compilers/VisualBasic/Portable/Symbols/ErrorTypeSymbol.vb index ba1990b0706..4d0cf74614d 100644 --- a/src/roslyn/src/Compilers/VisualBasic/Portable/Symbols/ErrorTypeSymbol.vb +++ b/src/roslyn/src/Compilers/VisualBasic/Portable/Symbols/ErrorTypeSymbol.vb @@ -7,6 +7,7 @@ Imports System.Collections.Immutable Imports System.Runtime.InteropServices Imports System.Text Imports System.Threading +Imports Microsoft.CodeAnalysis.Collections Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax diff --git a/src/roslyn/src/Compilers/VisualBasic/Portable/Symbols/Metadata/PE/PEGlobalNamespaceSymbol.vb b/src/roslyn/src/Compilers/VisualBasic/Portable/Symbols/Metadata/PE/PEGlobalNamespaceSymbol.vb index f8d33217132..0b99d1db2e1 100644 --- a/src/roslyn/src/Compilers/VisualBasic/Portable/Symbols/Metadata/PE/PEGlobalNamespaceSymbol.vb +++ b/src/roslyn/src/Compilers/VisualBasic/Portable/Symbols/Metadata/PE/PEGlobalNamespaceSymbol.vb @@ -3,11 +3,12 @@ ' See the LICENSE file in the project root for more information. Imports System.Collections.Generic +Imports System.Reflection.Metadata +Imports System.Threading +Imports Microsoft.CodeAnalysis.Collections Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax -Imports System.Reflection.Metadata -Imports System.Threading Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols.Metadata.PE diff --git a/src/roslyn/src/Compilers/VisualBasic/Portable/Symbols/Metadata/PE/PENamedTypeSymbol.vb b/src/roslyn/src/Compilers/VisualBasic/Portable/Symbols/Metadata/PE/PENamedTypeSymbol.vb index b512b6b7b84..73cd989bea3 100644 --- a/src/roslyn/src/Compilers/VisualBasic/Portable/Symbols/Metadata/PE/PENamedTypeSymbol.vb +++ b/src/roslyn/src/Compilers/VisualBasic/Portable/Symbols/Metadata/PE/PENamedTypeSymbol.vb @@ -8,6 +8,7 @@ Imports System.Reflection.Metadata Imports System.Reflection.Metadata.Ecma335 Imports System.Runtime.InteropServices Imports System.Threading +Imports Microsoft.CodeAnalysis.Collections Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.VisualBasic.Emit Imports Microsoft.CodeAnalysis.VisualBasic.Symbols diff --git a/src/roslyn/src/Compilers/VisualBasic/Portable/Symbols/Metadata/PE/PEPropertyOrEventHelpers.vb b/src/roslyn/src/Compilers/VisualBasic/Portable/Symbols/Metadata/PE/PEPropertyOrEventHelpers.vb index 35ec25d6b2d..2c87b4a7465 100644 --- a/src/roslyn/src/Compilers/VisualBasic/Portable/Symbols/Metadata/PE/PEPropertyOrEventHelpers.vb +++ b/src/roslyn/src/Compilers/VisualBasic/Portable/Symbols/Metadata/PE/PEPropertyOrEventHelpers.vb @@ -4,6 +4,7 @@ Imports System.Collections.Generic Imports System.Collections.Immutable +Imports Microsoft.CodeAnalysis.Collections Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax diff --git a/src/roslyn/src/Compilers/VisualBasic/Portable/Symbols/MissingAssemblySymbol.vb b/src/roslyn/src/Compilers/VisualBasic/Portable/Symbols/MissingAssemblySymbol.vb index 9bba967f9e7..045aefd0317 100644 --- a/src/roslyn/src/Compilers/VisualBasic/Portable/Symbols/MissingAssemblySymbol.vb +++ b/src/roslyn/src/Compilers/VisualBasic/Portable/Symbols/MissingAssemblySymbol.vb @@ -7,6 +7,7 @@ Imports System.Collections.Immutable Imports System.Collections.ObjectModel Imports System.Reflection Imports System.Threading +Imports Microsoft.CodeAnalysis.Collections Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax diff --git a/src/roslyn/src/Compilers/VisualBasic/Portable/Symbols/MissingModuleSymbol.vb b/src/roslyn/src/Compilers/VisualBasic/Portable/Symbols/MissingModuleSymbol.vb index 1d88e088a13..0259290cc1b 100644 --- a/src/roslyn/src/Compilers/VisualBasic/Portable/Symbols/MissingModuleSymbol.vb +++ b/src/roslyn/src/Compilers/VisualBasic/Portable/Symbols/MissingModuleSymbol.vb @@ -7,6 +7,7 @@ Imports System.Collections.Immutable Imports System.Reflection Imports System.Runtime.InteropServices Imports System.Threading +Imports Microsoft.CodeAnalysis.Collections Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax diff --git a/src/roslyn/src/Compilers/VisualBasic/Portable/Symbols/Source/ImplicitNamedTypeSymbol.vb b/src/roslyn/src/Compilers/VisualBasic/Portable/Symbols/Source/ImplicitNamedTypeSymbol.vb index b2b9c54651a..2000f2a6feb 100644 --- a/src/roslyn/src/Compilers/VisualBasic/Portable/Symbols/Source/ImplicitNamedTypeSymbol.vb +++ b/src/roslyn/src/Compilers/VisualBasic/Portable/Symbols/Source/ImplicitNamedTypeSymbol.vb @@ -10,6 +10,7 @@ Imports System.Linq Imports System.Runtime.InteropServices Imports System.Text Imports System.Threading.Tasks +Imports Microsoft.CodeAnalysis.Collections Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols diff --git a/src/roslyn/src/Compilers/VisualBasic/Portable/Symbols/Source/SourceAssemblySymbol.vb b/src/roslyn/src/Compilers/VisualBasic/Portable/Symbols/Source/SourceAssemblySymbol.vb index 998d7e2c78e..b325f2d3eb2 100644 --- a/src/roslyn/src/Compilers/VisualBasic/Portable/Symbols/Source/SourceAssemblySymbol.vb +++ b/src/roslyn/src/Compilers/VisualBasic/Portable/Symbols/Source/SourceAssemblySymbol.vb @@ -7,6 +7,7 @@ Imports System.Collections.Immutable Imports System.Reflection Imports System.Runtime.InteropServices Imports System.Threading +Imports Microsoft.CodeAnalysis.Collections Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Emit diff --git a/src/roslyn/src/Compilers/VisualBasic/Portable/Symbols/Source/SourceMethodSymbol.vb b/src/roslyn/src/Compilers/VisualBasic/Portable/Symbols/Source/SourceMethodSymbol.vb index a8ab13a0b95..c32efb5fe70 100644 --- a/src/roslyn/src/Compilers/VisualBasic/Portable/Symbols/Source/SourceMethodSymbol.vb +++ b/src/roslyn/src/Compilers/VisualBasic/Portable/Symbols/Source/SourceMethodSymbol.vb @@ -8,6 +8,7 @@ Imports System.Reflection Imports System.Runtime.InteropServices Imports System.Threading Imports Microsoft.Cci +Imports Microsoft.CodeAnalysis.Collections Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Emit diff --git a/src/roslyn/src/Compilers/VisualBasic/Portable/Symbols/Source/SourceNamedTypeSymbol.vb b/src/roslyn/src/Compilers/VisualBasic/Portable/Symbols/Source/SourceNamedTypeSymbol.vb index 17bf9ed29de..44be9f063a2 100644 --- a/src/roslyn/src/Compilers/VisualBasic/Portable/Symbols/Source/SourceNamedTypeSymbol.vb +++ b/src/roslyn/src/Compilers/VisualBasic/Portable/Symbols/Source/SourceNamedTypeSymbol.vb @@ -8,6 +8,7 @@ Imports System.Collections.Immutable Imports System.Globalization Imports System.Runtime.InteropServices Imports System.Threading +Imports Microsoft.CodeAnalysis.Collections Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.Symbols Imports Microsoft.CodeAnalysis.Text diff --git a/src/roslyn/src/Compilers/VisualBasic/Portable/Symbols/Source/SourceNamedTypeSymbol_ComClass.vb b/src/roslyn/src/Compilers/VisualBasic/Portable/Symbols/Source/SourceNamedTypeSymbol_ComClass.vb index eef1641c6bc..c3343d68e89 100644 --- a/src/roslyn/src/Compilers/VisualBasic/Portable/Symbols/Source/SourceNamedTypeSymbol_ComClass.vb +++ b/src/roslyn/src/Compilers/VisualBasic/Portable/Symbols/Source/SourceNamedTypeSymbol_ComClass.vb @@ -5,6 +5,7 @@ Imports System.Collections.Immutable Imports System.Runtime.InteropServices Imports System.Threading +Imports Microsoft.CodeAnalysis.Collections Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.VisualBasic.Emit Imports Microsoft.CodeAnalysis.VisualBasic.Symbols diff --git a/src/roslyn/src/Compilers/VisualBasic/Portable/Symbols/SynthesizedSymbols/SynthesizedEventDelegateSymbol.vb b/src/roslyn/src/Compilers/VisualBasic/Portable/Symbols/SynthesizedSymbols/SynthesizedEventDelegateSymbol.vb index d41acd9678e..9b05bcd9278 100644 --- a/src/roslyn/src/Compilers/VisualBasic/Portable/Symbols/SynthesizedSymbols/SynthesizedEventDelegateSymbol.vb +++ b/src/roslyn/src/Compilers/VisualBasic/Portable/Symbols/SynthesizedSymbols/SynthesizedEventDelegateSymbol.vb @@ -5,6 +5,7 @@ Imports System.Collections.Immutable Imports System.Runtime.InteropServices Imports System.Threading +Imports Microsoft.CodeAnalysis.Collections Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax diff --git a/src/roslyn/src/Compilers/VisualBasic/Portable/Symbols/SynthesizedSymbols/SynthesizedHotReloadExceptionSymbol.vb b/src/roslyn/src/Compilers/VisualBasic/Portable/Symbols/SynthesizedSymbols/SynthesizedHotReloadExceptionSymbol.vb index 77abc86606a..9ae958d45fa 100644 --- a/src/roslyn/src/Compilers/VisualBasic/Portable/Symbols/SynthesizedSymbols/SynthesizedHotReloadExceptionSymbol.vb +++ b/src/roslyn/src/Compilers/VisualBasic/Portable/Symbols/SynthesizedSymbols/SynthesizedHotReloadExceptionSymbol.vb @@ -5,6 +5,7 @@ Imports System.Collections.Immutable Imports System.Runtime.InteropServices Imports System.Threading +Imports Microsoft.CodeAnalysis.Collections Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols Friend NotInheritable Class SynthesizedHotReloadExceptionSymbol diff --git a/src/roslyn/src/Compilers/VisualBasic/Portable/Symbols/UnboundGenericType.vb b/src/roslyn/src/Compilers/VisualBasic/Portable/Symbols/UnboundGenericType.vb index 935fa628125..b96aa114b04 100644 --- a/src/roslyn/src/Compilers/VisualBasic/Portable/Symbols/UnboundGenericType.vb +++ b/src/roslyn/src/Compilers/VisualBasic/Portable/Symbols/UnboundGenericType.vb @@ -9,6 +9,7 @@ Imports System.Globalization Imports System.Runtime.InteropServices Imports System.Text Imports System.Threading +Imports Microsoft.CodeAnalysis.Collections Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols diff --git a/src/roslyn/src/Compilers/VisualBasic/Portable/Syntax/LambdaUtilities.vb b/src/roslyn/src/Compilers/VisualBasic/Portable/Syntax/LambdaUtilities.vb index 5192f11b968..aa6779dc959 100644 --- a/src/roslyn/src/Compilers/VisualBasic/Portable/Syntax/LambdaUtilities.vb +++ b/src/roslyn/src/Compilers/VisualBasic/Portable/Syntax/LambdaUtilities.vb @@ -2,9 +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. +Imports System.Runtime.InteropServices +Imports Microsoft.CodeAnalysis.Collections Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.VisualBasic.Syntax -Imports System.Runtime.InteropServices Namespace Microsoft.CodeAnalysis.VisualBasic diff --git a/src/roslyn/src/Compilers/VisualBasic/Portable/Syntax/VisualBasicSyntaxTree.vb b/src/roslyn/src/Compilers/VisualBasic/Portable/Syntax/VisualBasicSyntaxTree.vb index 890ed900865..04ed895f802 100644 --- a/src/roslyn/src/Compilers/VisualBasic/Portable/Syntax/VisualBasicSyntaxTree.vb +++ b/src/roslyn/src/Compilers/VisualBasic/Portable/Syntax/VisualBasicSyntaxTree.vb @@ -6,6 +6,7 @@ Imports System.Collections.Immutable Imports System.ComponentModel Imports System.Text Imports System.Threading +Imports Microsoft.CodeAnalysis.Collections Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax diff --git a/src/roslyn/src/Compilers/VisualBasic/Test/Emit/Emit/CompilationEmitTests.vb b/src/roslyn/src/Compilers/VisualBasic/Test/Emit/Emit/CompilationEmitTests.vb index 49cae4245ee..448277251c7 100644 --- a/src/roslyn/src/Compilers/VisualBasic/Test/Emit/Emit/CompilationEmitTests.vb +++ b/src/roslyn/src/Compilers/VisualBasic/Test/Emit/Emit/CompilationEmitTests.vb @@ -8,7 +8,9 @@ Imports System.Reflection Imports System.Reflection.Metadata Imports System.Reflection.PortableExecutable Imports System.Text +Imports Basic.Reference.Assemblies Imports Microsoft.CodeAnalysis.CodeGen +Imports Microsoft.CodeAnalysis.Collections Imports Microsoft.CodeAnalysis.Emit Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.CodeAnalysis.VisualBasic @@ -16,7 +18,6 @@ Imports Microsoft.CodeAnalysis.VisualBasic.Emit Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Symbols.Metadata.PE Imports Roslyn.Test.Utilities -Imports Basic.Reference.Assemblies Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Emit Public Class CompilationEmitTests diff --git a/src/roslyn/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/Source/PropertyTests.vb b/src/roslyn/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/Source/PropertyTests.vb index fe4ef71fdc1..f943a8f59ba 100644 --- a/src/roslyn/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/Source/PropertyTests.vb +++ b/src/roslyn/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/Source/PropertyTests.vb @@ -3,14 +3,15 @@ ' See the LICENSE file in the project root for more information. Imports System.Xml.Linq +Imports Microsoft.CodeAnalysis.Collections Imports Microsoft.CodeAnalysis.Emit Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.CodeAnalysis.VisualBasic.Emit -Imports Microsoft.CodeAnalysis.VisualBasic.Symbols.Metadata.PE Imports Microsoft.CodeAnalysis.VisualBasic.Symbols +Imports Microsoft.CodeAnalysis.VisualBasic.Symbols.Metadata.PE +Imports Microsoft.CodeAnalysis.VisualBasic.Symbols.Retargeting Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Roslyn.Test.Utilities -Imports Microsoft.CodeAnalysis.VisualBasic.Symbols.Retargeting Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests diff --git a/src/roslyn/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/SymbolErrorTests.vb b/src/roslyn/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/SymbolErrorTests.vb index e32077a0bb2..e90975efa3d 100644 --- a/src/roslyn/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/SymbolErrorTests.vb +++ b/src/roslyn/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/SymbolErrorTests.vb @@ -5,6 +5,7 @@ Imports System.Collections.Immutable Imports System.Xml.Linq Imports Basic.Reference.Assemblies +Imports Microsoft.CodeAnalysis.Collections Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.CodeAnalysis.VisualBasic Imports Microsoft.CodeAnalysis.VisualBasic.Symbols diff --git a/src/roslyn/src/Dependencies/Collections/Extensions/IEnumerableExtensions.cs b/src/roslyn/src/Dependencies/Collections/Extensions/IEnumerableExtensions.cs index d06a1733a9f..0e86991e66d 100644 --- a/src/roslyn/src/Dependencies/Collections/Extensions/IEnumerableExtensions.cs +++ b/src/roslyn/src/Dependencies/Collections/Extensions/IEnumerableExtensions.cs @@ -15,6 +15,7 @@ using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.PooledObjects; namespace Roslyn.Utilities diff --git a/src/roslyn/src/Dependencies/Collections/Specialized/SpecializedCollections.Empty.Collection.cs b/src/roslyn/src/Dependencies/Collections/Specialized/SpecializedCollections.Empty.Collection.cs index e135dcb8902..4885f9d0d14 100644 --- a/src/roslyn/src/Dependencies/Collections/Specialized/SpecializedCollections.Empty.Collection.cs +++ b/src/roslyn/src/Dependencies/Collections/Specialized/SpecializedCollections.Empty.Collection.cs @@ -7,7 +7,7 @@ using System; using System.Collections.Generic; -namespace Roslyn.Utilities +namespace Microsoft.CodeAnalysis.Collections { internal static partial class SpecializedCollections { diff --git a/src/roslyn/src/Dependencies/Collections/Specialized/SpecializedCollections.Empty.Dictionary.cs b/src/roslyn/src/Dependencies/Collections/Specialized/SpecializedCollections.Empty.Dictionary.cs index 7035b5e0c07..98164c6c405 100644 --- a/src/roslyn/src/Dependencies/Collections/Specialized/SpecializedCollections.Empty.Dictionary.cs +++ b/src/roslyn/src/Dependencies/Collections/Specialized/SpecializedCollections.Empty.Dictionary.cs @@ -8,7 +8,7 @@ using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; -namespace Roslyn.Utilities +namespace Microsoft.CodeAnalysis.Collections { internal partial class SpecializedCollections { diff --git a/src/roslyn/src/Dependencies/Collections/Specialized/SpecializedCollections.Empty.Enumerable.cs b/src/roslyn/src/Dependencies/Collections/Specialized/SpecializedCollections.Empty.Enumerable.cs index c0f577c7a74..9db162535cd 100644 --- a/src/roslyn/src/Dependencies/Collections/Specialized/SpecializedCollections.Empty.Enumerable.cs +++ b/src/roslyn/src/Dependencies/Collections/Specialized/SpecializedCollections.Empty.Enumerable.cs @@ -6,7 +6,7 @@ using System.Collections.Generic; -namespace Roslyn.Utilities +namespace Microsoft.CodeAnalysis.Collections { internal partial class SpecializedCollections { diff --git a/src/roslyn/src/Dependencies/Collections/Specialized/SpecializedCollections.Empty.Enumerator.cs b/src/roslyn/src/Dependencies/Collections/Specialized/SpecializedCollections.Empty.Enumerator.cs index fd3a41eb700..dfb79c7028b 100644 --- a/src/roslyn/src/Dependencies/Collections/Specialized/SpecializedCollections.Empty.Enumerator.cs +++ b/src/roslyn/src/Dependencies/Collections/Specialized/SpecializedCollections.Empty.Enumerator.cs @@ -7,7 +7,7 @@ using System; using System.Collections; -namespace Roslyn.Utilities +namespace Microsoft.CodeAnalysis.Collections { internal partial class SpecializedCollections { diff --git a/src/roslyn/src/Dependencies/Collections/Specialized/SpecializedCollections.Empty.Enumerator`1.cs b/src/roslyn/src/Dependencies/Collections/Specialized/SpecializedCollections.Empty.Enumerator`1.cs index 70c67464389..3e253bae606 100644 --- a/src/roslyn/src/Dependencies/Collections/Specialized/SpecializedCollections.Empty.Enumerator`1.cs +++ b/src/roslyn/src/Dependencies/Collections/Specialized/SpecializedCollections.Empty.Enumerator`1.cs @@ -7,7 +7,7 @@ using System; using System.Collections.Generic; -namespace Roslyn.Utilities +namespace Microsoft.CodeAnalysis.Collections { internal partial class SpecializedCollections { diff --git a/src/roslyn/src/Dependencies/Collections/Specialized/SpecializedCollections.Empty.List.cs b/src/roslyn/src/Dependencies/Collections/Specialized/SpecializedCollections.Empty.List.cs index 2e367fd0240..57e4cdd8d8e 100644 --- a/src/roslyn/src/Dependencies/Collections/Specialized/SpecializedCollections.Empty.List.cs +++ b/src/roslyn/src/Dependencies/Collections/Specialized/SpecializedCollections.Empty.List.cs @@ -8,7 +8,7 @@ using System.Collections.Generic; using System.Collections.Immutable; -namespace Roslyn.Utilities +namespace Microsoft.CodeAnalysis.Collections { internal partial class SpecializedCollections { diff --git a/src/roslyn/src/Dependencies/Collections/Specialized/SpecializedCollections.Empty.Set.cs b/src/roslyn/src/Dependencies/Collections/Specialized/SpecializedCollections.Empty.Set.cs index 13c41a758fa..be9f0dd34d9 100644 --- a/src/roslyn/src/Dependencies/Collections/Specialized/SpecializedCollections.Empty.Set.cs +++ b/src/roslyn/src/Dependencies/Collections/Specialized/SpecializedCollections.Empty.Set.cs @@ -5,9 +5,10 @@ #nullable enable using System; +using System.Linq; using System.Collections.Generic; -namespace Roslyn.Utilities +namespace Microsoft.CodeAnalysis.Collections { internal partial class SpecializedCollections { @@ -38,7 +39,7 @@ public void IntersectWith(IEnumerable other) public bool IsProperSubsetOf(IEnumerable other) { - return !other.IsEmpty(); + return other.Any(); } public bool IsProperSupersetOf(IEnumerable other) @@ -53,7 +54,7 @@ public bool IsSubsetOf(IEnumerable other) public bool IsSupersetOf(IEnumerable other) { - return other.IsEmpty(); + return !other.Any(); } public bool Overlaps(IEnumerable other) @@ -63,7 +64,7 @@ public bool Overlaps(IEnumerable other) public bool SetEquals(IEnumerable other) { - return other.IsEmpty(); + return !other.Any(); } public void SymmetricExceptWith(IEnumerable other) diff --git a/src/roslyn/src/Dependencies/Collections/Specialized/SpecializedCollections.Empty.cs b/src/roslyn/src/Dependencies/Collections/Specialized/SpecializedCollections.Empty.cs index 34ef01c22cd..84fcd89e5f2 100644 --- a/src/roslyn/src/Dependencies/Collections/Specialized/SpecializedCollections.Empty.cs +++ b/src/roslyn/src/Dependencies/Collections/Specialized/SpecializedCollections.Empty.cs @@ -4,7 +4,7 @@ #nullable enable -namespace Roslyn.Utilities +namespace Microsoft.CodeAnalysis.Collections { internal partial class SpecializedCollections { diff --git a/src/roslyn/src/Dependencies/Collections/Specialized/SpecializedCollections.ReadOnly.Collection.cs b/src/roslyn/src/Dependencies/Collections/Specialized/SpecializedCollections.ReadOnly.Collection.cs index 70c086c8cdd..f9a15d99ab9 100644 --- a/src/roslyn/src/Dependencies/Collections/Specialized/SpecializedCollections.ReadOnly.Collection.cs +++ b/src/roslyn/src/Dependencies/Collections/Specialized/SpecializedCollections.ReadOnly.Collection.cs @@ -7,7 +7,7 @@ using System; using System.Collections.Generic; -namespace Roslyn.Utilities +namespace Microsoft.CodeAnalysis.Collections { internal partial class SpecializedCollections { diff --git a/src/roslyn/src/Dependencies/Collections/Specialized/SpecializedCollections.ReadOnly.Enumerable`1.cs b/src/roslyn/src/Dependencies/Collections/Specialized/SpecializedCollections.ReadOnly.Enumerable`1.cs index 4b0c086b6cc..54741cb4ed6 100644 --- a/src/roslyn/src/Dependencies/Collections/Specialized/SpecializedCollections.ReadOnly.Enumerable`1.cs +++ b/src/roslyn/src/Dependencies/Collections/Specialized/SpecializedCollections.ReadOnly.Enumerable`1.cs @@ -6,7 +6,7 @@ using System.Collections; -namespace Roslyn.Utilities +namespace Microsoft.CodeAnalysis.Collections { internal partial class SpecializedCollections { diff --git a/src/roslyn/src/Dependencies/Collections/Specialized/SpecializedCollections.ReadOnly.Enumerable`2.cs b/src/roslyn/src/Dependencies/Collections/Specialized/SpecializedCollections.ReadOnly.Enumerable`2.cs index 5b88cbc975f..de762618c35 100644 --- a/src/roslyn/src/Dependencies/Collections/Specialized/SpecializedCollections.ReadOnly.Enumerable`2.cs +++ b/src/roslyn/src/Dependencies/Collections/Specialized/SpecializedCollections.ReadOnly.Enumerable`2.cs @@ -6,7 +6,7 @@ using System.Collections.Generic; -namespace Roslyn.Utilities +namespace Microsoft.CodeAnalysis.Collections { internal partial class SpecializedCollections { diff --git a/src/roslyn/src/Dependencies/Collections/Specialized/SpecializedCollections.ReadOnly.Set.cs b/src/roslyn/src/Dependencies/Collections/Specialized/SpecializedCollections.ReadOnly.Set.cs index 9a5781bd211..1a52178fc55 100644 --- a/src/roslyn/src/Dependencies/Collections/Specialized/SpecializedCollections.ReadOnly.Set.cs +++ b/src/roslyn/src/Dependencies/Collections/Specialized/SpecializedCollections.ReadOnly.Set.cs @@ -7,7 +7,7 @@ using System; using System.Collections.Generic; -namespace Roslyn.Utilities +namespace Microsoft.CodeAnalysis.Collections { internal partial class SpecializedCollections { diff --git a/src/roslyn/src/Dependencies/Collections/Specialized/SpecializedCollections.Singleton.Collection`1.cs b/src/roslyn/src/Dependencies/Collections/Specialized/SpecializedCollections.Singleton.Collection`1.cs index 0b1d4b5de5f..17e8e2709f2 100644 --- a/src/roslyn/src/Dependencies/Collections/Specialized/SpecializedCollections.Singleton.Collection`1.cs +++ b/src/roslyn/src/Dependencies/Collections/Specialized/SpecializedCollections.Singleton.Collection`1.cs @@ -8,7 +8,7 @@ using System.Collections; using System.Collections.Generic; -namespace Roslyn.Utilities +namespace Microsoft.CodeAnalysis.Collections { internal static partial class SpecializedCollections { diff --git a/src/roslyn/src/Dependencies/Collections/Specialized/SpecializedCollections.Singleton.Enumerator`1.cs b/src/roslyn/src/Dependencies/Collections/Specialized/SpecializedCollections.Singleton.Enumerator`1.cs index 160e9f272e6..d061ebd4039 100644 --- a/src/roslyn/src/Dependencies/Collections/Specialized/SpecializedCollections.Singleton.Enumerator`1.cs +++ b/src/roslyn/src/Dependencies/Collections/Specialized/SpecializedCollections.Singleton.Enumerator`1.cs @@ -7,7 +7,7 @@ using System.Collections; using System.Collections.Generic; -namespace Roslyn.Utilities +namespace Microsoft.CodeAnalysis.Collections { internal static partial class SpecializedCollections { diff --git a/src/roslyn/src/Dependencies/Collections/Specialized/SpecializedCollections.cs b/src/roslyn/src/Dependencies/Collections/Specialized/SpecializedCollections.cs index ac84a167127..a37cac03076 100644 --- a/src/roslyn/src/Dependencies/Collections/Specialized/SpecializedCollections.cs +++ b/src/roslyn/src/Dependencies/Collections/Specialized/SpecializedCollections.cs @@ -6,7 +6,7 @@ using System.Collections.Generic; -namespace Roslyn.Utilities +namespace Microsoft.CodeAnalysis.Collections { internal static partial class SpecializedCollections { diff --git a/src/roslyn/src/EditorFeatures/CSharpTest/ChangeSignature/AddParameterTests.Formatting.cs b/src/roslyn/src/EditorFeatures/CSharpTest/ChangeSignature/AddParameterTests.Formatting.cs index 7dfdd9d6773..7cbe3440a55 100644 --- a/src/roslyn/src/EditorFeatures/CSharpTest/ChangeSignature/AddParameterTests.Formatting.cs +++ b/src/roslyn/src/EditorFeatures/CSharpTest/ChangeSignature/AddParameterTests.Formatting.cs @@ -516,7 +516,7 @@ public async Task AddParameter_Formatting_PreserveIndentBraces_Editorconfig() var markup = @" - + public class C { public void M$$() @@ -524,7 +524,7 @@ public class C } } - [*.cs] + [*.cs] csharp_indent_braces = true diff --git a/src/roslyn/src/EditorFeatures/CSharpTest/ExtractInterface/ExtractInterfaceTests.cs b/src/roslyn/src/EditorFeatures/CSharpTest/ExtractInterface/ExtractInterfaceTests.cs index 13eb5390aa1..64ccb42a46c 100644 --- a/src/roslyn/src/EditorFeatures/CSharpTest/ExtractInterface/ExtractInterfaceTests.cs +++ b/src/roslyn/src/EditorFeatures/CSharpTest/ExtractInterface/ExtractInterfaceTests.cs @@ -2007,7 +2007,7 @@ public async Task RemoveEnumeratorCancellationAttribute() var markup = """ - i.Category.Single().Text == label); Assert.Equal(value, descriptionItem.Details.Single().Text); } - assertDescription("File:", w.Documents.Single().Name); + assertDescription("File:", w.Documents.Single().FilePath); assertDescription("Line:", "3"); // one based line number assertDescription("Project:", "Test"); }); diff --git a/src/roslyn/src/EditorFeatures/CSharpTest/Rename/CSharpInlineRenameServiceTests.cs b/src/roslyn/src/EditorFeatures/CSharpTest/Rename/CSharpInlineRenameServiceTests.cs index 56e7cb6f596..23b76cd2288 100644 --- a/src/roslyn/src/EditorFeatures/CSharpTest/Rename/CSharpInlineRenameServiceTests.cs +++ b/src/roslyn/src/EditorFeatures/CSharpTest/Rename/CSharpInlineRenameServiceTests.cs @@ -5,6 +5,7 @@ using System; using System.Collections.Generic; using System.Collections.Immutable; +using System.IO; using System.Linq; using System.Text.Json; using System.Threading; @@ -77,16 +78,21 @@ private static async Task VerifyGetRenameContextAsync( [WorkItem("https://github.com/dotnet/roslyn/issues/74545")] public async Task VerifyContextReachEndOfFile() { - var markup = @" -public class Sampl$$eClass() -{ -}"; + var markup = """ + public class Sampl$$eClass() + { + } + """; + + var escapedPath = Path.Combine(TestWorkspace.RootDirectory, "test1.cs").Replace("\\", "\\\\"); + await VerifyGetRenameContextAsync( markup, - @" -{ - ""definition"" : [ {""Item1"":""test1.cs"", ""Item2"":""public class SampleClass()\r\n{\r\n}""} ] -}", + $$""" + { + "definition": [{"Item1":"{{escapedPath}}", "Item2":"public class SampleClass()\r\n{\r\n}"}] + } + """, new SymbolRenameOptions(), CancellationToken.None); } diff --git a/src/roslyn/src/EditorFeatures/Core/Options/EditorAnalyzerConfigOptions.cs b/src/roslyn/src/EditorFeatures/Core/Options/EditorAnalyzerConfigOptions.cs index 49a55053e70..399e56ba751 100644 --- a/src/roslyn/src/EditorFeatures/Core/Options/EditorAnalyzerConfigOptions.cs +++ b/src/roslyn/src/EditorFeatures/Core/Options/EditorAnalyzerConfigOptions.cs @@ -5,6 +5,7 @@ using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; +using Microsoft.CodeAnalysis.Collections; using Microsoft.VisualStudio.Text.Editor; using Roslyn.Utilities; diff --git a/src/roslyn/src/EditorFeatures/Core/Preview/SolutionPreviewResult.cs b/src/roslyn/src/EditorFeatures/Core/Preview/SolutionPreviewResult.cs index 40a4354e46d..a734f66656d 100644 --- a/src/roslyn/src/EditorFeatures/Core/Preview/SolutionPreviewResult.cs +++ b/src/roslyn/src/EditorFeatures/Core/Preview/SolutionPreviewResult.cs @@ -7,6 +7,7 @@ using System.Linq; using System.Threading; using System.Threading.Tasks; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Roslyn.Utilities; diff --git a/src/roslyn/src/EditorFeatures/Core/Suggestions/RefineUsingCopilot/RefineUsingCopilotCodeAction.cs b/src/roslyn/src/EditorFeatures/Core/Suggestions/RefineUsingCopilot/RefineUsingCopilotCodeAction.cs index 36c4e5242f3..7dc2781361a 100644 --- a/src/roslyn/src/EditorFeatures/Core/Suggestions/RefineUsingCopilot/RefineUsingCopilotCodeAction.cs +++ b/src/roslyn/src/EditorFeatures/Core/Suggestions/RefineUsingCopilot/RefineUsingCopilotCodeAction.cs @@ -9,6 +9,7 @@ using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.Copilot; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Shared.Extensions; diff --git a/src/roslyn/src/EditorFeatures/Core/WpfClassificationExtensions.cs b/src/roslyn/src/EditorFeatures/Core/WpfClassificationExtensions.cs index cc2ad402355..0d71aa01edb 100644 --- a/src/roslyn/src/EditorFeatures/Core/WpfClassificationExtensions.cs +++ b/src/roslyn/src/EditorFeatures/Core/WpfClassificationExtensions.cs @@ -11,6 +11,7 @@ using System.Windows.Controls; using System.Windows.Documents; using Microsoft.CodeAnalysis.Classification; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.VisualStudio.Text.Classification; using Roslyn.Utilities; diff --git a/src/roslyn/src/EditorFeatures/DiagnosticsTestUtilities/CodeActions/AbstractCodeActionOrUserDiagnosticTest_TestAddDocument.cs b/src/roslyn/src/EditorFeatures/DiagnosticsTestUtilities/CodeActions/AbstractCodeActionOrUserDiagnosticTest_TestAddDocument.cs index 80348a22e8d..e2c6489f88b 100644 --- a/src/roslyn/src/EditorFeatures/DiagnosticsTestUtilities/CodeActions/AbstractCodeActionOrUserDiagnosticTest_TestAddDocument.cs +++ b/src/roslyn/src/EditorFeatures/DiagnosticsTestUtilities/CodeActions/AbstractCodeActionOrUserDiagnosticTest_TestAddDocument.cs @@ -43,7 +43,7 @@ await TestAddDocument( } } - protected async Task> TestAddDocumentAsync( + protected async Task<(Solution oldSolution, Solution newSolution)> TestAddDocumentAsync( TestParameters parameters, EditorTestWorkspace workspace, string expectedMarkup, @@ -71,7 +71,7 @@ await TestAddDocument( expectedDocumentName, action); } - private async Task> TestAddDocument( + private async Task<(Solution oldSolution, Solution newSolution)> TestAddDocument( EditorTestWorkspace workspace, string expectedMarkup, ImmutableArray expectedFolders, @@ -89,7 +89,7 @@ private async Task> TestAddDocument( expectedDocumentName: expectedDocumentName); } - protected static async Task> TestAddDocument( + protected static async Task<(Solution oldSolution, Solution newSolution)> TestAddDocument( EditorTestWorkspace workspace, string expected, ImmutableArray operations, @@ -98,9 +98,7 @@ protected static async Task> TestAddDocument( ImmutableArray expectedFolders, string expectedDocumentName) { - var appliedChanges = await ApplyOperationsAndGetSolutionAsync(workspace, operations); - var oldSolution = appliedChanges.Item1; - var newSolution = appliedChanges.Item2; + var (oldSolution, newSolution) = await ApplyOperationsAndGetSolutionAsync(workspace, operations); Document addedDocument = null; if (!hasProjectChange) @@ -155,6 +153,6 @@ protected static async Task> TestAddDocument( Assert.True(hasPreview); } - return Tuple.Create(oldSolution, newSolution); + return (oldSolution, newSolution); } } diff --git a/src/roslyn/src/EditorFeatures/DiagnosticsTestUtilities/Diagnostics/AbstractUserDiagnosticTest_GenerateTypeDialog.cs b/src/roslyn/src/EditorFeatures/DiagnosticsTestUtilities/Diagnostics/AbstractUserDiagnosticTest_GenerateTypeDialog.cs index 09ab9950482..4233fdfac33 100644 --- a/src/roslyn/src/EditorFeatures/DiagnosticsTestUtilities/Diagnostics/AbstractUserDiagnosticTest_GenerateTypeDialog.cs +++ b/src/roslyn/src/EditorFeatures/DiagnosticsTestUtilities/Diagnostics/AbstractUserDiagnosticTest_GenerateTypeDialog.cs @@ -99,11 +99,11 @@ internal async Task TestWithMockedGenerateTypeDialog( Assert.Equal(action.Title, FeaturesResources.Generate_new_type); var operations = await action.GetOperationsAsync( workspace.CurrentSolution, CodeAnalysisProgress.None, CancellationToken.None); - Tuple oldSolutionAndNewSolution = null; + Solution oldSolution, newSolution; if (!isNewFile) { - oldSolutionAndNewSolution = await TestOperationsAsync( + (oldSolution, newSolution) = await TestOperationsAsync( testState.Workspace, expected, operations, conflictSpans: [], renameSpans: [], @@ -113,11 +113,11 @@ internal async Task TestWithMockedGenerateTypeDialog( } else { - oldSolutionAndNewSolution = await TestAddDocument( + (oldSolution, newSolution) = await TestAddDocument( testState.Workspace, expected, operations, - projectName != null, + hasProjectChange: projectName != null, testState.ProjectToBeModified.Id, newFileFolderContainers, newFileName); @@ -136,8 +136,6 @@ await TestOperationsAsync(testState.Workspace, expectedTextWithUsings, operation if (checkIfUsingsNotIncluded) { - var oldSolution = oldSolutionAndNewSolution.Item1; - var newSolution = oldSolutionAndNewSolution.Item2; var changedDocumentIds = SolutionUtilities.GetChangedDocuments(oldSolution, newSolution); Assert.False(changedDocumentIds.Contains(testState.InvocationDocument.Id)); @@ -147,7 +145,6 @@ await TestOperationsAsync(testState.Workspace, expectedTextWithUsings, operation if (projectName != null) { var appliedChanges = await ApplyOperationsAndGetSolutionAsync(testState.Workspace, operations); - var newSolution = appliedChanges.Item2; var triggeredProject = newSolution.GetProject(testState.TriggeredProject.Id); // Make sure the Project reference is present diff --git a/src/roslyn/src/EditorFeatures/DiagnosticsTestUtilities/MoveType/AbstractMoveTypeTest.cs b/src/roslyn/src/EditorFeatures/DiagnosticsTestUtilities/MoveType/AbstractMoveTypeTest.cs index 4ef6536f45d..2a338dbee38 100644 --- a/src/roslyn/src/EditorFeatures/DiagnosticsTestUtilities/MoveType/AbstractMoveTypeTest.cs +++ b/src/roslyn/src/EditorFeatures/DiagnosticsTestUtilities/MoveType/AbstractMoveTypeTest.cs @@ -7,6 +7,7 @@ using System; using System.Collections.Generic; using System.Collections.Immutable; +using System.IO; using System.Linq; using System.Threading; using System.Threading.Tasks; @@ -14,6 +15,7 @@ using Microsoft.CodeAnalysis.CodeRefactorings.MoveType; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions; +using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.UnitTests; using Roslyn.Test.Utilities; @@ -159,19 +161,26 @@ private protected async Task TestMoveTypeToNewFileAsync( var sourceDocumentId = workspace.Documents[0].Id; // Verify the newly added document and its text - var oldSolutionAndNewSolution = await TestAddDocumentAsync( + var (oldSolution, newSolution) = await TestAddDocumentAsync( testOptions, workspace, destinationDocumentText, expectedDocumentName, destinationDocumentContainers); // Verify source document's text after moving type. - var oldSolution = oldSolutionAndNewSolution.Item1; - var newSolution = oldSolutionAndNewSolution.Item2; var changedDocumentIds = SolutionUtilities.GetChangedDocuments(oldSolution, newSolution); Assert.True(changedDocumentIds.Contains(sourceDocumentId), "source document was not changed."); - var modifiedSourceDocument = newSolution.GetDocument(sourceDocumentId); - var actualSourceTextAfterRefactoring = (await modifiedSourceDocument.GetTextAsync()).ToString(); - AssertEx.Equal(expectedSourceTextAfterRefactoring, actualSourceTextAfterRefactoring); + var addedDocument = SolutionUtilities.GetSingleAddedDocument(oldSolution, newSolution); + var addedSourceText = await addedDocument.GetTextAsync(); + var oldSourceDocument = oldSolution.GetRequiredDocument(sourceDocumentId); + var oldSourceText = await oldSourceDocument.GetTextAsync(); + var newSourceDocument = newSolution.GetRequiredDocument(sourceDocumentId); + var newSourceText = await newSourceDocument.GetTextAsync(); + + Assert.Equal(Path.Combine(Path.GetDirectoryName(addedDocument.FilePath), expectedDocumentName), addedDocument.FilePath); + Assert.Equal(oldSourceText.Encoding, addedSourceText.Encoding); + Assert.Equal(oldSourceText.ChecksumAlgorithm, addedSourceText.ChecksumAlgorithm); + + AssertEx.Equal(expectedSourceTextAfterRefactoring, newSourceText.ToString()); } else { diff --git a/src/roslyn/src/EditorFeatures/Test/CodeFixes/CodeFixServiceTests.cs b/src/roslyn/src/EditorFeatures/Test/CodeFixes/CodeFixServiceTests.cs index 2b49246cb1e..505d948836c 100644 --- a/src/roslyn/src/EditorFeatures/Test/CodeFixes/CodeFixServiceTests.cs +++ b/src/roslyn/src/EditorFeatures/Test/CodeFixes/CodeFixServiceTests.cs @@ -11,6 +11,7 @@ using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeFixes; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.Implementation.Suggestions; using Microsoft.CodeAnalysis.ErrorLogger; diff --git a/src/roslyn/src/EditorFeatures/Test/MetadataAsSource/AbstractMetadataAsSourceTests.TestContext.cs b/src/roslyn/src/EditorFeatures/Test/MetadataAsSource/AbstractMetadataAsSourceTests.TestContext.cs index 05627785d17..683080a2a53 100644 --- a/src/roslyn/src/EditorFeatures/Test/MetadataAsSource/AbstractMetadataAsSourceTests.TestContext.cs +++ b/src/roslyn/src/EditorFeatures/Test/MetadataAsSource/AbstractMetadataAsSourceTests.TestContext.cs @@ -311,7 +311,7 @@ internal Document GetDocument(MetadataAsSourceFile file) internal async Task GetNavigationSymbolAsync() { - var testDocument = Workspace.Documents.Single(d => d.FilePath == "SourceDocument"); + var testDocument = Workspace.Documents.Single(d => d.Name == "SourceDocument"); var document = Workspace.CurrentSolution.GetRequiredDocument(testDocument.Id); var syntaxRoot = await document.GetRequiredSyntaxRootAsync(CancellationToken.None); diff --git a/src/roslyn/src/EditorFeatures/Test2/CodeFixes/CodeFixServiceTests.vb b/src/roslyn/src/EditorFeatures/Test2/CodeFixes/CodeFixServiceTests.vb index da7fef606b2..8e079af3012 100644 --- a/src/roslyn/src/EditorFeatures/Test2/CodeFixes/CodeFixServiceTests.vb +++ b/src/roslyn/src/EditorFeatures/Test2/CodeFixes/CodeFixServiceTests.vb @@ -9,6 +9,7 @@ Imports System.Reflection Imports System.Threading Imports Microsoft.CodeAnalysis.CodeActions Imports Microsoft.CodeAnalysis.CodeFixes +Imports Microsoft.CodeAnalysis.Collections Imports Microsoft.CodeAnalysis.Copilot Imports Microsoft.CodeAnalysis.Diagnostics Imports Microsoft.CodeAnalysis.DocumentationComments diff --git a/src/roslyn/src/EditorFeatures/Test2/Diagnostics/DiagnosticProviderTests.vb b/src/roslyn/src/EditorFeatures/Test2/Diagnostics/DiagnosticProviderTests.vb index 10b648744e2..4553ffe542e 100644 --- a/src/roslyn/src/EditorFeatures/Test2/Diagnostics/DiagnosticProviderTests.vb +++ b/src/roslyn/src/EditorFeatures/Test2/Diagnostics/DiagnosticProviderTests.vb @@ -3,6 +3,7 @@ ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable +Imports System.IO Imports System.Threading Imports Microsoft.CodeAnalysis.CSharp Imports Microsoft.CodeAnalysis.Diagnostics @@ -331,7 +332,7 @@ Namespace Microsoft.CodeAnalysis.Editor.Implementation.Diagnostics.UnitTests Private Shared Function GetDocumentId(workspace As EditorTestWorkspace, document As String) As DocumentId Return (From doc In workspace.Documents - Where doc.FilePath.Equals(document) + Where Path.GetFileName(doc.FilePath).Equals(document) Select doc.Id).Single() End Function diff --git a/src/roslyn/src/EditorFeatures/Test2/Diagnostics/DiagnosticServiceTests.vb b/src/roslyn/src/EditorFeatures/Test2/Diagnostics/DiagnosticServiceTests.vb index 416331a7333..7b7e1afe04a 100644 --- a/src/roslyn/src/EditorFeatures/Test2/Diagnostics/DiagnosticServiceTests.vb +++ b/src/roslyn/src/EditorFeatures/Test2/Diagnostics/DiagnosticServiceTests.vb @@ -7,6 +7,7 @@ Imports System.IO Imports System.Reflection Imports System.Threading Imports Microsoft.CodeAnalysis +Imports Microsoft.CodeAnalysis.Collections Imports Microsoft.CodeAnalysis.CommonDiagnosticAnalyzers Imports Microsoft.CodeAnalysis.CSharp Imports Microsoft.CodeAnalysis.Diagnostics @@ -554,11 +555,12 @@ Namespace Microsoft.CodeAnalysis.Editor.Implementation.Diagnostics.UnitTests Using workspace = TestWorkspace.CreateWorkspace(test, composition:=s_compositionWithMockDiagnosticUpdateSourceRegistrationService) Dim solution = workspace.CurrentSolution Dim documentId = solution.Projects.Single().DocumentIds.Single() - solution = solution.WithDocumentTextLoader(documentId, New FailingTextLoader("Test.cs"), PreservationMode.PreserveIdentity) + Dim document = solution.GetDocument(documentId) + solution = solution.WithDocumentTextLoader(documentId, New FailingTextLoader(document.FilePath), PreservationMode.PreserveIdentity) Await workspace.ChangeSolutionAsync(solution) - Dim project = solution.Projects.Single() - Dim document = project.Documents.Single() + document = solution.GetDocument(documentId) + Dim project = document.Project ' analyzer throws an exception Dim analyzer = New CodeBlockStartedAnalyzer(Of Microsoft.CodeAnalysis.CSharp.SyntaxKind) @@ -572,7 +574,7 @@ Namespace Microsoft.CodeAnalysis.Editor.Implementation.Diagnostics.UnitTests Dim diagnostics = Await GetDiagnosticsForSpanAsync(diagnosticService, document, span).ConfigureAwait(False) Assert.Equal(1, diagnostics.Length) Assert.True(diagnostics(0).Id = "IDE1100") - Assert.Equal(String.Format(WorkspacesResources.Error_reading_content_of_source_file_0_1, "Test.cs", "Bad data!"), diagnostics(0).Message) + Assert.Equal(String.Format(WorkspacesResources.Error_reading_content_of_source_file_0_1, document.FilePath, "Bad data!"), diagnostics(0).Message) End Using End Function @@ -894,11 +896,13 @@ class AnonymousFunctions Using workspace = TestWorkspace.CreateWorkspace(test, composition:=s_compositionWithMockDiagnosticUpdateSourceRegistrationService) Dim solution = workspace.CurrentSolution Dim documentId = solution.Projects.Single().DocumentIds.Single() - solution = solution.WithDocumentTextLoader(documentId, New FailingTextLoader("Test.cs"), PreservationMode.PreserveIdentity) + Dim document = solution.GetDocument(documentId) + + solution = solution.WithDocumentTextLoader(documentId, New FailingTextLoader(document.FilePath), PreservationMode.PreserveIdentity) Await workspace.ChangeSolutionAsync(solution) - Dim project = solution.Projects.Single() - Dim document = project.Documents.Single() + document = solution.GetDocument(documentId) + Dim project = document.Project Dim analyzer = New StatefulCompilationAnalyzer Dim analyzerReference = New AnalyzerImageReference(ImmutableArray.Create(Of DiagnosticAnalyzer)(analyzer)) @@ -916,7 +920,7 @@ class AnonymousFunctions Dim documentDiagnostics = Await DiagnosticProviderTestUtilities.GetDocumentDiagnosticsAsync(workspace, document, TextSpan.FromBounds(0, 0)) AssertEx.Equal( { - "IDE1100: " & String.Format(WorkspacesResources.Error_reading_content_of_source_file_0_1, "Test.cs", "Bad data!") + "IDE1100: " & String.Format(WorkspacesResources.Error_reading_content_of_source_file_0_1, document.FilePath, "Bad data!") }, documentDiagnostics.Select(Function(d) d.Id & ": " & d.GetMessage())) End Using diff --git a/src/roslyn/src/EditorFeatures/Test2/IntelliSense/VisualBasicCompletionCommandHandlerTests.vb b/src/roslyn/src/EditorFeatures/Test2/IntelliSense/VisualBasicCompletionCommandHandlerTests.vb index c640397a1ce..993017d94dd 100644 --- a/src/roslyn/src/EditorFeatures/Test2/IntelliSense/VisualBasicCompletionCommandHandlerTests.vb +++ b/src/roslyn/src/EditorFeatures/Test2/IntelliSense/VisualBasicCompletionCommandHandlerTests.vb @@ -5,6 +5,7 @@ Imports System.Collections.Immutable Imports System.Composition Imports System.Threading +Imports Microsoft.CodeAnalysis.Collections Imports Microsoft.CodeAnalysis.Completion Imports Microsoft.CodeAnalysis.Editor.Implementation.IntelliSense.AsyncCompletion Imports Microsoft.CodeAnalysis.Editor.UnitTests.Extensions diff --git a/src/roslyn/src/EditorFeatures/Test2/NavigationBar/TestHelpers.vb b/src/roslyn/src/EditorFeatures/Test2/NavigationBar/TestHelpers.vb index 968c05751cb..e59a7ceebee 100644 --- a/src/roslyn/src/EditorFeatures/Test2/NavigationBar/TestHelpers.vb +++ b/src/roslyn/src/EditorFeatures/Test2/NavigationBar/TestHelpers.vb @@ -109,13 +109,13 @@ Namespace Microsoft.CodeAnalysis.Editor.UnitTests.NavigationBar Public Async Function AssertNavigationPointAsync( workspaceElement As XElement, host As TestHost, - startingDocumentFilePath As String, + startingDocumentName As String, leftItemToSelectText As String, rightItemToSelectText As String, Optional expectedVirtualSpace As Integer = 0) As Tasks.Task Using workspace = EditorTestWorkspace.Create(workspaceElement, composition:=If(host = TestHost.OutOfProcess, s_oopComposition, s_composition)) - Dim sourceDocument = workspace.CurrentSolution.Projects.First().Documents.First(Function(doc) doc.FilePath = startingDocumentFilePath) + Dim sourceDocument = workspace.CurrentSolution.Projects.First().Documents.First(Function(doc) doc.Name = startingDocumentName) Dim snapshot = (Await sourceDocument.GetTextAsync()).FindCorrespondingEditorTextSnapshot() Dim service = DirectCast(sourceDocument.GetLanguageService(Of INavigationBarItemService)(), AbstractEditorNavigationBarItemService) diff --git a/src/roslyn/src/EditorFeatures/Test2/NavigationBar/VisualBasicNavigationBarTests.vb b/src/roslyn/src/EditorFeatures/Test2/NavigationBar/VisualBasicNavigationBarTests.vb index d50444ee7e6..cea7a0b1551 100644 --- a/src/roslyn/src/EditorFeatures/Test2/NavigationBar/VisualBasicNavigationBarTests.vb +++ b/src/roslyn/src/EditorFeatures/Test2/NavigationBar/VisualBasicNavigationBarTests.vb @@ -956,7 +956,7 @@ End Class , host, - startingDocumentFilePath:="Source.vb", + startingDocumentName:="Source.vb", leftItemToSelectText:="Program", rightItemToSelectText:="TargetMethod") End Function @@ -979,7 +979,7 @@ End Class , host, - startingDocumentFilePath:="Code.vb", + startingDocumentName:="Code.vb", leftItemToSelectText:="Program", rightItemToSelectText:="SomeNumbers") End Function @@ -997,7 +997,7 @@ End Class , host, - startingDocumentFilePath:="Code.vb", + startingDocumentName:="Code.vb", leftItemToSelectText:="Program", rightItemToSelectText:="S") End Function @@ -1016,7 +1016,7 @@ End Class , host, - startingDocumentFilePath:="Code.vb", + startingDocumentName:="Code.vb", leftItemToSelectText:="Program", rightItemToSelectText:="S") End Function @@ -1038,7 +1038,7 @@ End Class , host, - startingDocumentFilePath:="Code.vb", + startingDocumentName:="Code.vb", leftItemToSelectText:="Program", rightItemToSelectText:="S") End Function @@ -1058,7 +1058,7 @@ End Class , host, - startingDocumentFilePath:="Code.vb", + startingDocumentName:="Code.vb", leftItemToSelectText:="Program", rightItemToSelectText:="S") End Function @@ -1078,7 +1078,7 @@ End Class , host, - startingDocumentFilePath:="Code.vb", + startingDocumentName:="Code.vb", leftItemToSelectText:="Program", rightItemToSelectText:="S") End Function @@ -1098,7 +1098,7 @@ End Class , host, - startingDocumentFilePath:="Code.vb", + startingDocumentName:="Code.vb", leftItemToSelectText:="Program", rightItemToSelectText:="S", expectedVirtualSpace:=8) @@ -1119,7 +1119,7 @@ End Class , host, - startingDocumentFilePath:="Code.vb", + startingDocumentName:="Code.vb", leftItemToSelectText:="Program", rightItemToSelectText:="S", expectedVirtualSpace:=4) diff --git a/src/roslyn/src/EditorFeatures/Test2/Peek/PeekTests.vb b/src/roslyn/src/EditorFeatures/Test2/Peek/PeekTests.vb index 93223ec8566..4661fd9bb15 100644 --- a/src/roslyn/src/EditorFeatures/Test2/Peek/PeekTests.vb +++ b/src/roslyn/src/EditorFeatures/Test2/Peek/PeekTests.vb @@ -204,15 +204,15 @@ public class D } } ]]> - public class Component { -#line 4 "Test.razor" +#line 4 "<%= Path.Combine(TestWorkspace.RootDirectory, "Test.razor") %>" public void M() { } } - ]]> + ) Dim result = GetPeekResultCollection(workspace) diff --git a/src/roslyn/src/EditorFeatures/Test2/Rename/RenameEngineTests.vb b/src/roslyn/src/EditorFeatures/Test2/Rename/RenameEngineTests.vb index cad46c18154..88df9f53b3f 100644 --- a/src/roslyn/src/EditorFeatures/Test2/Rename/RenameEngineTests.vb +++ b/src/roslyn/src/EditorFeatures/Test2/Rename/RenameEngineTests.vb @@ -345,8 +345,8 @@ class C2 , host:=host, renameTo:="def") - Dim originalDocument = result.ConflictResolution.OldSolution.Projects.First().Documents.Where(Function(d) d.FilePath = "Test2.cs").Single() - Dim newDocument = result.ConflictResolution.NewSolution.Projects.First().Documents.Where(Function(d) d.FilePath = "Test2.cs").Single() + Dim originalDocument = result.ConflictResolution.OldSolution.Projects.First().Documents.Where(Function(d) d.Name = "Test2.cs").Single() + Dim newDocument = result.ConflictResolution.NewSolution.Projects.First().Documents.Where(Function(d) d.Name = "Test2.cs").Single() Assert.Same(originalDocument.State, newDocument.State) Assert.Equal(1, result.ConflictResolution.NewSolution.GetChangedDocuments(result.ConflictResolution.OldSolution).Count) End Using diff --git a/src/roslyn/src/EditorFeatures/Test2/Rename/RenameTagProducerTests.vb b/src/roslyn/src/EditorFeatures/Test2/Rename/RenameTagProducerTests.vb index 043732945a1..2edfc36c531 100644 --- a/src/roslyn/src/EditorFeatures/Test2/Rename/RenameTagProducerTests.vb +++ b/src/roslyn/src/EditorFeatures/Test2/Rename/RenameTagProducerTests.vb @@ -4,6 +4,7 @@ Imports System.Collections.ObjectModel Imports System.Threading +Imports Microsoft.CodeAnalysis.Collections Imports Microsoft.CodeAnalysis.Editor.Implementation.InlineRename Imports Microsoft.CodeAnalysis.Editor.Implementation.InlineRename.HighlightTags Imports Microsoft.CodeAnalysis.Editor.UnitTests.Extensions @@ -406,7 +407,7 @@ public class Class1 textBuffer.Replace(New Span(location, 1), "B") Await WaitForRename(workspace) - Dim conflictDocument = workspace.Documents.Single(Function(d) d.FilePath = "B.cs") + Dim conflictDocument = workspace.Documents.Single(Function(d) d.Name = "B.cs") Dim expectedSpans = GetAnnotatedSpans("conflict", conflictDocument) Dim taggedSpans = GetTagsOfType(RenameConflictTag.Instance, renameService, conflictDocument.GetTextBuffer()) Assert.Equal(expectedSpans, taggedSpans) diff --git a/src/roslyn/src/EditorFeatures/Test2/SyncNamespaces/SyncNamespacesServiceTests.vb b/src/roslyn/src/EditorFeatures/Test2/SyncNamespaces/SyncNamespacesServiceTests.vb index a2c2d4b2e7a..b715afd4b24 100644 --- a/src/roslyn/src/EditorFeatures/Test2/SyncNamespaces/SyncNamespacesServiceTests.vb +++ b/src/roslyn/src/EditorFeatures/Test2/SyncNamespaces/SyncNamespacesServiceTests.vb @@ -3,9 +3,8 @@ ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable +Imports System.IO Imports System.Threading -Imports Microsoft.CodeAnalysis.CodeActions -Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces Imports Microsoft.CodeAnalysis.Host Imports Microsoft.CodeAnalysis.SyncNamespaces @@ -18,13 +17,13 @@ Namespace Microsoft.CodeAnalysis.Editor.Implementation.CodeFixes.UnitTests Public Async Function SingleProject_MatchingNamespace_NoChanges() As Task Dim test = - - + + is_global=true -build_property.ProjectDir = /Test/ +build_property.ProjectDir = <%= Path.Combine(TestWorkspace.RootDirectory, "Test") %> build_property.RootNamespace = Test.Namespace - + namespace Test.Namespace.App { class Goo @@ -53,13 +52,13 @@ namespace Test.Namespace.App Public Async Function SingleProject_MismatchedNamespace_HasChanges() As Task Dim test = - - + + is_global=true -build_property.ProjectDir = /Test/ +build_property.ProjectDir = <%= Path.Combine(TestWorkspace.RootDirectory, "Test") %> build_property.RootNamespace = Test.Namespace - + namespace Test { class Goo @@ -96,13 +95,13 @@ namespace Test Public Async Function MultipleProjects_MatchingNamespaces_NoChanges() As Task Dim test = - - + + is_global=true -build_property.ProjectDir = /Test/ +build_property.ProjectDir = <%= Path.Combine(TestWorkspace.RootDirectory, "Test") %> build_property.RootNamespace = Test.Namespace - + namespace Test.Namespace.App { class Goo @@ -111,13 +110,13 @@ namespace Test.Namespace.App } - - + + is_global=true -build_property.ProjectDir = /Test2/ +build_property.ProjectDir = <%= Path.Combine(TestWorkspace.RootDirectory, "Test2") %> build_property.RootNamespace = Test2.Namespace - + namespace Test2.Namespace.App { class Goo @@ -146,13 +145,13 @@ namespace Test2.Namespace.App Public Async Function MultipleProjects_OneMismatchedNamespace_HasChanges() As Task Dim test = - - + + is_global=true -build_property.ProjectDir = /Test/ +build_property.ProjectDir = <%= Path.Combine(TestWorkspace.RootDirectory, "Test") %> build_property.RootNamespace = Test.Namespace - + namespace Test.Namespace { class Goo @@ -161,13 +160,13 @@ namespace Test.Namespace } - - + + is_global=true -build_property.ProjectDir = /Test2/ +build_property.ProjectDir = <%= Path.Combine(TestWorkspace.RootDirectory, "Test2") %> build_property.RootNamespace = Test2.Namespace - + namespace Test2.Namespace.App { class Goo @@ -182,7 +181,7 @@ namespace Test2.Namespace.App Dim projects = workspace.CurrentSolution.Projects.ToImmutableArray() Dim project = projects.Single(Function(proj As Project) - Return proj.FilePath = "/Test/Test.csproj" + Return Path.GetFileName(proj.FilePath) = "Test.csproj" End Function) Dim document = project.Documents.Single() @@ -207,13 +206,13 @@ namespace Test2.Namespace.App Public Async Function MultipleProjects_MultipleMismatchedNamespaces_HasChanges() As Task Dim test = - - + + is_global=true -build_property.ProjectDir = /Test/ +build_property.ProjectDir = <%= Path.Combine(TestWorkspace.RootDirectory, "Test") %> build_property.RootNamespace = Test.Namespace - + namespace Test.Namespace { class Goo @@ -222,13 +221,13 @@ namespace Test.Namespace } - - + + is_global=true -build_property.ProjectDir = /Test2/ +build_property.ProjectDir = <%= Path.Combine(TestWorkspace.RootDirectory, "Test2") %> build_property.RootNamespace = Test2.Namespace - + namespace Test2.Namespace { class Goo @@ -243,12 +242,12 @@ namespace Test2.Namespace Dim projects = workspace.CurrentSolution.Projects.ToImmutableArray() Dim project = projects.Single(Function(proj As Project) - Return proj.FilePath = "/Test/Test.csproj" + Return Path.GetFileName(proj.FilePath) = "Test.csproj" End Function) Dim document = project.Documents.Single() Dim project2 = projects.Single(Function(proj As Project) - Return proj.FilePath = "/Test2/Test2.csproj" + Return Path.GetFileName(proj.FilePath) = "Test2.csproj" End Function) Dim document2 = project2.Documents.Single() diff --git a/src/roslyn/src/EditorFeatures/TestUtilities/GoToAdjacentMember/AbstractGoToAdjacentMemberTests.cs b/src/roslyn/src/EditorFeatures/TestUtilities/GoToAdjacentMember/AbstractGoToAdjacentMemberTests.cs index fb442fade88..84e6a0396b8 100644 --- a/src/roslyn/src/EditorFeatures/TestUtilities/GoToAdjacentMember/AbstractGoToAdjacentMemberTests.cs +++ b/src/roslyn/src/EditorFeatures/TestUtilities/GoToAdjacentMember/AbstractGoToAdjacentMemberTests.cs @@ -7,6 +7,7 @@ using System.Linq; using System.Threading; using System.Threading.Tasks; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.LanguageService; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Test.Utilities; diff --git a/src/roslyn/src/EditorFeatures/VisualBasic/AutomaticCompletion/AutomaticLineEnderCommandHandler.vb b/src/roslyn/src/EditorFeatures/VisualBasic/AutomaticCompletion/AutomaticLineEnderCommandHandler.vb index aeae57260ac..7a6bd7e369f 100644 --- a/src/roslyn/src/EditorFeatures/VisualBasic/AutomaticCompletion/AutomaticLineEnderCommandHandler.vb +++ b/src/roslyn/src/EditorFeatures/VisualBasic/AutomaticCompletion/AutomaticLineEnderCommandHandler.vb @@ -5,6 +5,7 @@ Imports System.ComponentModel.Composition Imports System.Threading Imports Microsoft.CodeAnalysis.AutomaticCompletion +Imports Microsoft.CodeAnalysis.Collections Imports Microsoft.CodeAnalysis.Diagnostics Imports Microsoft.CodeAnalysis.Formatting Imports Microsoft.CodeAnalysis.Host.Mef diff --git a/src/roslyn/src/EditorFeatures/VisualBasic/EndConstructGeneration/EndConstructStatementVisitor_IfStatement.vb b/src/roslyn/src/EditorFeatures/VisualBasic/EndConstructGeneration/EndConstructStatementVisitor_IfStatement.vb index b47d0ee6703..2be009de6e8 100644 --- a/src/roslyn/src/EditorFeatures/VisualBasic/EndConstructGeneration/EndConstructStatementVisitor_IfStatement.vb +++ b/src/roslyn/src/EditorFeatures/VisualBasic/EndConstructGeneration/EndConstructStatementVisitor_IfStatement.vb @@ -2,6 +2,7 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. +Imports Microsoft.CodeAnalysis.Collections Imports Microsoft.CodeAnalysis.Text.Shared.Extensions Imports Microsoft.CodeAnalysis.VisualBasic.Syntax diff --git a/src/roslyn/src/EditorFeatures/VisualBasicTest/KeywordHighlighting/AbstractVisualBasicKeywordHighlighterTests.vb b/src/roslyn/src/EditorFeatures/VisualBasicTest/KeywordHighlighting/AbstractVisualBasicKeywordHighlighterTests.vb index c8012131e34..fa8ff80f7ab 100644 --- a/src/roslyn/src/EditorFeatures/VisualBasicTest/KeywordHighlighting/AbstractVisualBasicKeywordHighlighterTests.vb +++ b/src/roslyn/src/EditorFeatures/VisualBasicTest/KeywordHighlighting/AbstractVisualBasicKeywordHighlighterTests.vb @@ -2,6 +2,7 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. +Imports Microsoft.CodeAnalysis.Collections Imports Microsoft.CodeAnalysis.Editor.UnitTests.Extensions Imports Microsoft.CodeAnalysis.Editor.UnitTests.KeywordHighlighting Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces diff --git a/src/roslyn/src/EditorFeatures/VisualBasicTest/NavigateTo/NavigateToTests.vb b/src/roslyn/src/EditorFeatures/VisualBasicTest/NavigateTo/NavigateToTests.vb index e65db62bf19..56e6382b9af 100644 --- a/src/roslyn/src/EditorFeatures/VisualBasicTest/NavigateTo/NavigateToTests.vb +++ b/src/roslyn/src/EditorFeatures/VisualBasicTest/NavigateTo/NavigateToTests.vb @@ -792,7 +792,7 @@ End Class", Async Function(w) Assert.Equal(value, descriptionItem.Details.Single().Text) End Sub - assertDescription("File:", w.Documents.Single().Name) + assertDescription("File:", w.Documents.Single().FilePath) assertDescription("Line:", "2") assertDescription("Project:", "Test") End Function) diff --git a/src/roslyn/src/EditorFeatures/VisualBasicTest/SignatureHelp/InvocationExpressionSignatureHelpProviderTests.vb b/src/roslyn/src/EditorFeatures/VisualBasicTest/SignatureHelp/InvocationExpressionSignatureHelpProviderTests.vb index 8cb4b7cd813..6074a942ec3 100644 --- a/src/roslyn/src/EditorFeatures/VisualBasicTest/SignatureHelp/InvocationExpressionSignatureHelpProviderTests.vb +++ b/src/roslyn/src/EditorFeatures/VisualBasicTest/SignatureHelp/InvocationExpressionSignatureHelpProviderTests.vb @@ -2,6 +2,7 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. +Imports Microsoft.CodeAnalysis.Collections Imports Microsoft.CodeAnalysis.Editor.UnitTests.SignatureHelp Imports Microsoft.CodeAnalysis.VisualBasic.SignatureHelp diff --git a/src/roslyn/src/ExpressionEvaluator/CSharp/Source/ExpressionCompiler/Symbols/EENamedTypeSymbol.cs b/src/roslyn/src/ExpressionEvaluator/CSharp/Source/ExpressionCompiler/Symbols/EENamedTypeSymbol.cs index 23643883a6b..32bc84a21f7 100644 --- a/src/roslyn/src/ExpressionEvaluator/CSharp/Source/ExpressionCompiler/Symbols/EENamedTypeSymbol.cs +++ b/src/roslyn/src/ExpressionEvaluator/CSharp/Source/ExpressionCompiler/Symbols/EENamedTypeSymbol.cs @@ -8,6 +8,7 @@ using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.CSharp.Symbols; using Roslyn.Utilities; diff --git a/src/roslyn/src/ExpressionEvaluator/Core/Source/ExpressionCompiler/AssemblyReference.cs b/src/roslyn/src/ExpressionEvaluator/Core/Source/ExpressionCompiler/AssemblyReference.cs index e71161d7191..f8fbb15fab1 100644 --- a/src/roslyn/src/ExpressionEvaluator/Core/Source/ExpressionCompiler/AssemblyReference.cs +++ b/src/roslyn/src/ExpressionEvaluator/Core/Source/ExpressionCompiler/AssemblyReference.cs @@ -2,11 +2,12 @@ // 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; +using System.Collections.Generic; using Microsoft.Cci; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.Emit; using Roslyn.Utilities; -using System; -using System.Collections.Generic; namespace Microsoft.CodeAnalysis.ExpressionEvaluator { diff --git a/src/roslyn/src/ExpressionEvaluator/Core/Source/ExpressionCompiler/DkmUtilities.cs b/src/roslyn/src/ExpressionEvaluator/Core/Source/ExpressionCompiler/DkmUtilities.cs index 38639903bc8..3aa81e301d7 100644 --- a/src/roslyn/src/ExpressionEvaluator/Core/Source/ExpressionCompiler/DkmUtilities.cs +++ b/src/roslyn/src/ExpressionEvaluator/Core/Source/ExpressionCompiler/DkmUtilities.cs @@ -9,6 +9,7 @@ using System.Diagnostics; using System.Linq; using System.Reflection.Metadata; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.Debugging; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Symbols; diff --git a/src/roslyn/src/ExpressionEvaluator/VisualBasic/Source/ExpressionCompiler/EEAssemblyBuilder.vb b/src/roslyn/src/ExpressionEvaluator/VisualBasic/Source/ExpressionCompiler/EEAssemblyBuilder.vb index 6fb8bc777ac..9a404f842d4 100644 --- a/src/roslyn/src/ExpressionEvaluator/VisualBasic/Source/ExpressionCompiler/EEAssemblyBuilder.vb +++ b/src/roslyn/src/ExpressionEvaluator/VisualBasic/Source/ExpressionCompiler/EEAssemblyBuilder.vb @@ -2,8 +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. +Imports System.Collections.Immutable +Imports System.Diagnostics +Imports System.Reflection.Metadata +Imports System.Runtime.InteropServices Imports Microsoft.Cci Imports Microsoft.CodeAnalysis.CodeGen +Imports Microsoft.CodeAnalysis.Collections Imports Microsoft.CodeAnalysis.Emit Imports Microsoft.CodeAnalysis.ExpressionEvaluator Imports Microsoft.CodeAnalysis.PooledObjects @@ -11,10 +16,6 @@ Imports Microsoft.CodeAnalysis.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Emit Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Symbols.Metadata.PE -Imports System.Collections.Immutable -Imports System.Diagnostics -Imports System.Reflection.Metadata -Imports System.Runtime.InteropServices Imports Roslyn.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.ExpressionEvaluator diff --git a/src/roslyn/src/ExpressionEvaluator/VisualBasic/Source/ExpressionCompiler/Symbols/EENamedTypeSymbol.vb b/src/roslyn/src/ExpressionEvaluator/VisualBasic/Source/ExpressionCompiler/Symbols/EENamedTypeSymbol.vb index 1d6662d79a9..3177c68027c 100644 --- a/src/roslyn/src/ExpressionEvaluator/VisualBasic/Source/ExpressionCompiler/Symbols/EENamedTypeSymbol.vb +++ b/src/roslyn/src/ExpressionEvaluator/VisualBasic/Source/ExpressionCompiler/Symbols/EENamedTypeSymbol.vb @@ -6,6 +6,7 @@ Imports System.Collections.Immutable Imports System.Runtime.InteropServices Imports System.Threading Imports Microsoft.Cci +Imports Microsoft.CodeAnalysis.Collections Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Roslyn.Utilities diff --git a/src/roslyn/src/Features/CSharp/Portable/Completion/CompletionProviders/XmlDocCommentCompletionProvider.cs b/src/roslyn/src/Features/CSharp/Portable/Completion/CompletionProviders/XmlDocCommentCompletionProvider.cs index f5e8f62abec..d79ea9c581d 100644 --- a/src/roslyn/src/Features/CSharp/Portable/Completion/CompletionProviders/XmlDocCommentCompletionProvider.cs +++ b/src/roslyn/src/Features/CSharp/Portable/Completion/CompletionProviders/XmlDocCommentCompletionProvider.cs @@ -10,6 +10,7 @@ using System.Linq; using System.Threading; using System.Threading.Tasks; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.Completion; using Microsoft.CodeAnalysis.Completion.Providers; using Microsoft.CodeAnalysis.CSharp.Extensions; diff --git a/src/roslyn/src/Features/CSharp/Portable/SignatureHelp/TupleConstructionSignatureHelpProvider.cs b/src/roslyn/src/Features/CSharp/Portable/SignatureHelp/TupleConstructionSignatureHelpProvider.cs index c1cfc778abd..9b63703f76e 100644 --- a/src/roslyn/src/Features/CSharp/Portable/SignatureHelp/TupleConstructionSignatureHelpProvider.cs +++ b/src/roslyn/src/Features/CSharp/Portable/SignatureHelp/TupleConstructionSignatureHelpProvider.cs @@ -10,6 +10,7 @@ using System.Linq; using System.Threading; using System.Threading.Tasks; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.LanguageService; diff --git a/src/roslyn/src/Features/CSharpTest/ExtractMethod/ExtractLocalFunctionTests.cs b/src/roslyn/src/Features/CSharpTest/ExtractMethod/ExtractLocalFunctionTests.cs index 0ae7a1e3a0f..c6586b0c3f0 100644 --- a/src/roslyn/src/Features/CSharpTest/ExtractMethod/ExtractLocalFunctionTests.cs +++ b/src/roslyn/src/Features/CSharpTest/ExtractMethod/ExtractLocalFunctionTests.cs @@ -4574,7 +4574,7 @@ public async Task TestNaming_CamelCase_DoesntApply() var input = """ - + class Program1 { static void Main() @@ -4584,7 +4584,7 @@ static void Main() } } - + """ + EditorConfigNaming_CamelCase + """ dotnet_naming_symbols.local_functions.required_modifiers = static @@ -4595,7 +4595,7 @@ static void Main() var expected = """ - + class Program1 { static void Main() @@ -4610,7 +4610,7 @@ bool NewMethod() } } - + """ + EditorConfigNaming_CamelCase + """ dotnet_naming_symbols.local_functions.required_modifiers = static diff --git a/src/roslyn/src/Features/Core/Portable/CodeFixes/Suppression/AbstractSuppressionCodeFixProvider.AbstractGlobalSuppressMessageCodeAction.cs b/src/roslyn/src/Features/Core/Portable/CodeFixes/Suppression/AbstractSuppressionCodeFixProvider.AbstractGlobalSuppressMessageCodeAction.cs index dce4b49dc22..37a1d650a4e 100644 --- a/src/roslyn/src/Features/Core/Portable/CodeFixes/Suppression/AbstractSuppressionCodeFixProvider.AbstractGlobalSuppressMessageCodeAction.cs +++ b/src/roslyn/src/Features/Core/Portable/CodeFixes/Suppression/AbstractSuppressionCodeFixProvider.AbstractGlobalSuppressMessageCodeAction.cs @@ -8,10 +8,12 @@ using System.Collections.Immutable; using System.IO; using System.Linq; +using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.LanguageService; +using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CodeFixes.Suppression; @@ -104,7 +106,8 @@ protected async Task GetOrCreateSuppressionsDocumentAsync(Cancellation else { // Create an empty global suppressions file. - suppressionsDoc = _project.AddDocument(suppressionsFileName, string.Empty); + var emptyText = SourceText.From("", Encoding.UTF8, SourceHashAlgorithms.Default); + suppressionsDoc = _project.AddDocument(suppressionsFileName, emptyText, filePath: suppressionsFilePath); } } } diff --git a/src/roslyn/src/Features/Core/Portable/CodeRefactorings/MoveType/AbstractMoveTypeService.Editor.cs b/src/roslyn/src/Features/Core/Portable/CodeRefactorings/MoveType/AbstractMoveTypeService.Editor.cs index 35aede8ef24..7e70c10d453 100644 --- a/src/roslyn/src/Features/Core/Portable/CodeRefactorings/MoveType/AbstractMoveTypeService.Editor.cs +++ b/src/roslyn/src/Features/Core/Portable/CodeRefactorings/MoveType/AbstractMoveTypeService.Editor.cs @@ -6,6 +6,7 @@ using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; +using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CodeRefactorings.MoveType; @@ -50,5 +51,10 @@ public static Editor GetEditor(MoveTypeOperationKind operationKind, TService ser MoveTypeOperationKind.MoveTypeNamespaceScope => new MoveTypeNamespaceScopeEditor(service, document, typeDeclaration, fileName, cancellationToken), _ => throw ExceptionUtilities.UnexpectedValue(operationKind), }; + + protected string? GetTargetDocumentFilePath() + => PathUtilities.GetDirectoryName(SemanticDocument.Document.FilePath) is { } dir + ? PathUtilities.CombinePaths(dir, FileName) + : null; } } diff --git a/src/roslyn/src/Features/Core/Portable/CodeRefactorings/MoveType/AbstractMoveTypeService.MoveTypeEditor.cs b/src/roslyn/src/Features/Core/Portable/CodeRefactorings/MoveType/AbstractMoveTypeService.MoveTypeEditor.cs index e4fc8389b39..2bd31a250ab 100644 --- a/src/roslyn/src/Features/Core/Portable/CodeRefactorings/MoveType/AbstractMoveTypeService.MoveTypeEditor.cs +++ b/src/roslyn/src/Features/Core/Portable/CodeRefactorings/MoveType/AbstractMoveTypeService.MoveTypeEditor.cs @@ -6,6 +6,7 @@ using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; +using System.IO; using System.Linq; using System.Threading; using System.Threading.Tasks; @@ -157,10 +158,7 @@ private async Task AddNewDocumentWithSingleTypeDeclarationAsync(Docume // add an empty document to solution, so that we'll have options from the right context. var solutionWithNewDocument = projectToBeUpdated.Solution.AddDocument( - newDocumentId, FileName, text: string.Empty, folders: document.Folders); - - // update the text for the new document - solutionWithNewDocument = solutionWithNewDocument.WithDocumentSyntaxRoot(newDocumentId, modifiedRoot, PreservationMode.PreserveIdentity); + newDocumentId, FileName, modifiedRoot, document.Folders, filePath: GetTargetDocumentFilePath()); // get the updated document, give it the minimal set of imports that the type // inside it needs. diff --git a/src/roslyn/src/Features/Core/Portable/EditAndContinue/DeclarationBodyMap.cs b/src/roslyn/src/Features/Core/Portable/EditAndContinue/DeclarationBodyMap.cs index a718933ce95..7055fe2c499 100644 --- a/src/roslyn/src/Features/Core/Portable/EditAndContinue/DeclarationBodyMap.cs +++ b/src/roslyn/src/Features/Core/Portable/EditAndContinue/DeclarationBodyMap.cs @@ -4,6 +4,7 @@ using System.Collections.Generic; using System.Collections.Immutable; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.Differencing; using Roslyn.Utilities; diff --git a/src/roslyn/src/Features/Core/Portable/EditAndContinue/Utilities/BidirectionalMap.cs b/src/roslyn/src/Features/Core/Portable/EditAndContinue/Utilities/BidirectionalMap.cs index b8b9e320ce4..7a9c419522d 100644 --- a/src/roslyn/src/Features/Core/Portable/EditAndContinue/Utilities/BidirectionalMap.cs +++ b/src/roslyn/src/Features/Core/Portable/EditAndContinue/Utilities/BidirectionalMap.cs @@ -3,6 +3,7 @@ // See the LICENSE file in the project root for more information. using System.Collections.Generic; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.Differencing; using Roslyn.Utilities; diff --git a/src/roslyn/src/Features/Core/Portable/ExtractInterface/ExtractInterfaceCodeAction.cs b/src/roslyn/src/Features/Core/Portable/ExtractInterface/ExtractInterfaceCodeAction.cs index 308cca1569f..6a9033a83ca 100644 --- a/src/roslyn/src/Features/Core/Portable/ExtractInterface/ExtractInterfaceCodeAction.cs +++ b/src/roslyn/src/Features/Core/Portable/ExtractInterface/ExtractInterfaceCodeAction.cs @@ -7,6 +7,7 @@ using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; +using Microsoft.CodeAnalysis.Collections; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.ExtractInterface; diff --git a/src/roslyn/src/Features/Core/Portable/ExtractMethod/AbstractSyntaxTriviaService.cs b/src/roslyn/src/Features/Core/Portable/ExtractMethod/AbstractSyntaxTriviaService.cs index b12ececb621..cae8e39b9bc 100644 --- a/src/roslyn/src/Features/Core/Portable/ExtractMethod/AbstractSyntaxTriviaService.cs +++ b/src/roslyn/src/Features/Core/Portable/ExtractMethod/AbstractSyntaxTriviaService.cs @@ -7,6 +7,7 @@ using System.Diagnostics; using System.Linq; using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; diff --git a/src/roslyn/src/Features/Core/Portable/GenerateType/AbstractGenerateTypeService.CodeAction.cs b/src/roslyn/src/Features/Core/Portable/GenerateType/AbstractGenerateTypeService.CodeAction.cs index a12d05bd7e6..62bb1ce3292 100644 --- a/src/roslyn/src/Features/Core/Portable/GenerateType/AbstractGenerateTypeService.CodeAction.cs +++ b/src/roslyn/src/Features/Core/Portable/GenerateType/AbstractGenerateTypeService.CodeAction.cs @@ -8,6 +8,7 @@ using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.LanguageService; using Microsoft.CodeAnalysis.Notification; using Microsoft.CodeAnalysis.ProjectManagement; diff --git a/src/roslyn/src/Features/Core/Portable/LanguageServices/AnonymousTypeDisplayService/AbstractStructuralTypeDisplayService.cs b/src/roslyn/src/Features/Core/Portable/LanguageServices/AnonymousTypeDisplayService/AbstractStructuralTypeDisplayService.cs index 9f6b7df2c5b..a8e57e9361c 100644 --- a/src/roslyn/src/Features/Core/Portable/LanguageServices/AnonymousTypeDisplayService/AbstractStructuralTypeDisplayService.cs +++ b/src/roslyn/src/Features/Core/Portable/LanguageServices/AnonymousTypeDisplayService/AbstractStructuralTypeDisplayService.cs @@ -5,6 +5,7 @@ using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; diff --git a/src/roslyn/src/Features/Core/Portable/LanguageServices/SymbolDisplayService/AbstractSymbolDisplayService.cs b/src/roslyn/src/Features/Core/Portable/LanguageServices/SymbolDisplayService/AbstractSymbolDisplayService.cs index c3827e8cae0..60c3add0450 100644 --- a/src/roslyn/src/Features/Core/Portable/LanguageServices/SymbolDisplayService/AbstractSymbolDisplayService.cs +++ b/src/roslyn/src/Features/Core/Portable/LanguageServices/SymbolDisplayService/AbstractSymbolDisplayService.cs @@ -6,6 +6,7 @@ using System.Collections.Immutable; using System.Threading; using System.Threading.Tasks; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.Host; using Roslyn.Utilities; diff --git a/src/roslyn/src/Features/Core/Portable/MoveStaticMembers/MoveStaticMembersOptions.cs b/src/roslyn/src/Features/Core/Portable/MoveStaticMembers/MoveStaticMembersOptions.cs index 6d1c8b45284..6fefee44ca6 100644 --- a/src/roslyn/src/Features/Core/Portable/MoveStaticMembers/MoveStaticMembersOptions.cs +++ b/src/roslyn/src/Features/Core/Portable/MoveStaticMembers/MoveStaticMembersOptions.cs @@ -12,7 +12,7 @@ internal readonly struct MoveStaticMembersOptions { public bool IsCancelled { get; } - public string FileName { get; } + public string FilePath { get; } public bool IsNewType { get; } @@ -42,7 +42,7 @@ public MoveStaticMembersOptions( RoslynDebug.AssertNotNull(sourceLocation.SyntaxTree); IsCancelled = isCancelled; - FileName = sourceLocation.SyntaxTree.FilePath; + FilePath = sourceLocation.SyntaxTree.FilePath; IsNewType = false; Destination = destination; TypeName = null; @@ -57,7 +57,7 @@ public MoveStaticMembersOptions( bool isCancelled = false) { IsCancelled = isCancelled; - FileName = fileName; + FilePath = fileName; IsNewType = true; Destination = null; var namespacesAndType = fullTypeName.Split(separator: '.'); diff --git a/src/roslyn/src/Features/Core/Portable/MoveStaticMembers/MoveStaticMembersWithDialogCodeAction.cs b/src/roslyn/src/Features/Core/Portable/MoveStaticMembers/MoveStaticMembersWithDialogCodeAction.cs index 941fe57932d..11fe4ab91a4 100644 --- a/src/roslyn/src/Features/Core/Portable/MoveStaticMembers/MoveStaticMembersWithDialogCodeAction.cs +++ b/src/roslyn/src/Features/Core/Portable/MoveStaticMembers/MoveStaticMembersWithDialogCodeAction.cs @@ -63,7 +63,7 @@ protected override async Task> ComputeOperation // we already have our destination type, but we need to find the document it is in // When it is an existing type, "FileName" points to a full path rather than just the name // There should be no two docs that have the same file path - var destinationDocId = _document.Project.Solution.GetDocumentIdsWithFilePath(moveOptions.FileName).Single(); + var destinationDocId = _document.Project.Solution.GetDocumentIdsWithFilePath(moveOptions.FilePath).Single(); var fixedSolution = await RefactorAndMoveAsync( moveOptions.SelectedMembers, @@ -102,7 +102,7 @@ protected override async Task> ComputeOperation var (newDoc, annotation) = await ExtractTypeHelpers.AddTypeToNewFileAsync( sourceDoc.Project.Solution, moveOptions.NamespaceDisplay, - moveOptions.FileName, + moveOptions.FilePath, sourceDoc.Project.Id, sourceDoc.Folders, newType, diff --git a/src/roslyn/src/Features/Core/Portable/Navigation/NavigableItemFactory.cs b/src/roslyn/src/Features/Core/Portable/Navigation/NavigableItemFactory.cs index b4f4f502413..b734c1339dd 100644 --- a/src/roslyn/src/Features/Core/Portable/Navigation/NavigableItemFactory.cs +++ b/src/roslyn/src/Features/Core/Portable/Navigation/NavigableItemFactory.cs @@ -6,6 +6,7 @@ using System.Collections.Immutable; using System.Linq; using System.Threading; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; diff --git a/src/roslyn/src/Features/Core/Portable/ReplacePropertyWithMethods/AbstractReplacePropertyWithMethodsService.cs b/src/roslyn/src/Features/Core/Portable/ReplacePropertyWithMethods/AbstractReplacePropertyWithMethodsService.cs index b79956802af..e1fc1c8eaf8 100644 --- a/src/roslyn/src/Features/Core/Portable/ReplacePropertyWithMethods/AbstractReplacePropertyWithMethodsService.cs +++ b/src/roslyn/src/Features/Core/Portable/ReplacePropertyWithMethods/AbstractReplacePropertyWithMethodsService.cs @@ -9,6 +9,7 @@ using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeRefactorings; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.LanguageService; using Microsoft.CodeAnalysis.Shared.Extensions; diff --git a/src/roslyn/src/Features/Core/Portable/SignatureHelp/AbstractSignatureHelpProvider.cs b/src/roslyn/src/Features/Core/Portable/SignatureHelp/AbstractSignatureHelpProvider.cs index d2b348584b2..2a6e78acfc3 100644 --- a/src/roslyn/src/Features/Core/Portable/SignatureHelp/AbstractSignatureHelpProvider.cs +++ b/src/roslyn/src/Features/Core/Portable/SignatureHelp/AbstractSignatureHelpProvider.cs @@ -8,6 +8,7 @@ using System.Linq; using System.Threading; using System.Threading.Tasks; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.LanguageService; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; diff --git a/src/roslyn/src/Features/Core/Portable/Workspace/MiscellaneousFileUtilities.cs b/src/roslyn/src/Features/Core/Portable/Workspace/MiscellaneousFileUtilities.cs index f5457cf6551..d7784bcf900 100644 --- a/src/roslyn/src/Features/Core/Portable/Workspace/MiscellaneousFileUtilities.cs +++ b/src/roslyn/src/Features/Core/Portable/Workspace/MiscellaneousFileUtilities.cs @@ -46,6 +46,12 @@ internal static ProjectInfo CreateMiscellaneousProjectInfoForDocument( compilationOptions = GetCompilationOptionsWithScriptReferenceResolvers(services, compilationOptions, filePath); } + if (parseOptions != null && fileExtension != languageInformation.ScriptExtension) + { + // Any non-script misc file should not complain about usage of '#:' ignored directives. + parseOptions = parseOptions.WithFeatures([.. parseOptions.Features, new("FileBasedProgram", "true")]); + } + var projectId = ProjectId.CreateNewId(debugName: $"{workspace.GetType().Name} Files Project for {filePath}"); var documentId = DocumentId.CreateNewId(projectId, debugName: filePath); diff --git a/src/roslyn/src/Features/TestUtilities/Snippets/AbstractSnippetProviderTests.cs b/src/roslyn/src/Features/TestUtilities/Snippets/AbstractSnippetProviderTests.cs index 838958b955d..53086d840f9 100644 --- a/src/roslyn/src/Features/TestUtilities/Snippets/AbstractSnippetProviderTests.cs +++ b/src/roslyn/src/Features/TestUtilities/Snippets/AbstractSnippetProviderTests.cs @@ -4,6 +4,8 @@ using System.Collections.Immutable; using System.Diagnostics.CodeAnalysis; +using System.IO; +using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Shared.Extensions; @@ -37,11 +39,18 @@ protected async Task VerifySnippetAsync( .WithMetadataReferences(metadataReferences); TestFileMarkupParser.GetPosition(markupBeforeCommit, out markupBeforeCommit, out var snippetRequestPosition); - var document = project.AddDocument("TestDocument", markupBeforeCommit, filePath: "/TestDocument"); + var document = project.AddDocument( + "TestDocument", + SourceText.From(markupBeforeCommit, Encoding.UTF8, SourceHashAlgorithms.Default), + filePath: Path.Combine(TempRoot.Root, "TestDocument")); if (editorconfig is not null) { - var editorConfigDoc = document.Project.AddAnalyzerConfigDocument(".editorconfig", SourceText.From(editorconfig), filePath: "/.editorconfig"); + var editorConfigDoc = document.Project.AddAnalyzerConfigDocument( + ".editorconfig", + SourceText.From(editorconfig, Encoding.UTF8, SourceHashAlgorithms.Default), + filePath: Path.Combine(TempRoot.Root, ".editorconfig")); + document = editorConfigDoc.Project.GetDocument(document.Id)!; } @@ -120,7 +129,7 @@ protected async Task VerifySnippetIsAbsentAsync( .WithMetadataReferences(metadataReferences); TestFileMarkupParser.GetPosition(markup, out markup, out var snippetRequestPosition); - var document = project.AddDocument("TestDocument", markup); + var document = project.AddDocument("TestDocument", SourceText.From(markup, Encoding.UTF8, SourceHashAlgorithms.Default)); var snippetServiceInterface = document.GetRequiredLanguageService(); var snippetService = Assert.IsAssignableFrom(snippetServiceInterface); diff --git a/src/roslyn/src/Features/VisualBasic/Portable/CodeFixes/IncorrectFunctionReturnType/IncorrectFunctionReturnTypeCodeFixProvider.vb b/src/roslyn/src/Features/VisualBasic/Portable/CodeFixes/IncorrectFunctionReturnType/IncorrectFunctionReturnTypeCodeFixProvider.vb index aaefe834904..3932389ef15 100644 --- a/src/roslyn/src/Features/VisualBasic/Portable/CodeFixes/IncorrectFunctionReturnType/IncorrectFunctionReturnTypeCodeFixProvider.vb +++ b/src/roslyn/src/Features/VisualBasic/Portable/CodeFixes/IncorrectFunctionReturnType/IncorrectFunctionReturnTypeCodeFixProvider.vb @@ -9,6 +9,7 @@ Imports System.Threading Imports Microsoft.CodeAnalysis.CodeActions Imports Microsoft.CodeAnalysis.CodeCleanup Imports Microsoft.CodeAnalysis.CodeFixes +Imports Microsoft.CodeAnalysis.Collections Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Syntax diff --git a/src/roslyn/src/Features/VisualBasic/Portable/CodeFixes/MoveToTopOfFile/MoveToTopOfFileCodeFixProvider.vb b/src/roslyn/src/Features/VisualBasic/Portable/CodeFixes/MoveToTopOfFile/MoveToTopOfFileCodeFixProvider.vb index b9ba95ef1b3..9e0dd4da321 100644 --- a/src/roslyn/src/Features/VisualBasic/Portable/CodeFixes/MoveToTopOfFile/MoveToTopOfFileCodeFixProvider.vb +++ b/src/roslyn/src/Features/VisualBasic/Portable/CodeFixes/MoveToTopOfFile/MoveToTopOfFileCodeFixProvider.vb @@ -9,6 +9,7 @@ Imports System.Threading Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.CodeActions Imports Microsoft.CodeAnalysis.CodeFixes +Imports Microsoft.CodeAnalysis.Collections Imports Microsoft.CodeAnalysis.VisualBasic.CodeActions Imports Microsoft.CodeAnalysis.VisualBasic.Syntax diff --git a/src/roslyn/src/Features/VisualBasic/Portable/Completion/CompletionProviders/CrefCompletionProvider.vb b/src/roslyn/src/Features/VisualBasic/Portable/Completion/CompletionProviders/CrefCompletionProvider.vb index d66fe1f93ae..8734d2fae14 100644 --- a/src/roslyn/src/Features/VisualBasic/Portable/Completion/CompletionProviders/CrefCompletionProvider.vb +++ b/src/roslyn/src/Features/VisualBasic/Portable/Completion/CompletionProviders/CrefCompletionProvider.vb @@ -7,6 +7,7 @@ Imports System.Composition Imports System.Text Imports System.Threading Imports Microsoft.CodeAnalysis +Imports Microsoft.CodeAnalysis.Collections Imports Microsoft.CodeAnalysis.Completion Imports Microsoft.CodeAnalysis.Completion.Providers Imports Microsoft.CodeAnalysis.ErrorReporting diff --git a/src/roslyn/src/Features/VisualBasic/Portable/Completion/CompletionProviders/NamedParameterCompletionProvider.vb b/src/roslyn/src/Features/VisualBasic/Portable/Completion/CompletionProviders/NamedParameterCompletionProvider.vb index f5e6e4dd229..2ffacc9fe17 100644 --- a/src/roslyn/src/Features/VisualBasic/Portable/Completion/CompletionProviders/NamedParameterCompletionProvider.vb +++ b/src/roslyn/src/Features/VisualBasic/Portable/Completion/CompletionProviders/NamedParameterCompletionProvider.vb @@ -3,17 +3,18 @@ ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable +Imports System.Composition Imports System.Threading +Imports Microsoft.CodeAnalysis.Collections Imports Microsoft.CodeAnalysis.Completion Imports Microsoft.CodeAnalysis.Completion.Providers -Imports Microsoft.CodeAnalysis.Text -Imports Microsoft.CodeAnalysis.VisualBasic.Syntax -Imports Microsoft.CodeAnalysis.Options -Imports Microsoft.CodeAnalysis.VisualBasic.Extensions.ContextQuery Imports Microsoft.CodeAnalysis.ErrorReporting -Imports System.Composition Imports Microsoft.CodeAnalysis.Host.Mef Imports Microsoft.CodeAnalysis.LanguageService +Imports Microsoft.CodeAnalysis.Options +Imports Microsoft.CodeAnalysis.Text +Imports Microsoft.CodeAnalysis.VisualBasic.Extensions.ContextQuery +Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.Completion.Providers diff --git a/src/roslyn/src/Features/VisualBasic/Portable/Completion/CompletionProviders/XmlDocCommentCompletionProvider.vb b/src/roslyn/src/Features/VisualBasic/Portable/Completion/CompletionProviders/XmlDocCommentCompletionProvider.vb index 0c4b6054807..3f560688767 100644 --- a/src/roslyn/src/Features/VisualBasic/Portable/Completion/CompletionProviders/XmlDocCommentCompletionProvider.vb +++ b/src/roslyn/src/Features/VisualBasic/Portable/Completion/CompletionProviders/XmlDocCommentCompletionProvider.vb @@ -5,6 +5,7 @@ Imports System.Collections.Immutable Imports System.Composition Imports System.Threading +Imports Microsoft.CodeAnalysis.Collections Imports Microsoft.CodeAnalysis.Completion Imports Microsoft.CodeAnalysis.Completion.Providers Imports Microsoft.CodeAnalysis.ErrorReporting diff --git a/src/roslyn/src/Features/VisualBasic/Portable/ConvertIfToSwitch/VisualBasicConvertIfToSwitchCodeRefactoringProvider.Rewriting.vb b/src/roslyn/src/Features/VisualBasic/Portable/ConvertIfToSwitch/VisualBasicConvertIfToSwitchCodeRefactoringProvider.Rewriting.vb index 26a4c2cc134..c80d4ba0c1b 100644 --- a/src/roslyn/src/Features/VisualBasic/Portable/ConvertIfToSwitch/VisualBasicConvertIfToSwitchCodeRefactoringProvider.Rewriting.vb +++ b/src/roslyn/src/Features/VisualBasic/Portable/ConvertIfToSwitch/VisualBasicConvertIfToSwitchCodeRefactoringProvider.Rewriting.vb @@ -3,9 +3,10 @@ ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable -Imports Microsoft.CodeAnalysis.VisualBasic.Syntax +Imports Microsoft.CodeAnalysis.Collections Imports Microsoft.CodeAnalysis.Operations Imports Microsoft.CodeAnalysis.VisualBasic.CodeGeneration +Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.ConvertIfToSwitch Partial Friend NotInheritable Class VisualBasicConvertIfToSwitchCodeRefactoringProvider diff --git a/src/roslyn/src/Features/VisualBasic/Portable/Debugging/BreakpointResolver.vb b/src/roslyn/src/Features/VisualBasic/Portable/Debugging/BreakpointResolver.vb index a4563ab669c..f5c2c8afd5b 100644 --- a/src/roslyn/src/Features/VisualBasic/Portable/Debugging/BreakpointResolver.vb +++ b/src/roslyn/src/Features/VisualBasic/Portable/Debugging/BreakpointResolver.vb @@ -4,8 +4,9 @@ Imports System.Threading Imports Microsoft.CodeAnalysis -Imports Microsoft.CodeAnalysis.VisualBasic.Syntax +Imports Microsoft.CodeAnalysis.Collections Imports Microsoft.CodeAnalysis.Debugging +Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.Debugging diff --git a/src/roslyn/src/Features/VisualBasic/Portable/EditAndContinue/DeclarationBody/PropertyWithInitializerDeclarationBody.vb b/src/roslyn/src/Features/VisualBasic/Portable/EditAndContinue/DeclarationBody/PropertyWithInitializerDeclarationBody.vb index ee0efab03ed..5385782b62a 100644 --- a/src/roslyn/src/Features/VisualBasic/Portable/EditAndContinue/DeclarationBody/PropertyWithInitializerDeclarationBody.vb +++ b/src/roslyn/src/Features/VisualBasic/Portable/EditAndContinue/DeclarationBody/PropertyWithInitializerDeclarationBody.vb @@ -3,6 +3,7 @@ ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable +Imports Microsoft.CodeAnalysis.Collections Imports Microsoft.CodeAnalysis.EditAndContinue Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Syntax diff --git a/src/roslyn/src/Features/VisualBasic/Portable/EditAndContinue/DeclarationBody/PropertyWithNewClauseDeclarationBody.vb b/src/roslyn/src/Features/VisualBasic/Portable/EditAndContinue/DeclarationBody/PropertyWithNewClauseDeclarationBody.vb index 589d580d36f..3ba7e85ee85 100644 --- a/src/roslyn/src/Features/VisualBasic/Portable/EditAndContinue/DeclarationBody/PropertyWithNewClauseDeclarationBody.vb +++ b/src/roslyn/src/Features/VisualBasic/Portable/EditAndContinue/DeclarationBody/PropertyWithNewClauseDeclarationBody.vb @@ -2,6 +2,7 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. +Imports Microsoft.CodeAnalysis.Collections Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Syntax diff --git a/src/roslyn/src/Features/VisualBasic/Portable/EncapsulateField/VisualBasicEncapsulateFieldService.vb b/src/roslyn/src/Features/VisualBasic/Portable/EncapsulateField/VisualBasicEncapsulateFieldService.vb index 443cb7745a2..7c520134682 100644 --- a/src/roslyn/src/Features/VisualBasic/Portable/EncapsulateField/VisualBasicEncapsulateFieldService.vb +++ b/src/roslyn/src/Features/VisualBasic/Portable/EncapsulateField/VisualBasicEncapsulateFieldService.vb @@ -5,6 +5,7 @@ Imports System.Collections.Immutable Imports System.Composition Imports System.Threading +Imports Microsoft.CodeAnalysis.Collections Imports Microsoft.CodeAnalysis.EncapsulateField Imports Microsoft.CodeAnalysis.Formatting Imports Microsoft.CodeAnalysis.Host.Mef diff --git a/src/roslyn/src/Features/VisualBasic/Portable/ExtractMethod/VisualBasicMethodExtractor.PostProcessor.vb b/src/roslyn/src/Features/VisualBasic/Portable/ExtractMethod/VisualBasicMethodExtractor.PostProcessor.vb index a5b3c774caf..4eb3f20744f 100644 --- a/src/roslyn/src/Features/VisualBasic/Portable/ExtractMethod/VisualBasicMethodExtractor.PostProcessor.vb +++ b/src/roslyn/src/Features/VisualBasic/Portable/ExtractMethod/VisualBasicMethodExtractor.PostProcessor.vb @@ -4,6 +4,7 @@ Imports System.Collections.Immutable Imports Microsoft.CodeAnalysis +Imports Microsoft.CodeAnalysis.Collections Imports Microsoft.CodeAnalysis.VisualBasic Imports Microsoft.CodeAnalysis.VisualBasic.Syntax diff --git a/src/roslyn/src/Features/VisualBasic/Portable/ExtractMethod/VisualBasicMethodExtractor.TriviaResult.vb b/src/roslyn/src/Features/VisualBasic/Portable/ExtractMethod/VisualBasicMethodExtractor.TriviaResult.vb index c6368e296b3..13887b9b995 100644 --- a/src/roslyn/src/Features/VisualBasic/Portable/ExtractMethod/VisualBasicMethodExtractor.TriviaResult.vb +++ b/src/roslyn/src/Features/VisualBasic/Portable/ExtractMethod/VisualBasicMethodExtractor.TriviaResult.vb @@ -4,6 +4,7 @@ Imports System.Threading Imports Microsoft.CodeAnalysis +Imports Microsoft.CodeAnalysis.Collections Imports Microsoft.CodeAnalysis.ExtractMethod Imports Microsoft.CodeAnalysis.VisualBasic.Syntax diff --git a/src/roslyn/src/Features/VisualBasic/Portable/ExtractMethod/VisualBasicMethodExtractor.VisualBasicCodeGenerator.vb b/src/roslyn/src/Features/VisualBasic/Portable/ExtractMethod/VisualBasicMethodExtractor.VisualBasicCodeGenerator.vb index 42b161fc8c4..66980debb0b 100644 --- a/src/roslyn/src/Features/VisualBasic/Portable/ExtractMethod/VisualBasicMethodExtractor.VisualBasicCodeGenerator.vb +++ b/src/roslyn/src/Features/VisualBasic/Portable/ExtractMethod/VisualBasicMethodExtractor.VisualBasicCodeGenerator.vb @@ -6,6 +6,7 @@ Imports System.Collections.Immutable Imports System.Threading Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.CodeGeneration +Imports Microsoft.CodeAnalysis.Collections Imports Microsoft.CodeAnalysis.Editing Imports Microsoft.CodeAnalysis.ExtractMethod Imports Microsoft.CodeAnalysis.Formatting diff --git a/src/roslyn/src/Features/VisualBasic/Portable/NavigationBar/VisualBasicNavigationBarItemService.vb b/src/roslyn/src/Features/VisualBasic/Portable/NavigationBar/VisualBasicNavigationBarItemService.vb index 1302e602d6e..63c4c403370 100644 --- a/src/roslyn/src/Features/VisualBasic/Portable/NavigationBar/VisualBasicNavigationBarItemService.vb +++ b/src/roslyn/src/Features/VisualBasic/Portable/NavigationBar/VisualBasicNavigationBarItemService.vb @@ -6,6 +6,7 @@ Imports System.Collections.Immutable Imports System.Composition Imports System.Threading Imports Microsoft.CodeAnalysis +Imports Microsoft.CodeAnalysis.Collections Imports Microsoft.CodeAnalysis.ErrorReporting Imports Microsoft.CodeAnalysis.Host.Mef Imports Microsoft.CodeAnalysis.LanguageService diff --git a/src/roslyn/src/Features/VisualBasic/Portable/SignatureHelp/AbstractIntrinsicOperatorSignatureHelpProvider.vb b/src/roslyn/src/Features/VisualBasic/Portable/SignatureHelp/AbstractIntrinsicOperatorSignatureHelpProvider.vb index a3744fa7264..ed3d8826fd2 100644 --- a/src/roslyn/src/Features/VisualBasic/Portable/SignatureHelp/AbstractIntrinsicOperatorSignatureHelpProvider.vb +++ b/src/roslyn/src/Features/VisualBasic/Portable/SignatureHelp/AbstractIntrinsicOperatorSignatureHelpProvider.vb @@ -3,6 +3,7 @@ ' See the LICENSE file in the project root for more information. Imports System.Threading +Imports Microsoft.CodeAnalysis.Collections Imports Microsoft.CodeAnalysis.LanguageService Imports Microsoft.CodeAnalysis.SignatureHelp Imports Microsoft.CodeAnalysis.Text diff --git a/src/roslyn/src/Features/VisualBasic/Portable/SignatureHelp/AddRemoveHandlerSignatureHelpProvider.vb b/src/roslyn/src/Features/VisualBasic/Portable/SignatureHelp/AddRemoveHandlerSignatureHelpProvider.vb index 9372eb95254..f69f741736a 100644 --- a/src/roslyn/src/Features/VisualBasic/Portable/SignatureHelp/AddRemoveHandlerSignatureHelpProvider.vb +++ b/src/roslyn/src/Features/VisualBasic/Portable/SignatureHelp/AddRemoveHandlerSignatureHelpProvider.vb @@ -5,6 +5,7 @@ Imports System.Collections.Immutable Imports System.Composition Imports System.Threading +Imports Microsoft.CodeAnalysis.Collections Imports Microsoft.CodeAnalysis.Host.Mef Imports Microsoft.CodeAnalysis.SignatureHelp Imports Microsoft.CodeAnalysis.VisualBasic.Syntax diff --git a/src/roslyn/src/Features/VisualBasic/Portable/SignatureHelp/CastExpressionSignatureHelpProvider.vb b/src/roslyn/src/Features/VisualBasic/Portable/SignatureHelp/CastExpressionSignatureHelpProvider.vb index 86e9cac9f06..371fd846972 100644 --- a/src/roslyn/src/Features/VisualBasic/Portable/SignatureHelp/CastExpressionSignatureHelpProvider.vb +++ b/src/roslyn/src/Features/VisualBasic/Portable/SignatureHelp/CastExpressionSignatureHelpProvider.vb @@ -5,6 +5,7 @@ Imports System.Collections.Immutable Imports System.Composition Imports System.Threading +Imports Microsoft.CodeAnalysis.Collections Imports Microsoft.CodeAnalysis.Host.Mef Imports Microsoft.CodeAnalysis.SignatureHelp Imports Microsoft.CodeAnalysis.VisualBasic.Syntax diff --git a/src/roslyn/src/Features/VisualBasic/Portable/SignatureHelp/FunctionAggregationSignatureHelpProvider.vb b/src/roslyn/src/Features/VisualBasic/Portable/SignatureHelp/FunctionAggregationSignatureHelpProvider.vb index 320684f1ac6..f99edead13e 100644 --- a/src/roslyn/src/Features/VisualBasic/Portable/SignatureHelp/FunctionAggregationSignatureHelpProvider.vb +++ b/src/roslyn/src/Features/VisualBasic/Portable/SignatureHelp/FunctionAggregationSignatureHelpProvider.vb @@ -5,6 +5,7 @@ Imports System.Collections.Immutable Imports System.Composition Imports System.Threading +Imports Microsoft.CodeAnalysis.Collections Imports Microsoft.CodeAnalysis.DocumentationComments Imports Microsoft.CodeAnalysis.Host.Mef Imports Microsoft.CodeAnalysis.LanguageService diff --git a/src/roslyn/src/Features/VisualBasic/Portable/SignatureHelp/InvocationExpressionSignatureHelpProvider.DelegateInvoke.vb b/src/roslyn/src/Features/VisualBasic/Portable/SignatureHelp/InvocationExpressionSignatureHelpProvider.DelegateInvoke.vb index ad65a25624f..bb409778cc4 100644 --- a/src/roslyn/src/Features/VisualBasic/Portable/SignatureHelp/InvocationExpressionSignatureHelpProvider.DelegateInvoke.vb +++ b/src/roslyn/src/Features/VisualBasic/Portable/SignatureHelp/InvocationExpressionSignatureHelpProvider.DelegateInvoke.vb @@ -3,6 +3,7 @@ ' See the LICENSE file in the project root for more information. Imports System.Threading +Imports Microsoft.CodeAnalysis.Collections Imports Microsoft.CodeAnalysis.DocumentationComments Imports Microsoft.CodeAnalysis.LanguageService Imports Microsoft.CodeAnalysis.SignatureHelp diff --git a/src/roslyn/src/Features/VisualBasic/Portable/SignatureHelp/InvocationExpressionSignatureHelpProvider.ElementAccess.vb b/src/roslyn/src/Features/VisualBasic/Portable/SignatureHelp/InvocationExpressionSignatureHelpProvider.ElementAccess.vb index 68d7c384df2..3fc0bbf04f9 100644 --- a/src/roslyn/src/Features/VisualBasic/Portable/SignatureHelp/InvocationExpressionSignatureHelpProvider.ElementAccess.vb +++ b/src/roslyn/src/Features/VisualBasic/Portable/SignatureHelp/InvocationExpressionSignatureHelpProvider.ElementAccess.vb @@ -3,6 +3,7 @@ ' See the LICENSE file in the project root for more information. Imports System.Threading +Imports Microsoft.CodeAnalysis.Collections Imports Microsoft.CodeAnalysis.DocumentationComments Imports Microsoft.CodeAnalysis.LanguageService Imports Microsoft.CodeAnalysis.SignatureHelp diff --git a/src/roslyn/src/Features/VisualBasic/Portable/SignatureHelp/InvocationExpressionSignatureHelpProvider.MemberGroup.vb b/src/roslyn/src/Features/VisualBasic/Portable/SignatureHelp/InvocationExpressionSignatureHelpProvider.MemberGroup.vb index 2bf844ac129..d2059cb0f5f 100644 --- a/src/roslyn/src/Features/VisualBasic/Portable/SignatureHelp/InvocationExpressionSignatureHelpProvider.MemberGroup.vb +++ b/src/roslyn/src/Features/VisualBasic/Portable/SignatureHelp/InvocationExpressionSignatureHelpProvider.MemberGroup.vb @@ -4,6 +4,7 @@ Imports System.Collections.Immutable Imports System.Threading +Imports Microsoft.CodeAnalysis.Collections Imports Microsoft.CodeAnalysis.SignatureHelp Imports Microsoft.CodeAnalysis.VisualBasic.Syntax diff --git a/src/roslyn/src/Features/VisualBasic/Portable/SignatureHelp/InvocationExpressionSignatureHelpProvider.vb b/src/roslyn/src/Features/VisualBasic/Portable/SignatureHelp/InvocationExpressionSignatureHelpProvider.vb index ec19c6c3e70..4d223d56bf7 100644 --- a/src/roslyn/src/Features/VisualBasic/Portable/SignatureHelp/InvocationExpressionSignatureHelpProvider.vb +++ b/src/roslyn/src/Features/VisualBasic/Portable/SignatureHelp/InvocationExpressionSignatureHelpProvider.vb @@ -5,6 +5,7 @@ Imports System.Collections.Immutable Imports System.Composition Imports System.Threading +Imports Microsoft.CodeAnalysis.Collections Imports Microsoft.CodeAnalysis.DocumentationComments Imports Microsoft.CodeAnalysis.Host.Mef Imports Microsoft.CodeAnalysis.LanguageService diff --git a/src/roslyn/src/Features/VisualBasic/Portable/SignatureHelp/ObjectCreationExpressionSignatureHelpProvider.DelegateType.vb b/src/roslyn/src/Features/VisualBasic/Portable/SignatureHelp/ObjectCreationExpressionSignatureHelpProvider.DelegateType.vb index d64c2015504..8936e239cec 100644 --- a/src/roslyn/src/Features/VisualBasic/Portable/SignatureHelp/ObjectCreationExpressionSignatureHelpProvider.DelegateType.vb +++ b/src/roslyn/src/Features/VisualBasic/Portable/SignatureHelp/ObjectCreationExpressionSignatureHelpProvider.DelegateType.vb @@ -2,6 +2,7 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. +Imports Microsoft.CodeAnalysis.Collections Imports Microsoft.CodeAnalysis.DocumentationComments Imports Microsoft.CodeAnalysis.LanguageService Imports Microsoft.CodeAnalysis.SignatureHelp diff --git a/src/roslyn/src/Features/VisualBasic/Portable/SignatureHelp/PredefinedCastExpressionSignatureHelpProvider.vb b/src/roslyn/src/Features/VisualBasic/Portable/SignatureHelp/PredefinedCastExpressionSignatureHelpProvider.vb index db75a461e73..6cb0d0aef86 100644 --- a/src/roslyn/src/Features/VisualBasic/Portable/SignatureHelp/PredefinedCastExpressionSignatureHelpProvider.vb +++ b/src/roslyn/src/Features/VisualBasic/Portable/SignatureHelp/PredefinedCastExpressionSignatureHelpProvider.vb @@ -5,6 +5,7 @@ Imports System.Collections.Immutable Imports System.Composition Imports System.Threading +Imports Microsoft.CodeAnalysis.Collections Imports Microsoft.CodeAnalysis.Host.Mef Imports Microsoft.CodeAnalysis.SignatureHelp Imports Microsoft.CodeAnalysis.VisualBasic.Syntax diff --git a/src/roslyn/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer.UnitTests/TelemetryReporterTests.cs b/src/roslyn/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer.UnitTests/TelemetryReporterTests.cs index 0a678d0b4fd..da5b1fadccb 100644 --- a/src/roslyn/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer.UnitTests/TelemetryReporterTests.cs +++ b/src/roslyn/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer.UnitTests/TelemetryReporterTests.cs @@ -14,13 +14,11 @@ public sealed class TelemetryReporterTests(ITestOutputHelper testOutputHelper) { private async Task CreateReporterAsync() { - var exportProvider = await LanguageServerTestComposition.CreateExportProviderAsync( + var (exportProvider, _) = await LanguageServerTestComposition.CreateExportProviderAsync( LoggerFactory, includeDevKitComponents: true, MefCacheDirectory.Path, - [], - out var _, - out var _); + []); // VS Telemetry requires this environment variable to be set. Environment.SetEnvironmentVariable("CommonPropertyBagPath", Path.GetTempFileName()); diff --git a/src/roslyn/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer.UnitTests/Utilities/AbstractLanguageServerHostTests.cs b/src/roslyn/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer.UnitTests/Utilities/AbstractLanguageServerHostTests.cs index 56583026440..7d6f5476c8c 100644 --- a/src/roslyn/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer.UnitTests/Utilities/AbstractLanguageServerHostTests.cs +++ b/src/roslyn/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer.UnitTests/Utilities/AbstractLanguageServerHostTests.cs @@ -46,8 +46,8 @@ protected sealed class TestLspServer : ILspClient, IAsyncDisposable internal static async Task CreateAsync(ClientCapabilities clientCapabilities, ILoggerFactory loggerFactory, string cacheDirectory, bool includeDevKitComponents = true, string[]? extensionPaths = null) { - var exportProvider = await LanguageServerTestComposition.CreateExportProviderAsync( - loggerFactory, includeDevKitComponents, cacheDirectory, extensionPaths, out var _, out var assemblyLoader); + var (exportProvider, assemblyLoader) = await LanguageServerTestComposition.CreateExportProviderAsync( + loggerFactory, includeDevKitComponents, cacheDirectory, extensionPaths); var testLspServer = new TestLspServer(exportProvider, loggerFactory, assemblyLoader); var initializeResponse = await testLspServer.ExecuteRequestAsync(Methods.InitializeName, new InitializeParams { Capabilities = clientCapabilities }, CancellationToken.None); Assert.NotNull(initializeResponse?.Capabilities); diff --git a/src/roslyn/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer.UnitTests/Utilities/LanguageServerTestComposition.cs b/src/roslyn/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer.UnitTests/Utilities/LanguageServerTestComposition.cs index 9215dfc08b8..54e01719766 100644 --- a/src/roslyn/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer.UnitTests/Utilities/LanguageServerTestComposition.cs +++ b/src/roslyn/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer.UnitTests/Utilities/LanguageServerTestComposition.cs @@ -10,16 +10,14 @@ namespace Microsoft.CodeAnalysis.LanguageServer.UnitTests; internal sealed class LanguageServerTestComposition { - public static Task CreateExportProviderAsync( + public static async Task<(ExportProvider exportProvider, IAssemblyLoader assemblyLoader)> CreateExportProviderAsync( ILoggerFactory loggerFactory, bool includeDevKitComponents, string cacheDirectory, - string[]? extensionPaths, - out ServerConfiguration serverConfiguration, - out IAssemblyLoader assemblyLoader) + string[]? extensionPaths) { var devKitDependencyPath = includeDevKitComponents ? TestPaths.GetDevKitExtensionPath() : null; - serverConfiguration = new ServerConfiguration(LaunchDebugger: false, + var serverConfiguration = new ServerConfiguration(LaunchDebugger: false, LogConfiguration: new LogConfiguration(LogLevel.Trace), StarredCompletionsPath: null, TelemetryLevel: null, @@ -32,8 +30,10 @@ public static Task CreateExportProviderAsync( ServerPipeName: null, UseStdIo: false); var extensionManager = ExtensionAssemblyManager.Create(serverConfiguration, loggerFactory); - assemblyLoader = new CustomExportAssemblyLoader(extensionManager, loggerFactory); + var assemblyLoader = new CustomExportAssemblyLoader(extensionManager, loggerFactory); - return LanguageServerExportProviderBuilder.CreateExportProviderAsync(extensionManager, assemblyLoader, devKitDependencyPath, cacheDirectory, loggerFactory, CancellationToken.None); + var exportProvider = await LanguageServerExportProviderBuilder.CreateExportProviderAsync(extensionManager, assemblyLoader, devKitDependencyPath, cacheDirectory, loggerFactory, CancellationToken.None); + exportProvider.GetExportedValue().InitializeConfiguration(serverConfiguration); + return (exportProvider, assemblyLoader); } } diff --git a/src/roslyn/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer.UnitTests/WorkspaceProjectFactoryServiceTests.cs b/src/roslyn/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer.UnitTests/WorkspaceProjectFactoryServiceTests.cs index b5082c97af3..5b1a75909dc 100644 --- a/src/roslyn/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer.UnitTests/WorkspaceProjectFactoryServiceTests.cs +++ b/src/roslyn/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer.UnitTests/WorkspaceProjectFactoryServiceTests.cs @@ -18,11 +18,10 @@ public sealed class WorkspaceProjectFactoryServiceTests(ITestOutputHelper testOu public async Task CreateProjectAndBatch() { var loggerFactory = new LoggerFactory(); - using var exportProvider = await LanguageServerTestComposition.CreateExportProviderAsync( - loggerFactory, includeDevKitComponents: false, MefCacheDirectory.Path, [], out var serverConfiguration, out var _); + var (exportProvider, _) = await LanguageServerTestComposition.CreateExportProviderAsync( + loggerFactory, includeDevKitComponents: false, MefCacheDirectory.Path, []); + using var _ = exportProvider; - exportProvider.GetExportedValue() - .InitializeConfiguration(serverConfiguration); await exportProvider.GetExportedValue().CreateAsync(); var workspaceFactory = exportProvider.GetExportedValue(); @@ -48,7 +47,7 @@ public async Task CreateProjectAndBatch() await batch.ApplyAsync(CancellationToken.None); // Verify it actually did something; we won't exclusively test each method since those are tested at lower layers - var project = workspaceFactory.Workspace.CurrentSolution.Projects.Single(); + var project = workspaceFactory.HostWorkspace.CurrentSolution.Projects.Single(); var document = Assert.Single(project.Documents); Assert.Equal(sourceFilePath, document.FilePath); diff --git a/src/roslyn/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer/HostWorkspace/FileBasedProgramsProjectSystem.cs b/src/roslyn/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer/HostWorkspace/FileBasedProgramsProjectSystem.cs new file mode 100644 index 00000000000..4b229d8497a --- /dev/null +++ b/src/roslyn/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer/HostWorkspace/FileBasedProgramsProjectSystem.cs @@ -0,0 +1,143 @@ +// 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; +using System.Security; +using Microsoft.CodeAnalysis.Features.Workspaces; +using Microsoft.CodeAnalysis.Host; +using Microsoft.CodeAnalysis.LanguageServer.HostWorkspace.ProjectTelemetry; +using Microsoft.CodeAnalysis.MetadataAsSource; +using Microsoft.CodeAnalysis.MSBuild; +using Microsoft.CodeAnalysis.Options; +using Microsoft.CodeAnalysis.ProjectSystem; +using Microsoft.CodeAnalysis.Shared.Extensions; +using Microsoft.CodeAnalysis.Shared.TestHooks; +using Microsoft.CodeAnalysis.Text; +using Microsoft.CodeAnalysis.Workspaces.ProjectSystem; +using Microsoft.CommonLanguageServerProtocol.Framework; +using Microsoft.Extensions.Logging; +using Microsoft.VisualStudio.Composition; +using Roslyn.LanguageServer.Protocol; +using Roslyn.Utilities; +using static Microsoft.CodeAnalysis.MSBuild.BuildHostProcessManager; + +namespace Microsoft.CodeAnalysis.LanguageServer.HostWorkspace; + +/// Handles loading both miscellaneous files and file-based program projects. +internal sealed class FileBasedProgramsProjectSystem : LanguageServerProjectLoader, ILspMiscellaneousFilesWorkspaceProvider +{ + private readonly ILspServices _lspServices; + private readonly ILogger _logger; + private readonly IMetadataAsSourceFileService _metadataAsSourceFileService; + + public FileBasedProgramsProjectSystem( + ILspServices lspServices, + IMetadataAsSourceFileService metadataAsSourceFileService, + LanguageServerWorkspaceFactory workspaceFactory, + IFileChangeWatcher fileChangeWatcher, + IGlobalOptionService globalOptionService, + ILoggerFactory loggerFactory, + IAsynchronousOperationListenerProvider listenerProvider, + ProjectLoadTelemetryReporter projectLoadTelemetry, + ServerConfigurationFactory serverConfigurationFactory, + BinlogNamer binlogNamer) + : base( + workspaceFactory.FileBasedProgramsProjectFactory, + workspaceFactory.TargetFrameworkManager, + workspaceFactory.ProjectSystemHostInfo, + fileChangeWatcher, + globalOptionService, + loggerFactory, + listenerProvider, + projectLoadTelemetry, + serverConfigurationFactory, + binlogNamer) + { + _lspServices = lspServices; + _logger = loggerFactory.CreateLogger(); + _metadataAsSourceFileService = metadataAsSourceFileService; + } + + public Workspace Workspace => ProjectFactory.Workspace; + + private string GetDocumentFilePath(DocumentUri uri) => uri.ParsedUri is { } parsedUri ? ProtocolConversions.GetDocumentFilePathFromUri(parsedUri) : uri.UriString; + + public async ValueTask AddMiscellaneousDocumentAsync(DocumentUri uri, SourceText documentText, string languageId, ILspLogger logger) + { + var documentFilePath = GetDocumentFilePath(uri); + + // https://github.com/dotnet/roslyn/issues/78421: MetadataAsSource should be its own workspace + if (_metadataAsSourceFileService.TryAddDocumentToWorkspace(documentFilePath, documentText.Container, out var documentId)) + { + var metadataWorkspace = _metadataAsSourceFileService.TryGetWorkspace(); + Contract.ThrowIfNull(metadataWorkspace); + return metadataWorkspace.CurrentSolution.GetRequiredDocument(documentId); + } + + var primordialDoc = AddPrimordialDocument(uri, documentText, languageId); + Contract.ThrowIfNull(primordialDoc.FilePath); + + var doDesignTimeBuild = uri.ParsedUri?.IsFile is true + && primordialDoc.Project.Language == LanguageNames.CSharp + && GlobalOptionService.GetOption(LanguageServerProjectSystemOptionsStorage.EnableFileBasedPrograms); + await BeginLoadingProjectWithPrimordialAsync(primordialDoc.FilePath, primordialProjectId: primordialDoc.Project.Id, doDesignTimeBuild); + + return primordialDoc; + + TextDocument AddPrimordialDocument(DocumentUri uri, SourceText documentText, string languageId) + { + var languageInfoProvider = _lspServices.GetRequiredService(); + if (!languageInfoProvider.TryGetLanguageInformation(uri, languageId, out var languageInformation)) + { + Contract.Fail($"Could not find language information for {uri} with absolute path {documentFilePath}"); + } + + var workspace = Workspace; + var sourceTextLoader = new SourceTextLoader(documentText, documentFilePath); + var projectInfo = MiscellaneousFileUtilities.CreateMiscellaneousProjectInfoForDocument( + workspace, documentFilePath, sourceTextLoader, languageInformation, documentText.ChecksumAlgorithm, workspace.Services.SolutionServices, []); + + ProjectFactory.ApplyChangeToWorkspace(workspace => workspace.OnProjectAdded(projectInfo)); + + // https://github.com/dotnet/roslyn/pull/78267 + // Work around an issue where opening a Razor file in the misc workspace causes a crash. + if (languageInformation.LanguageName == LanguageInfoProvider.RazorLanguageName) + { + var docId = projectInfo.AdditionalDocuments.Single().Id; + return workspace.CurrentSolution.GetRequiredAdditionalDocument(docId); + } + + var id = projectInfo.Documents.Single().Id; + return workspace.CurrentSolution.GetRequiredDocument(id); + } + } + + public async ValueTask TryRemoveMiscellaneousDocumentAsync(DocumentUri uri, bool removeFromMetadataWorkspace) + { + var documentPath = GetDocumentFilePath(uri); + if (removeFromMetadataWorkspace && _metadataAsSourceFileService.TryRemoveDocumentFromWorkspace(documentPath)) + { + return; + } + + await UnloadProjectAsync(documentPath); + } + + protected override async Task<(RemoteProjectFile projectFile, bool hasAllInformation, BuildHostProcessKind preferred, BuildHostProcessKind actual)?> TryLoadProjectInMSBuildHostAsync( + BuildHostProcessManager buildHostProcessManager, string documentPath, CancellationToken cancellationToken) + { + const BuildHostProcessKind buildHostKind = BuildHostProcessKind.NetCore; + var buildHost = await buildHostProcessManager.GetBuildHostAsync(buildHostKind, cancellationToken); + + var loader = ProjectFactory.CreateFileTextLoader(documentPath); + var textAndVersion = await loader.LoadTextAsync(new LoadTextOptions(SourceHashAlgorithms.Default), cancellationToken); + var (virtualProjectContent, isFileBasedProgram) = VirtualCSharpFileBasedProgramProject.MakeVirtualProjectContent(documentPath, textAndVersion.Text); + + // When loading a virtual project, the path to the on-disk source file is not used. Instead the path is adjusted to end with .csproj. + // This is necessary in order to get msbuild to apply the standard c# props/targets to the project. + var virtualProjectPath = VirtualCSharpFileBasedProgramProject.GetVirtualProjectPath(documentPath); + var loadedFile = await buildHost.LoadProjectAsync(virtualProjectPath, virtualProjectContent, languageName: LanguageNames.CSharp, cancellationToken); + return (loadedFile, hasAllInformation: isFileBasedProgram, preferred: buildHostKind, actual: buildHostKind); + } +} diff --git a/src/roslyn/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer/HostWorkspace/FileBasedProgramsWorkspaceProviderFactory.cs b/src/roslyn/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer/HostWorkspace/FileBasedProgramsWorkspaceProviderFactory.cs new file mode 100644 index 00000000000..d7c63e9f2ae --- /dev/null +++ b/src/roslyn/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer/HostWorkspace/FileBasedProgramsWorkspaceProviderFactory.cs @@ -0,0 +1,42 @@ +// 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.Composition; +using Microsoft.CodeAnalysis.Host; +using Microsoft.CodeAnalysis.Host.Mef; +using Microsoft.CodeAnalysis.LanguageServer.Handler; +using Microsoft.CodeAnalysis.LanguageServer.HostWorkspace.ProjectTelemetry; +using Microsoft.CodeAnalysis.MetadataAsSource; +using Microsoft.CodeAnalysis.Options; +using Microsoft.CodeAnalysis.ProjectSystem; +using Microsoft.CodeAnalysis.Shared.TestHooks; +using Microsoft.CommonLanguageServerProtocol.Framework; +using Microsoft.Extensions.Logging; + +namespace Microsoft.CodeAnalysis.LanguageServer.HostWorkspace; + +/// +/// Service to create instances. +/// This is not exported as a as it requires +/// special base language server dependencies such as the +/// +[ExportCSharpVisualBasicStatelessLspService(typeof(ILspMiscellaneousFilesWorkspaceProviderFactory), WellKnownLspServerKinds.CSharpVisualBasicLspServer), Shared] +[method: ImportingConstructor] +[method: Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] +internal sealed class FileBasedProgramsWorkspaceProviderFactory( + IMetadataAsSourceFileService metadataAsSourceFileService, + LanguageServerWorkspaceFactory workspaceFactory, + IFileChangeWatcher fileChangeWatcher, + IGlobalOptionService globalOptionService, + ILoggerFactory loggerFactory, + IAsynchronousOperationListenerProvider listenerProvider, + ProjectLoadTelemetryReporter projectLoadTelemetry, + ServerConfigurationFactory serverConfigurationFactory, + BinlogNamer binlogNamer) : ILspMiscellaneousFilesWorkspaceProviderFactory +{ + public ILspMiscellaneousFilesWorkspaceProvider CreateLspMiscellaneousFilesWorkspaceProvider(ILspServices lspServices, HostServices hostServices) + { + return new FileBasedProgramsProjectSystem(lspServices, metadataAsSourceFileService, workspaceFactory, fileChangeWatcher, globalOptionService, loggerFactory, listenerProvider, projectLoadTelemetry, serverConfigurationFactory, binlogNamer); + } +} diff --git a/src/roslyn/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer/HostWorkspace/LanguageServerProjectLoader.cs b/src/roslyn/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer/HostWorkspace/LanguageServerProjectLoader.cs index 56d127d86d7..d97745c2edb 100644 --- a/src/roslyn/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer/HostWorkspace/LanguageServerProjectLoader.cs +++ b/src/roslyn/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer/HostWorkspace/LanguageServerProjectLoader.cs @@ -4,23 +4,27 @@ using System.Collections.Concurrent; using System.Collections.Immutable; -using System.Composition; using System.Diagnostics; -using System.Runtime.InteropServices; +using System.IO; +using System.Threading; +using System.Threading.Tasks; using Microsoft.CodeAnalysis.Collections; +using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.Host; -using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.LanguageServer.Handler.DebugConfiguration; using Microsoft.CodeAnalysis.LanguageServer.HostWorkspace.ProjectTelemetry; using Microsoft.CodeAnalysis.MSBuild; using Microsoft.CodeAnalysis.Options; +using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.ProjectSystem; +using Microsoft.CodeAnalysis.Shared.Collections; +using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.CodeAnalysis.Shared.Utilities; +using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.Threading; using Microsoft.CodeAnalysis.Workspaces.ProjectSystem; using Microsoft.Extensions.Logging; -using Microsoft.VisualStudio.Composition; using Roslyn.Utilities; using static Microsoft.CodeAnalysis.MSBuild.BuildHostProcessManager; using LSP = Roslyn.LanguageServer.Protocol; @@ -29,27 +33,60 @@ namespace Microsoft.CodeAnalysis.LanguageServer.HostWorkspace; internal abstract class LanguageServerProjectLoader { - protected readonly AsyncBatchingWorkQueue ProjectsToLoadAndReload; + private readonly AsyncBatchingWorkQueue _projectsToReload; protected readonly ProjectSystemProjectFactory ProjectFactory; private readonly ProjectTargetFrameworkManager _targetFrameworkManager; private readonly ProjectSystemHostInfo _projectSystemHostInfo; private readonly IFileChangeWatcher _fileChangeWatcher; - private readonly IGlobalOptionService _globalOptionService; + protected readonly IGlobalOptionService GlobalOptionService; protected readonly ILoggerFactory LoggerFactory; private readonly ILogger _logger; private readonly ProjectLoadTelemetryReporter _projectLoadTelemetryReporter; private readonly BinlogNamer _binlogNamer; - private readonly ProjectFileExtensionRegistry _projectFileExtensionRegistry; protected readonly ImmutableDictionary AdditionalProperties; /// - /// The list of loaded projects in the workspace, keyed by project file path. The outer dictionary is a concurrent dictionary since we may be loading - /// multiple projects at once; the key is a single List we just have a single thread processing any given project file. This is only to be used - /// in and downstream calls; any other updating of this (like unloading projects) should be achieved by adding - /// things to the . + /// Guards access to . + /// To keep the LSP queue responsive, must not be held while performing design-time builds. /// - private readonly ConcurrentDictionary> _loadedProjects = []; + private readonly SemaphoreSlim _gate = new(initialCount: 1); + + /// + /// Maps the file path of a tracked project to the load state for the project. + /// Absence of an entry indicates the project is not tracked, e.g. it was never loaded, or it was unloaded. + /// must be held when modifying the dictionary or objects contained in it. + /// + private readonly Dictionary _loadedProjects = []; + + /// + /// State transitions: + /// -> + /// Any state -> unloaded (which is denoted by removing the entry for the project) + /// + private abstract record ProjectLoadState + { + private ProjectLoadState() { } + + /// + /// Represents a project which has not yet had a design-time build performed for it, + /// and which has an associated "primordial project" in the workspace. + /// + /// + /// ID of the project which LSP uses to fulfill requests until the first design-time build is complete. + /// The project with this ID is removed from the workspace when unloading or when transitioning to state. + /// + public sealed record Primordial(ProjectId PrimordialProjectId) : ProjectLoadState; + + /// + /// Represents a project for which we have loaded zero or more targets. + /// Generally a project which has zero loaded targets has not had a design-time build completed for it yet. + /// Incrementally updated upon subsequent design-time builds. + /// The are disposed when unloading. + /// + /// List of target frameworks which have been loaded for this project so far. + public sealed record LoadedTargets(ImmutableArray LoadedProjectTargets) : ProjectLoadState; + } protected LanguageServerProjectLoader( ProjectSystemProjectFactory projectFactory, @@ -67,22 +104,21 @@ protected LanguageServerProjectLoader( _targetFrameworkManager = targetFrameworkManager; _projectSystemHostInfo = projectSystemHostInfo; _fileChangeWatcher = fileChangeWatcher; - _globalOptionService = globalOptionService; + GlobalOptionService = globalOptionService; LoggerFactory = loggerFactory; _logger = loggerFactory.CreateLogger(nameof(LanguageServerProjectLoader)); _projectLoadTelemetryReporter = projectLoadTelemetry; _binlogNamer = binlogNamer; var workspace = projectFactory.Workspace; - _projectFileExtensionRegistry = new ProjectFileExtensionRegistry(workspace.CurrentSolution.Services, new DiagnosticReporter(workspace)); var razorDesignTimePath = serverConfigurationFactory.ServerConfiguration?.RazorDesignTimePath; AdditionalProperties = razorDesignTimePath is null ? ImmutableDictionary.Empty : ImmutableDictionary.Empty.Add("RazorDesignTimeTargets", razorDesignTimePath); - ProjectsToLoadAndReload = new AsyncBatchingWorkQueue( + _projectsToReload = new AsyncBatchingWorkQueue( TimeSpan.FromMilliseconds(100), - LoadOrReloadProjectsAsync, + ReloadProjectsAsync, ProjectToLoad.Comparer, listenerProvider.GetListener(FeatureAttribute.Workspace), CancellationToken.None); // TODO: do we need to introduce a shutdown cancellation token for this? @@ -103,7 +139,7 @@ public async Task ReportErrorAsync(LSP.MessageType errorKind, string message, Ca } } - private async ValueTask LoadOrReloadProjectsAsync(ImmutableSegmentedList projectPathsToLoadOrReload, CancellationToken cancellationToken) + private async ValueTask ReloadProjectsAsync(ImmutableSegmentedList projectPathsToLoadOrReload, CancellationToken cancellationToken) { var stopwatch = Stopwatch.StartNew(); @@ -121,7 +157,7 @@ private async ValueTask LoadOrReloadProjectsAsync(ImmutableSegmentedList { var (@this, toastErrorReporter, buildHostProcessManager) = args; - var projectNeedsRestore = await @this.LoadOrReloadProjectAsync( + var projectNeedsRestore = await @this.ReloadProjectAsync( projectToLoad, toastErrorReporter, buildHostProcessManager, cancellationToken); if (projectNeedsRestore) @@ -130,7 +166,7 @@ private async ValueTask LoadOrReloadProjectsAsync(ImmutableSegmentedListLoads a project in the MSBuild host. + /// Caller needs to catch exceptions to avoid bringing down the project loader queue. + protected abstract Task<(RemoteProjectFile projectFile, bool hasAllInformation, BuildHostProcessKind preferred, BuildHostProcessKind actual)?> TryLoadProjectInMSBuildHostAsync( + BuildHostProcessManager buildHostProcessManager, string projectPath, CancellationToken cancellationToken); + /// True if the project needs a NuGet restore, false otherwise. - private async Task LoadOrReloadProjectAsync(ProjectToLoad projectToLoad, ToastErrorReporter toastErrorReporter, BuildHostProcessManager buildHostProcessManager, CancellationToken cancellationToken) + private async Task ReloadProjectAsync(ProjectToLoad projectToLoad, ToastErrorReporter toastErrorReporter, BuildHostProcessManager buildHostProcessManager, CancellationToken cancellationToken) { BuildHostProcessKind? preferredBuildHostKindThatWeDidNotGet = null; var projectPath = projectToLoad.Path; + Contract.ThrowIfFalse(PathUtilities.IsAbsolute(projectPath)); + + // Before doing any work, check if the project has already been unloaded. + using (await _gate.DisposableWaitAsync(cancellationToken)) + { + if (!_loadedProjects.ContainsKey(projectPath)) + { + return false; + } + } try { - var preferredBuildHostKind = GetKindForProject(projectPath); - var (buildHost, actualBuildHostKind) = await buildHostProcessManager.GetBuildHostWithFallbackAsync(preferredBuildHostKind, projectPath, cancellationToken); + if (await TryLoadProjectInMSBuildHostAsync(buildHostProcessManager, projectPath, cancellationToken) + is not var (remoteProjectFile, hasAllInformation, preferredBuildHostKind, actualBuildHostKind)) + { + _logger.LogWarning($"Unable to load project '{projectPath}'."); + return false; + } + if (preferredBuildHostKind != actualBuildHostKind) preferredBuildHostKindThatWeDidNotGet = preferredBuildHostKind; - if (!_projectFileExtensionRegistry.TryGetLanguageNameFromProjectPath(projectPath, DiagnosticReportingMode.Ignore, out var languageName)) - return false; - - var loadedFile = await buildHost.LoadProjectFileAsync(projectPath, languageName, cancellationToken); - var diagnosticLogItems = await loadedFile.GetDiagnosticLogItemsAsync(cancellationToken); + var diagnosticLogItems = await remoteProjectFile.GetDiagnosticLogItemsAsync(cancellationToken); if (diagnosticLogItems.Any(item => item.Kind is DiagnosticLogItemKind.Error)) { await LogDiagnosticsAsync(diagnosticLogItems); @@ -171,7 +223,7 @@ private async Task LoadOrReloadProjectAsync(ProjectToLoad projectToLoad, T return false; } - var loadedProjectInfos = await loadedFile.GetProjectFileInfosAsync(cancellationToken); + var loadedProjectInfos = await remoteProjectFile.GetProjectFileInfosAsync(cancellationToken); // The out-of-proc build host supports more languages than we may actually have Workspace binaries for, so ensure we can actually process that // language in-process. @@ -181,55 +233,65 @@ private async Task LoadOrReloadProjectAsync(ProjectToLoad projectToLoad, T return false; } - var existingProjects = _loadedProjects.GetOrAdd(projectPath, static _ => []); - Dictionary telemetryInfos = []; var needsRestore = false; - foreach (var loadedProjectInfo in loadedProjectInfos) + using (await _gate.DisposableWaitAsync(cancellationToken)) { - // If we already have the project with this same target framework, just update it - var existingProject = existingProjects.Find(p => p.GetTargetFramework() == loadedProjectInfo.TargetFramework); - bool targetNeedsRestore; - ProjectLoadTelemetryReporter.TelemetryInfo targetTelemetryInfo; - - if (existingProject != null) + if (!_loadedProjects.TryGetValue(projectPath, out var currentLoadState)) { - (targetTelemetryInfo, targetNeedsRestore) = await existingProject.UpdateWithNewProjectInfoAsync(loadedProjectInfo, _logger); + // Project was unloaded. Do not proceed with reloading it. + return false; } - else + + var previousProjectTargets = currentLoadState is ProjectLoadState.LoadedTargets loaded ? loaded.LoadedProjectTargets : []; + var newProjectTargetsBuilder = ArrayBuilder.GetInstance(loadedProjectInfos.Length); + foreach (var loadedProjectInfo in loadedProjectInfos) { - var projectSystemName = $"{projectPath} (${loadedProjectInfo.TargetFramework})"; - var projectCreationInfo = new ProjectSystemProjectCreationInfo - { - AssemblyName = projectSystemName, - FilePath = projectPath, - CompilationOutputAssemblyFilePath = loadedProjectInfo.IntermediateOutputFilePath - }; + var (target, targetAlreadyExists) = await GetOrCreateProjectTargetAsync(previousProjectTargets, loadedProjectInfo); + newProjectTargetsBuilder.Add(target); - var projectSystemProject = await ProjectFactory.CreateAndAddToWorkspaceAsync( - projectSystemName, - loadedProjectInfo.Language, - projectCreationInfo, - _projectSystemHostInfo); + if (targetAlreadyExists) + { + // https://github.com/dotnet/roslyn/issues/78561: Automatic restore should run even when the target is already loaded + _ = await target.UpdateWithNewProjectInfoAsync(loadedProjectInfo, hasAllInformation, _logger); + } + else + { + var (targetTelemetryInfo, targetNeedsRestore) = await target.UpdateWithNewProjectInfoAsync(loadedProjectInfo, hasAllInformation, _logger); + needsRestore |= targetNeedsRestore; + telemetryInfos[loadedProjectInfo] = targetTelemetryInfo with { IsSdkStyle = preferredBuildHostKind == BuildHostProcessKind.NetCore }; + } + } - var loadedProject = new LoadedProject(projectSystemProject, ProjectFactory.Workspace.Services.SolutionServices, _fileChangeWatcher, _targetFrameworkManager); - loadedProject.NeedsReload += (_, _) => ProjectsToLoadAndReload.AddWork(projectToLoad with { ReportTelemetry = false }); - existingProjects.Add(loadedProject); + var newProjectTargets = newProjectTargetsBuilder.ToImmutableAndFree(); + foreach (var target in previousProjectTargets) + { + // Unload targets which were present in a past design-time build, but absent in the current one. + if (!newProjectTargets.Contains(target)) + { + target.Dispose(); + } + } - (targetTelemetryInfo, targetNeedsRestore) = await loadedProject.UpdateWithNewProjectInfoAsync(loadedProjectInfo, _logger); + if (projectToLoad.ReportTelemetry) + { + await _projectLoadTelemetryReporter.ReportProjectLoadTelemetryAsync(telemetryInfos, projectToLoad, cancellationToken); + } - needsRestore |= targetNeedsRestore; - telemetryInfos[loadedProjectInfo] = targetTelemetryInfo with { IsSdkStyle = preferredBuildHostKind == BuildHostProcessKind.NetCore }; + if (currentLoadState is ProjectLoadState.Primordial(var projectId)) + { + // Remove the primordial project now that the design-time build pass is finished. This ensures that + // we have the new project in place before we remove the primordial project; otherwise for + // Miscellaneous Files we could have a case where we'd get another request to create a project + // for the project we're currently processing. + await ProjectFactory.ApplyChangeToWorkspaceAsync(workspace => workspace.OnProjectRemoved(projectId), cancellationToken); } - } - if (projectToLoad.ReportTelemetry) - { - await _projectLoadTelemetryReporter.ReportProjectLoadTelemetryAsync(telemetryInfos, projectToLoad, cancellationToken); + _loadedProjects[projectPath] = new ProjectLoadState.LoadedTargets(newProjectTargets); } - diagnosticLogItems = await loadedFile.GetDiagnosticLogItemsAsync(cancellationToken); + diagnosticLogItems = await remoteProjectFile.GetDiagnosticLogItemsAsync(cancellationToken); if (diagnosticLogItems.Any()) { await LogDiagnosticsAsync(diagnosticLogItems); @@ -251,6 +313,35 @@ private async Task LoadOrReloadProjectAsync(ProjectToLoad projectToLoad, T return false; } + async Task<(LoadedProject, bool alreadyExists)> GetOrCreateProjectTargetAsync(ImmutableArray previousProjectTargets, ProjectFileInfo loadedProjectInfo) + { + var existingProject = previousProjectTargets.FirstOrDefault(p => p.GetTargetFramework() == loadedProjectInfo.TargetFramework); + if (existingProject != null) + { + return (existingProject, alreadyExists: true); + } + + var targetFramework = loadedProjectInfo.TargetFramework; + var projectSystemName = targetFramework is null ? projectPath : $"{projectPath} (${targetFramework})"; + + var projectCreationInfo = new ProjectSystemProjectCreationInfo + { + AssemblyName = projectSystemName, + FilePath = projectPath, + CompilationOutputAssemblyFilePath = loadedProjectInfo.IntermediateOutputFilePath, + }; + + var projectSystemProject = await ProjectFactory.CreateAndAddToWorkspaceAsync( + projectSystemName, + loadedProjectInfo.Language, + projectCreationInfo, + _projectSystemHostInfo); + + var loadedProject = new LoadedProject(projectSystemProject, ProjectFactory.Workspace.Services.SolutionServices, _fileChangeWatcher, _targetFrameworkManager); + loadedProject.NeedsReload += (_, _) => _projectsToReload.AddWork(projectToLoad with { ReportTelemetry = false }); + return (loadedProject, alreadyExists: false); + } + async Task LogDiagnosticsAsync(ImmutableArray diagnosticLogItems) { foreach (var logItem in diagnosticLogItems) @@ -273,4 +364,81 @@ async Task LogDiagnosticsAsync(ImmutableArray diagnosticLogIt await toastErrorReporter.ReportErrorAsync(worstLspMessageKind, message, cancellationToken); } } + + /// + /// Begins loading a project with an associated primordial project. Must not be called for a project which has already begun loading. + /// + /// + /// If , initiates a design-time build now, and starts file watchers to repeat the design-time build on relevant changes. + /// If , only tracks the primordial project. + /// + protected async ValueTask BeginLoadingProjectWithPrimordialAsync(string projectPath, ProjectId primordialProjectId, bool doDesignTimeBuild) + { + using (await _gate.DisposableWaitAsync(CancellationToken.None)) + { + // If this project has already begun loading, we need to throw. + // This is because we can't ensure that the workspace and project system will remain in a consistent state after this call. + // For example, there could be a need for the project system to track both a primordial project and list of loaded targets, which we don't support. + if (_loadedProjects.ContainsKey(projectPath)) + { + Contract.Fail($"Cannot begin loading project '{projectPath}' because it has already begun loading."); + } + + _loadedProjects.Add(projectPath, new ProjectLoadState.Primordial(primordialProjectId)); + if (doDesignTimeBuild) + { + _projectsToReload.AddWork(new ProjectToLoad(projectPath, ProjectGuid: null, ReportTelemetry: true)); + } + } + } + + /// + /// Begins loading a project. If the project has already begun loading, returns without doing any additional work. + /// + protected async Task BeginLoadingProjectAsync(string projectPath, string? projectGuid) + { + using (await _gate.DisposableWaitAsync(CancellationToken.None)) + { + // If project has already begun loading, no need to do any further work. + if (_loadedProjects.ContainsKey(projectPath)) + { + return; + } + + _loadedProjects.Add(projectPath, new ProjectLoadState.LoadedTargets(LoadedProjectTargets: [])); + _projectsToReload.AddWork(new ProjectToLoad(Path: projectPath, ProjectGuid: projectGuid, ReportTelemetry: true)); + } + } + + protected Task WaitForProjectsToFinishLoadingAsync() => _projectsToReload.WaitUntilCurrentBatchCompletesAsync(); + + protected async ValueTask UnloadProjectAsync(string projectPath) + { + using (await _gate.DisposableWaitAsync(CancellationToken.None)) + { + if (!_loadedProjects.Remove(projectPath, out var loadState)) + { + // It is common to be called with a path to a project which is already not loaded. + // In this case, we should do nothing. + return; + } + + if (loadState is ProjectLoadState.Primordial(var projectId)) + { + await ProjectFactory.ApplyChangeToWorkspaceAsync(workspace => workspace.OnProjectRemoved(projectId)); + } + else if (loadState is ProjectLoadState.LoadedTargets(var existingProjects)) + { + foreach (var existingProject in existingProjects) + { + // Disposing a LoadedProject unloads it and removes it from the workspace. + existingProject.Dispose(); + } + } + else + { + throw ExceptionUtilities.UnexpectedValue(loadState); + } + } + } } diff --git a/src/roslyn/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer/HostWorkspace/LanguageServerProjectSystem.cs b/src/roslyn/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer/HostWorkspace/LanguageServerProjectSystem.cs index caea9bff27f..47145013cfb 100644 --- a/src/roslyn/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer/HostWorkspace/LanguageServerProjectSystem.cs +++ b/src/roslyn/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer/HostWorkspace/LanguageServerProjectSystem.cs @@ -2,27 +2,19 @@ // 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.Concurrent; using System.Collections.Immutable; using System.Composition; -using System.Diagnostics; using System.Runtime.InteropServices; -using Microsoft.CodeAnalysis.Collections; -using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.LanguageServer.HostWorkspace.ProjectTelemetry; using Microsoft.CodeAnalysis.MSBuild; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.ProjectSystem; using Microsoft.CodeAnalysis.Shared.TestHooks; -using Microsoft.CodeAnalysis.Shared.Utilities; -using Microsoft.CodeAnalysis.Threading; -using Microsoft.CodeAnalysis.Workspaces.ProjectSystem; using Microsoft.Extensions.Logging; using Microsoft.VisualStudio.Composition; using Roslyn.Utilities; using static Microsoft.CodeAnalysis.MSBuild.BuildHostProcessManager; -using LSP = Roslyn.LanguageServer.Protocol; namespace Microsoft.CodeAnalysis.LanguageServer.HostWorkspace; @@ -30,7 +22,7 @@ namespace Microsoft.CodeAnalysis.LanguageServer.HostWorkspace; internal sealed class LanguageServerProjectSystem : LanguageServerProjectLoader { private readonly ILogger _logger; - private readonly SemaphoreSlim _gate = new SemaphoreSlim(initialCount: 1); + private readonly ProjectFileExtensionRegistry _projectFileExtensionRegistry; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] @@ -44,7 +36,7 @@ public LanguageServerProjectSystem( ServerConfigurationFactory serverConfigurationFactory, BinlogNamer binlogNamer) : base( - workspaceFactory.ProjectSystemProjectFactory, + workspaceFactory.HostProjectFactory, workspaceFactory.TargetFrameworkManager, workspaceFactory.ProjectSystemHostInfo, fileChangeWatcher, @@ -56,36 +48,34 @@ public LanguageServerProjectSystem( binlogNamer) { _logger = loggerFactory.CreateLogger(nameof(LanguageServerProjectSystem)); + var workspace = ProjectFactory.Workspace; + _projectFileExtensionRegistry = new ProjectFileExtensionRegistry(workspace.CurrentSolution.Services, new DiagnosticReporter(workspace)); } public async Task OpenSolutionAsync(string solutionFilePath) { - using (await _gate.DisposableWaitAsync()) - { - _logger.LogInformation(string.Format(LanguageServerResources.Loading_0, solutionFilePath)); - ProjectFactory.SolutionPath = solutionFilePath; - - // We'll load solutions out-of-proc, since it's possible we might be running on a runtime that doesn't have a matching SDK installed, - // and we don't want any MSBuild registration to set environment variables in our process that might impact child processes. - await using var buildHostProcessManager = new BuildHostProcessManager(globalMSBuildProperties: AdditionalProperties, loggerFactory: LoggerFactory); - var buildHost = await buildHostProcessManager.GetBuildHostAsync(BuildHostProcessKind.NetCore, CancellationToken.None); + _logger.LogInformation(string.Format(LanguageServerResources.Loading_0, solutionFilePath)); + ProjectFactory.SolutionPath = solutionFilePath; - // If we don't have a .NET Core SDK on this machine at all, try .NET Framework - if (!await buildHost.HasUsableMSBuildAsync(solutionFilePath, CancellationToken.None)) - { - var kind = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? BuildHostProcessKind.NetFramework : BuildHostProcessKind.Mono; - buildHost = await buildHostProcessManager.GetBuildHostAsync(kind, CancellationToken.None); - } + // We'll load solutions out-of-proc, since it's possible we might be running on a runtime that doesn't have a matching SDK installed, + // and we don't want any MSBuild registration to set environment variables in our process that might impact child processes. + await using var buildHostProcessManager = new BuildHostProcessManager(globalMSBuildProperties: AdditionalProperties, loggerFactory: LoggerFactory); + var buildHost = await buildHostProcessManager.GetBuildHostAsync(BuildHostProcessKind.NetCore, CancellationToken.None); - foreach (var project in await buildHost.GetProjectsInSolutionAsync(solutionFilePath, CancellationToken.None)) - { - ProjectsToLoadAndReload.AddWork(new ProjectToLoad(project.ProjectPath, project.ProjectGuid, ReportTelemetry: true)); - } + // If we don't have a .NET Core SDK on this machine at all, try .NET Framework + if (!await buildHost.HasUsableMSBuildAsync(solutionFilePath, CancellationToken.None)) + { + var kind = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? BuildHostProcessKind.NetFramework : BuildHostProcessKind.Mono; + buildHost = await buildHostProcessManager.GetBuildHostAsync(kind, CancellationToken.None); + } - // Wait for the in progress batch to complete and send a project initialized notification to the client. - await ProjectsToLoadAndReload.WaitUntilCurrentBatchCompletesAsync(); - await ProjectInitializationHandler.SendProjectInitializationCompleteNotificationAsync(); + var projects = await buildHost.GetProjectsInSolutionAsync(solutionFilePath, CancellationToken.None); + foreach (var (path, guid) in projects) + { + await BeginLoadingProjectAsync(path, guid); } + await WaitForProjectsToFinishLoadingAsync(); + await ProjectInitializationHandler.SendProjectInitializationCompleteNotificationAsync(); } public async Task OpenProjectsAsync(ImmutableArray projectFilePaths) @@ -93,13 +83,24 @@ public async Task OpenProjectsAsync(ImmutableArray projectFilePaths) if (!projectFilePaths.Any()) return; - using (await _gate.DisposableWaitAsync()) + foreach (var path in projectFilePaths) { - ProjectsToLoadAndReload.AddWork(projectFilePaths.Select(p => new ProjectToLoad(p, ProjectGuid: null, ReportTelemetry: true))); - - // Wait for the in progress batch to complete and send a project initialized notification to the client. - await ProjectsToLoadAndReload.WaitUntilCurrentBatchCompletesAsync(); - await ProjectInitializationHandler.SendProjectInitializationCompleteNotificationAsync(); + await BeginLoadingProjectAsync(path, projectGuid: null); } + await WaitForProjectsToFinishLoadingAsync(); + await ProjectInitializationHandler.SendProjectInitializationCompleteNotificationAsync(); + } + + protected override async Task<(RemoteProjectFile projectFile, bool hasAllInformation, BuildHostProcessKind preferred, BuildHostProcessKind actual)?> TryLoadProjectInMSBuildHostAsync( + BuildHostProcessManager buildHostProcessManager, string projectPath, CancellationToken cancellationToken) + { + if (!_projectFileExtensionRegistry.TryGetLanguageNameFromProjectPath(projectPath, DiagnosticReportingMode.Ignore, out var languageName)) + return null; + + var preferredBuildHostKind = GetKindForProject(projectPath); + var (buildHost, actualBuildHostKind) = await buildHostProcessManager.GetBuildHostWithFallbackAsync(preferredBuildHostKind, projectPath, cancellationToken); + + var loadedFile = await buildHost.LoadProjectFileAsync(projectPath, languageName, cancellationToken); + return (loadedFile, hasAllInformation: true, preferredBuildHostKind, actualBuildHostKind); } } diff --git a/src/roslyn/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer/HostWorkspace/LanguageServerWorkspace.cs b/src/roslyn/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer/HostWorkspace/LanguageServerWorkspace.cs index 78d8546e280..26f2eb2fae2 100644 --- a/src/roslyn/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer/HostWorkspace/LanguageServerWorkspace.cs +++ b/src/roslyn/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer/HostWorkspace/LanguageServerWorkspace.cs @@ -2,9 +2,11 @@ // 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.Diagnostics; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.Workspaces.ProjectSystem; +using Roslyn.Utilities; using LSP = Roslyn.LanguageServer.Protocol; namespace Microsoft.CodeAnalysis.LanguageServer.HostWorkspace; @@ -36,6 +38,7 @@ namespace Microsoft.CodeAnalysis.LanguageServer.HostWorkspace; /// it will use the local information it has outside of the workspace to ensure it is always matched with the lsp /// client. /// +[DebuggerDisplay("{GetDebuggerDisplay(),nq}")] internal sealed class LanguageServerWorkspace : Workspace, ILspWorkspace { /// @@ -44,8 +47,8 @@ internal sealed class LanguageServerWorkspace : Workspace, ILspWorkspace /// public ProjectSystemProjectFactory ProjectSystemProjectFactory { private get; set; } = null!; - public LanguageServerWorkspace(HostServices host) - : base(host, WorkspaceKind.Host) + public LanguageServerWorkspace(HostServices host, string workspaceKind) + : base(host, workspaceKind) { } @@ -106,7 +109,9 @@ internal override ValueTask TryOnDocumentClosedAsync(DocumentId documentId, Canc { TextLoader loader; var document = textDocument as Document; - if (document?.DocumentState.Attributes.DesignTimeOnly == true) + + // 'DesignTimeOnly == true' or 'filePath' not being absolute indicates the document is for a virtual file (in-memory, not on-disk). + if (document is not null && (document.DocumentState.Attributes.DesignTimeOnly || !PathUtilities.IsAbsolute(filePath))) { // Dynamic files don't exist on disk so if we were to use the FileTextLoader we'd effectively be emptying out the document. // We also assume they're not user editable, and hence can't have "unsaved" changes that are expected to go away on close. @@ -133,4 +138,9 @@ internal override ValueTask TryOnDocumentClosedAsync(DocumentId documentId, Canc }, cancellationToken); } + + private string GetDebuggerDisplay() + { + return $"""LanguageServerWorkspace(Kind: "{Kind}")"""; + } } diff --git a/src/roslyn/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer/HostWorkspace/LanguageServerWorkspaceFactory.cs b/src/roslyn/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer/HostWorkspace/LanguageServerWorkspaceFactory.cs index 2bbe0368ccb..e00375533db 100644 --- a/src/roslyn/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer/HostWorkspace/LanguageServerWorkspaceFactory.cs +++ b/src/roslyn/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer/HostWorkspace/LanguageServerWorkspaceFactory.cs @@ -45,14 +45,22 @@ public LanguageServerWorkspaceFactory( .ToImmutableArray(); // Create the workspace and set analyzer references for it - var workspace = new LanguageServerWorkspace(hostServicesProvider.HostServices); + var workspace = new LanguageServerWorkspace(hostServicesProvider.HostServices, WorkspaceKind.Host); workspace.SetCurrentSolution(s => s.WithAnalyzerReferences(CreateSolutionLevelAnalyzerReferencesForWorkspace(workspace)), WorkspaceChangeKind.SolutionChanged); - Workspace = workspace; - ProjectSystemProjectFactory = new ProjectSystemProjectFactory( - Workspace, fileChangeWatcher, static (_, _) => Task.CompletedTask, _ => { }, + HostProjectFactory = new ProjectSystemProjectFactory( + workspace, fileChangeWatcher, static (_, _) => Task.CompletedTask, _ => { }, CancellationToken.None); // TODO: do we need to introduce a shutdown cancellation token for this? - workspace.ProjectSystemProjectFactory = ProjectSystemProjectFactory; + workspace.ProjectSystemProjectFactory = HostProjectFactory; + + // https://github.com/dotnet/roslyn/issues/78560: Move this workspace creation to 'FileBasedProgramsWorkspaceProviderFactory'. + // 'CreateSolutionLevelAnalyzerReferencesForWorkspace' needs to be broken out into its own service for us to be able to move this. + var fileBasedProgramsWorkspace = new LanguageServerWorkspace(hostServicesProvider.HostServices, WorkspaceKind.MiscellaneousFiles); + fileBasedProgramsWorkspace.SetCurrentSolution(s => s.WithAnalyzerReferences(CreateSolutionLevelAnalyzerReferencesForWorkspace(fileBasedProgramsWorkspace)), WorkspaceChangeKind.SolutionChanged); + + FileBasedProgramsProjectFactory = new ProjectSystemProjectFactory( + fileBasedProgramsWorkspace, fileChangeWatcher, static (_, _) => Task.CompletedTask, _ => { }, CancellationToken.None); + fileBasedProgramsWorkspace.ProjectSystemProjectFactory = FileBasedProgramsProjectFactory; var razorSourceGenerator = serverConfigurationFactory?.ServerConfiguration?.RazorSourceGenerator; ProjectSystemHostInfo = new ProjectSystemHostInfo( @@ -63,9 +71,11 @@ public LanguageServerWorkspaceFactory( TargetFrameworkManager = projectTargetFrameworkManager; } - public Workspace Workspace { get; } + public Workspace HostWorkspace => HostProjectFactory.Workspace; + + public ProjectSystemProjectFactory HostProjectFactory { get; } + public ProjectSystemProjectFactory FileBasedProgramsProjectFactory { get; } - public ProjectSystemProjectFactory ProjectSystemProjectFactory { get; } public ProjectSystemHostInfo ProjectSystemHostInfo { get; } public ProjectTargetFrameworkManager TargetFrameworkManager { get; } diff --git a/src/roslyn/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer/HostWorkspace/LoadedProject.cs b/src/roslyn/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer/HostWorkspace/LoadedProject.cs index c2cae1e5418..7a2c74612d7 100644 --- a/src/roslyn/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer/HostWorkspace/LoadedProject.cs +++ b/src/roslyn/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer/HostWorkspace/LoadedProject.cs @@ -100,13 +100,17 @@ private void FileChangedContext_FileChanged(object? sender, string filePath) return _mostRecentFileInfo.TargetFramework; } + /// + /// Unloads the project and removes it from the workspace. + /// public void Dispose() { + _fileChangeContext.Dispose(); _optionsProcessor.Dispose(); _projectSystemProject.RemoveFromWorkspace(); } - public async ValueTask<(ProjectLoadTelemetryReporter.TelemetryInfo, bool NeedsRestore)> UpdateWithNewProjectInfoAsync(ProjectFileInfo newProjectInfo, ILogger logger) + public async ValueTask<(ProjectLoadTelemetryReporter.TelemetryInfo, bool NeedsRestore)> UpdateWithNewProjectInfoAsync(ProjectFileInfo newProjectInfo, bool hasAllInformation, ILogger logger) { if (_mostRecentFileInfo != null) { @@ -134,6 +138,7 @@ public void Dispose() _projectSystemProject.GeneratedFilesOutputDirectory = newProjectInfo.GeneratedFilesOutputDirectory; _projectSystemProject.CompilationOutputAssemblyFilePath = newProjectInfo.IntermediateOutputFilePath; _projectSystemProject.DefaultNamespace = newProjectInfo.DefaultNamespace; + _projectSystemProject.HasAllInformation = hasAllInformation; if (newProjectInfo.TargetFrameworkIdentifier != null) { diff --git a/src/roslyn/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer/HostWorkspace/ProjectToLoad.cs b/src/roslyn/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer/HostWorkspace/ProjectToLoad.cs index f3d72668e11..41d767d74f9 100644 --- a/src/roslyn/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer/HostWorkspace/ProjectToLoad.cs +++ b/src/roslyn/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer/HostWorkspace/ProjectToLoad.cs @@ -7,7 +7,7 @@ namespace Microsoft.CodeAnalysis.LanguageServer.HostWorkspace; /// -/// The project path (and the guid if it game from a solution) of the project to load. +/// The project path (and the guid if it came from a solution) of the project to load. /// internal sealed record ProjectToLoad(string Path, string? ProjectGuid, bool ReportTelemetry) { diff --git a/src/roslyn/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer/HostWorkspace/Razor/RazorDynamicFileInfoProvider.cs b/src/roslyn/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer/HostWorkspace/Razor/RazorDynamicFileInfoProvider.cs index 9b3e7b29783..6eb90d6d0ef 100644 --- a/src/roslyn/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer/HostWorkspace/Razor/RazorDynamicFileInfoProvider.cs +++ b/src/roslyn/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer/HostWorkspace/Razor/RazorDynamicFileInfoProvider.cs @@ -37,7 +37,7 @@ internal sealed partial class RazorDynamicFileInfoProvider(Lazy +/// This will be replaced invoke dotnet run-api command implemented in https://github.com/dotnet/sdk/pull/48749 +/// +internal static class VirtualCSharpFileBasedProgramProject +{ + /// + /// Adjusts a path to a file-based program for use in passing the virtual project to msbuild. + /// (msbuild needs the path to end in .csproj to recognize as a C# project and apply all the standard props/targets to it.) + /// + internal static string GetVirtualProjectPath(string documentFilePath) + => Path.ChangeExtension(documentFilePath, ".csproj"); + + internal static (string virtualProjectXml, bool isFileBasedProgram) MakeVirtualProjectContent(string documentFilePath, SourceText text) + { + Contract.ThrowIfFalse(PathUtilities.IsAbsolute(documentFilePath)); + // NB: this is a temporary solution for running our heuristic. + // When we adopt the dotnet run-api, we need to get rid of this or adjust it to be more sustainable (e.g. using the appropriate document to get a syntax tree) + var tree = CSharpSyntaxTree.ParseText(text, options: CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.Preview), path: documentFilePath); + var root = tree.GetRoot(); + var isFileBasedProgram = root.GetLeadingTrivia().Any(SyntaxKind.IgnoredDirectiveTrivia) || root.ChildNodes().Any(node => node.IsKind(SyntaxKind.GlobalStatement)); + + var virtualProjectXml = $""" + + + + Exe + net8.0 + enable + enable + $(Features);FileBasedProgram + false + + + + + + + + + + + + + + + + + <_RestoreProjectPathItems Include="@(FilteredRestoreGraphProjectInputItems)" /> + + + + + + + + """; + + return (virtualProjectXml, isFileBasedProgram); + } +} diff --git a/src/roslyn/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer/HostWorkspace/WorkspaceProjectFactoryService.cs b/src/roslyn/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer/HostWorkspace/WorkspaceProjectFactoryService.cs index b3f28c56512..90b2b00d53a 100644 --- a/src/roslyn/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer/HostWorkspace/WorkspaceProjectFactoryService.cs +++ b/src/roslyn/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer/HostWorkspace/WorkspaceProjectFactoryService.cs @@ -48,16 +48,16 @@ public async Task CreateAndAddProjectAsync(WorkspaceProjectCr { if (creationInfo.BuildSystemProperties.TryGetValue("SolutionPath", out var solutionPath)) { - _workspaceFactory.ProjectSystemProjectFactory.SolutionPath = solutionPath; + _workspaceFactory.HostProjectFactory.SolutionPath = solutionPath; } - var project = await _workspaceFactory.ProjectSystemProjectFactory.CreateAndAddToWorkspaceAsync( + var project = await _workspaceFactory.HostProjectFactory.CreateAndAddToWorkspaceAsync( creationInfo.DisplayName, creationInfo.Language, new Workspaces.ProjectSystem.ProjectSystemProjectCreationInfo { FilePath = creationInfo.FilePath }, _workspaceFactory.ProjectSystemHostInfo); - var workspaceProject = new WorkspaceProject(project, _workspaceFactory.Workspace.Services.SolutionServices, _workspaceFactory.TargetFrameworkManager, _loggerFactory); + var workspaceProject = new WorkspaceProject(project, _workspaceFactory.HostWorkspace.Services.SolutionServices, _workspaceFactory.TargetFrameworkManager, _loggerFactory); // We've created a new project, so initialize properties we have await workspaceProject.SetBuildSystemPropertiesAsync(creationInfo.BuildSystemProperties, CancellationToken.None); diff --git a/src/roslyn/src/LanguageServer/Protocol.TestUtilities/Diagnostics/TestDiagnosticAnalyzerDriver.cs b/src/roslyn/src/LanguageServer/Protocol.TestUtilities/Diagnostics/TestDiagnosticAnalyzerDriver.cs index 7f2f6b4c1b0..dcfbef292e3 100644 --- a/src/roslyn/src/LanguageServer/Protocol.TestUtilities/Diagnostics/TestDiagnosticAnalyzerDriver.cs +++ b/src/roslyn/src/LanguageServer/Protocol.TestUtilities/Diagnostics/TestDiagnosticAnalyzerDriver.cs @@ -8,6 +8,7 @@ using System.Linq; using System.Threading; using System.Threading.Tasks; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Test.Utilities; diff --git a/src/roslyn/src/LanguageServer/Protocol.TestUtilities/LanguageServer/AbstractLanguageServerProtocolTests.cs b/src/roslyn/src/LanguageServer/Protocol.TestUtilities/LanguageServer/AbstractLanguageServerProtocolTests.cs index 9925ad95eab..a887ae34e8a 100644 --- a/src/roslyn/src/LanguageServer/Protocol.TestUtilities/LanguageServer/AbstractLanguageServerProtocolTests.cs +++ b/src/roslyn/src/LanguageServer/Protocol.TestUtilities/LanguageServer/AbstractLanguageServerProtocolTests.cs @@ -330,23 +330,6 @@ private async Task CreateTestLspServerAsync(LspTestWorkspace work { var solution = workspace.CurrentSolution; - foreach (var document in workspace.Documents) - { - if (document.IsSourceGenerated) - continue; - - solution = solution.WithDocumentFilePath(document.Id, GetDocumentFilePathFromName(document.Name)); - - var documentText = await solution.GetRequiredDocument(document.Id).GetTextAsync(CancellationToken.None); - solution = solution.WithDocumentText(document.Id, SourceText.From(documentText.ToString(), System.Text.Encoding.UTF8, SourceHashAlgorithms.Default)); - } - - foreach (var project in workspace.Projects) - { - // Ensure all the projects have a valid file path. - solution = solution.WithProjectFilePath(project.Id, GetDocumentFilePathFromName(project.FilePath)); - } - var analyzerReferencesByLanguage = CreateTestAnalyzersReference(); if (initializationOptions.AdditionalAnalyzers != null) analyzerReferencesByLanguage = analyzerReferencesByLanguage.WithAdditionalAnalyzers(languageName, initializationOptions.AdditionalAnalyzers); @@ -496,9 +479,6 @@ private protected static LSP.Location GetLocationPlusOne(LSP.Location originalLo }; } - private static string GetDocumentFilePathFromName(string documentName) - => "C:\\" + documentName; - private static LSP.DidChangeTextDocumentParams CreateDidChangeTextDocumentParams( DocumentUri documentUri, ImmutableArray<(LSP.Range Range, string Text)> changes) diff --git a/src/roslyn/src/LanguageServer/Protocol/Extensions/ProtocolConversions.cs b/src/roslyn/src/LanguageServer/Protocol/Extensions/ProtocolConversions.cs index a8449c99b24..187cd244bdf 100644 --- a/src/roslyn/src/LanguageServer/Protocol/Extensions/ProtocolConversions.cs +++ b/src/roslyn/src/LanguageServer/Protocol/Extensions/ProtocolConversions.cs @@ -832,7 +832,9 @@ public static LSP.VSProjectContext ProjectToProjectContext(Project project) { Id = ProjectIdToProjectContextId(project.Id), Label = project.Name, - IsMiscellaneous = project.Solution.WorkspaceKind == WorkspaceKind.MiscellaneousFiles, + // IsMiscellaneous controls whether a toast appears which warns that editor features are not available. + // In case HasAllInformation is true, though, we do actually have all information needed to light up any features user is trying to use related to the project. + IsMiscellaneous = project.Solution.WorkspaceKind == WorkspaceKind.MiscellaneousFiles && !project.State.HasAllInformation, }; if (project.Language == LanguageNames.CSharp) diff --git a/src/roslyn/src/LanguageServer/Protocol/Features/Options/LanguageServerProjectSystemOptionsStorage.cs b/src/roslyn/src/LanguageServer/Protocol/Features/Options/LanguageServerProjectSystemOptionsStorage.cs index 04364827cd6..05b65aa3247 100644 --- a/src/roslyn/src/LanguageServer/Protocol/Features/Options/LanguageServerProjectSystemOptionsStorage.cs +++ b/src/roslyn/src/LanguageServer/Protocol/Features/Options/LanguageServerProjectSystemOptionsStorage.cs @@ -19,4 +19,9 @@ internal static class LanguageServerProjectSystemOptionsStorage /// Whether or not automatic nuget restore is enabled. /// public static readonly Option2 EnableAutomaticRestore = new Option2("dotnet_enable_automatic_restore", defaultValue: true, s_optionGroup); + + /// + /// Whether to use the new 'dotnet run app.cs' (file-based programs) experience. + /// + public static readonly Option2 EnableFileBasedPrograms = new Option2("dotnet_enable_file_based_programs", defaultValue: true, s_optionGroup); } diff --git a/src/roslyn/src/LanguageServer/Protocol/Handler/Completion/CompletionCapabilityHelper.cs b/src/roslyn/src/LanguageServer/Protocol/Handler/Completion/CompletionCapabilityHelper.cs index db6a32115cb..d16fab7642f 100644 --- a/src/roslyn/src/LanguageServer/Protocol/Handler/Completion/CompletionCapabilityHelper.cs +++ b/src/roslyn/src/LanguageServer/Protocol/Handler/Completion/CompletionCapabilityHelper.cs @@ -6,6 +6,7 @@ using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.LanguageServer.Protocol; using Roslyn.Utilities; diff --git a/src/roslyn/src/LanguageServer/Protocol/Handler/Configuration/DidChangeConfigurationNotificationHandler_OptionList.cs b/src/roslyn/src/LanguageServer/Protocol/Handler/Configuration/DidChangeConfigurationNotificationHandler_OptionList.cs index 2a9a61828b0..89fa870411f 100644 --- a/src/roslyn/src/LanguageServer/Protocol/Handler/Configuration/DidChangeConfigurationNotificationHandler_OptionList.cs +++ b/src/roslyn/src/LanguageServer/Protocol/Handler/Configuration/DidChangeConfigurationNotificationHandler_OptionList.cs @@ -58,6 +58,7 @@ internal sealed partial class DidChangeConfigurationNotificationHandler LspOptionsStorage.LspEnableAutoInsert, LanguageServerProjectSystemOptionsStorage.BinaryLogPath, LanguageServerProjectSystemOptionsStorage.EnableAutomaticRestore, + LanguageServerProjectSystemOptionsStorage.EnableFileBasedPrograms, MetadataAsSourceOptionsStorage.NavigateToSourceLinkAndEmbeddedSources, LspOptionsStorage.LspOrganizeImportsOnFormat, ]; diff --git a/src/roslyn/src/LanguageServer/Protocol/Handler/Formatting/AbstractFormatDocumentHandlerBase.cs b/src/roslyn/src/LanguageServer/Protocol/Handler/Formatting/AbstractFormatDocumentHandlerBase.cs index 6b220acd0c0..02940fd5063 100644 --- a/src/roslyn/src/LanguageServer/Protocol/Handler/Formatting/AbstractFormatDocumentHandlerBase.cs +++ b/src/roslyn/src/LanguageServer/Protocol/Handler/Formatting/AbstractFormatDocumentHandlerBase.cs @@ -5,6 +5,7 @@ using System.Linq; using System.Threading; using System.Threading.Tasks; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.OrganizeImports; diff --git a/src/roslyn/src/LanguageServer/Protocol/Workspaces/ILspMiscellaneousFilesWorkspaceProvider.cs b/src/roslyn/src/LanguageServer/Protocol/Workspaces/ILspMiscellaneousFilesWorkspaceProvider.cs index 2b3a00bd63d..6635fd32f12 100644 --- a/src/roslyn/src/LanguageServer/Protocol/Workspaces/ILspMiscellaneousFilesWorkspaceProvider.cs +++ b/src/roslyn/src/LanguageServer/Protocol/Workspaces/ILspMiscellaneousFilesWorkspaceProvider.cs @@ -3,6 +3,7 @@ // See the LICENSE file in the project root for more information. using System; +using System.Threading.Tasks; using Microsoft.CodeAnalysis.Text; using Microsoft.CommonLanguageServerProtocol.Framework; using Roslyn.LanguageServer.Protocol; @@ -15,6 +16,18 @@ internal interface ILspMiscellaneousFilesWorkspaceProvider : ILspService /// Returns the actual workspace that the documents are added to or removed from. /// Workspace Workspace { get; } - TextDocument? AddMiscellaneousDocument(DocumentUri uri, SourceText documentText, string languageId, ILspLogger logger); - void TryRemoveMiscellaneousDocument(DocumentUri uri, bool removeFromMetadataWorkspace); + + /// + /// Adds a document to the workspace. Note that the implementation of this method should not depend on anything expensive such as RPC calls. + /// async is used here to allow taking locks asynchronously and "relatively fast" stuff like that. + /// + ValueTask AddMiscellaneousDocumentAsync(DocumentUri uri, SourceText documentText, string languageId, ILspLogger logger); + + /// + /// Removes the document with the given from the workspace. + /// If the workspace already does not contain such a document, does nothing. + /// Note that the implementation of this method should not depend on anything expensive such as RPC calls. + /// async is used here to allow taking locks asynchronously and "relatively fast" stuff like that. + /// + ValueTask TryRemoveMiscellaneousDocumentAsync(DocumentUri uri, bool removeFromMetadataWorkspace); } diff --git a/src/roslyn/src/LanguageServer/Protocol/Workspaces/LspMiscellaneousFilesWorkspaceProvider.cs b/src/roslyn/src/LanguageServer/Protocol/Workspaces/LspMiscellaneousFilesWorkspaceProvider.cs index db2940f3585..d8ead3e1210 100644 --- a/src/roslyn/src/LanguageServer/Protocol/Workspaces/LspMiscellaneousFilesWorkspaceProvider.cs +++ b/src/roslyn/src/LanguageServer/Protocol/Workspaces/LspMiscellaneousFilesWorkspaceProvider.cs @@ -37,10 +37,13 @@ internal sealed class LspMiscellaneousFilesWorkspaceProvider(ILspServices lspSer /// /// Takes in a file URI and text and creates a misc project and document for the file. /// - /// Calls to this method and are made + /// Calls to this method and are made /// from LSP text sync request handling which do not run concurrently. /// - public TextDocument? AddMiscellaneousDocument(DocumentUri uri, SourceText documentText, string languageId, ILspLogger logger) + public ValueTask AddMiscellaneousDocumentAsync(DocumentUri uri, SourceText documentText, string languageId, ILspLogger logger) + => ValueTaskFactory.FromResult(AddMiscellaneousDocument(uri, documentText, languageId, logger)); + + private TextDocument? AddMiscellaneousDocument(DocumentUri uri, SourceText documentText, string languageId, ILspLogger logger) { var documentFilePath = uri.UriString; if (uri.ParsedUri is not null) @@ -87,11 +90,11 @@ internal sealed class LspMiscellaneousFilesWorkspaceProvider(ILspServices lspSer /// Calls to this method and are made /// from LSP text sync request handling which do not run concurrently. /// - public void TryRemoveMiscellaneousDocument(DocumentUri uri, bool removeFromMetadataWorkspace) + public ValueTask TryRemoveMiscellaneousDocumentAsync(DocumentUri uri, bool removeFromMetadataWorkspace) { if (removeFromMetadataWorkspace && uri.ParsedUri is not null && metadataAsSourceFileService.TryRemoveDocumentFromWorkspace(ProtocolConversions.GetDocumentFilePathFromUri(uri.ParsedUri))) { - return; + return ValueTaskFactory.CompletedTask; } // We'll only ever have a single document matching this URI in the misc solution. @@ -112,6 +115,8 @@ public void TryRemoveMiscellaneousDocument(DocumentUri uri, bool removeFromMetad var project = CurrentSolution.GetRequiredProject(matchingDocument.ProjectId); OnProjectRemoved(project.Id); } + + return ValueTaskFactory.CompletedTask; } public ValueTask UpdateTextIfPresentAsync(DocumentId documentId, SourceText sourceText, CancellationToken cancellationToken) diff --git a/src/roslyn/src/LanguageServer/Protocol/Workspaces/LspWorkspaceManager.cs b/src/roslyn/src/LanguageServer/Protocol/Workspaces/LspWorkspaceManager.cs index 281ad35c95c..22e3c092dbb 100644 --- a/src/roslyn/src/LanguageServer/Protocol/Workspaces/LspWorkspaceManager.cs +++ b/src/roslyn/src/LanguageServer/Protocol/Workspaces/LspWorkspaceManager.cs @@ -9,6 +9,7 @@ using System.Linq; using System.Threading; using System.Threading.Tasks; +using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.LanguageServer.Handler; using Microsoft.CodeAnalysis.LanguageServer.Handler.DocumentChanges; using Microsoft.CodeAnalysis.PooledObjects; @@ -153,7 +154,17 @@ public async ValueTask StopTrackingAsync(DocumentUri uri, CancellationToken canc _cachedLspSolutions.Clear(); // Also remove it from our loose files or metadata workspace if it is still there. - _lspMiscellaneousFilesWorkspaceProvider?.TryRemoveMiscellaneousDocument(uri, removeFromMetadataWorkspace: true); + if (_lspMiscellaneousFilesWorkspaceProvider is not null) + { + try + { + await _lspMiscellaneousFilesWorkspaceProvider.TryRemoveMiscellaneousDocumentAsync(uri, removeFromMetadataWorkspace: true).ConfigureAwait(false); + } + catch (Exception ex) when (FatalError.ReportAndCatch(ex)) + { + this._logger.LogException(ex); + } + } LspTextChanged?.Invoke(this, EventArgs.Empty); @@ -253,8 +264,18 @@ public void UpdateTrackedDocument(DocumentUri uri, SourceText newSourceText) // if it happens to be in there as well. if (workspace != _lspMiscellaneousFilesWorkspaceProvider?.Workspace) { - // Do not attempt to remove the file from the metadata workspace (the document is still open). - _lspMiscellaneousFilesWorkspaceProvider?.TryRemoveMiscellaneousDocument(uri, removeFromMetadataWorkspace: false); + if (_lspMiscellaneousFilesWorkspaceProvider is not null) + { + try + { + // Do not attempt to remove the file from the metadata workspace (the document is still open). + await _lspMiscellaneousFilesWorkspaceProvider.TryRemoveMiscellaneousDocumentAsync(uri, removeFromMetadataWorkspace: false).ConfigureAwait(false); + } + catch (Exception ex) when (FatalError.ReportAndCatch(ex)) + { + _logger.LogException(ex); + } + } } return (workspace, document.Project.Solution, document); @@ -268,11 +289,18 @@ public void UpdateTrackedDocument(DocumentUri uri, SourceText newSourceText) _requestTelemetryLogger.UpdateFindDocumentTelemetryData(success: false, workspaceKind: null); // Add the document to our loose files workspace (if we have one) if it is open. - if (_trackedDocuments.TryGetValue(uri, out var trackedDocument)) + if (_trackedDocuments.TryGetValue(uri, out var trackedDocument) && _lspMiscellaneousFilesWorkspaceProvider is not null) { - var miscDocument = _lspMiscellaneousFilesWorkspaceProvider?.AddMiscellaneousDocument(uri, trackedDocument.Text, trackedDocument.LanguageId, _logger); - if (miscDocument is not null) - return (miscDocument.Project.Solution.Workspace, miscDocument.Project.Solution, miscDocument); + try + { + var miscDocument = await _lspMiscellaneousFilesWorkspaceProvider.AddMiscellaneousDocumentAsync(uri, trackedDocument.Text, trackedDocument.LanguageId, _logger).ConfigureAwait(false); + if (miscDocument is not null) + return (miscDocument.Project.Solution.Workspace, miscDocument.Project.Solution, miscDocument); + } + catch (Exception ex) when (FatalError.ReportAndCatch(ex)) + { + _logger.LogException(ex); + } } return default; diff --git a/src/roslyn/src/LanguageServer/ProtocolUnitTests/Configuration/DidChangeConfigurationNotificationHandlerTest.cs b/src/roslyn/src/LanguageServer/ProtocolUnitTests/Configuration/DidChangeConfigurationNotificationHandlerTest.cs index e0afe76a841..b69153c799c 100644 --- a/src/roslyn/src/LanguageServer/ProtocolUnitTests/Configuration/DidChangeConfigurationNotificationHandlerTest.cs +++ b/src/roslyn/src/LanguageServer/ProtocolUnitTests/Configuration/DidChangeConfigurationNotificationHandlerTest.cs @@ -147,6 +147,7 @@ public void VerifyLspClientOptionNames() "auto_insert.dotnet_enable_auto_insert", "projects.dotnet_binary_log_path", "projects.dotnet_enable_automatic_restore", + "projects.dotnet_enable_file_based_programs", "navigation.dotnet_navigate_to_source_link_and_embedded_sources", "formatting.dotnet_organize_imports_on_format", }; diff --git a/src/roslyn/src/LanguageServer/ProtocolUnitTests/Diagnostics/PullDiagnosticTests.cs b/src/roslyn/src/LanguageServer/ProtocolUnitTests/Diagnostics/PullDiagnosticTests.cs index aab9adbec58..cffdff4781a 100644 --- a/src/roslyn/src/LanguageServer/ProtocolUnitTests/Diagnostics/PullDiagnosticTests.cs +++ b/src/roslyn/src/LanguageServer/ProtocolUnitTests/Diagnostics/PullDiagnosticTests.cs @@ -4,6 +4,7 @@ using System; using System.Collections.Immutable; +using System.IO; using System.Linq; using System.Threading; using System.Threading.Tasks; @@ -18,6 +19,7 @@ using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.CodeAnalysis.SolutionCrawler; using Microsoft.CodeAnalysis.TaskList; +using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Threading; using Roslyn.LanguageServer.Protocol; @@ -1263,18 +1265,20 @@ public async Task EditAndContinue(bool useVSDiagnostics, bool mutatingLspWorkspa var documentResults1 = await RunGetDocumentPullDiagnosticsAsync(testLspServer, openDocument.GetURI(), useVSDiagnostics, category: PullDiagnosticCategories.EditAndContinue); + var rootUri = ProtocolConversions.GetAbsoluteUriString(TestWorkspace.RootDirectory); + // both diagnostics located in the open document are reported: AssertEx.Equal( [ - "file:///C:/test1.cs -> [ENC_OPEN_DOC1,ENC_OPEN_DOC2]", + $"{rootUri}/test1.cs -> [ENC_OPEN_DOC1,ENC_OPEN_DOC2]", ], documentResults1.Select(Inspect)); var workspaceResults1 = await RunGetWorkspacePullDiagnosticsAsync(testLspServer, useVSDiagnostics, includeTaskListItems: false, category: PullDiagnosticCategories.EditAndContinue); AssertEx.Equal( [ - "file:///C:/test2.cs -> [ENC_CLOSED_DOC]", - "file:///C:/Test.csproj -> [ENC_PROJECT]", + $"{rootUri}/test2.cs -> [ENC_CLOSED_DOC]", + $"{rootUri}/Test.csproj -> [ENC_PROJECT]", ], workspaceResults1.Select(Inspect)); // clear workspace diagnostics: @@ -1287,15 +1291,15 @@ public async Task EditAndContinue(bool useVSDiagnostics, bool mutatingLspWorkspa AssertEx.Equal( [ - "file:///C:/test1.cs -> [ENC_OPEN_DOC2]", + $"{rootUri}/test1.cs -> [ENC_OPEN_DOC2]", ], documentResults2.Select(Inspect)); var workspaceResults2 = await RunGetWorkspacePullDiagnosticsAsync( testLspServer, useVSDiagnostics, previousResults: CreateDiagnosticParamsFromPreviousReports(workspaceResults1), includeTaskListItems: false, category: PullDiagnosticCategories.EditAndContinue); AssertEx.Equal( [ - "file:///C:/test2.cs -> []", - "file:///C:/Test.csproj -> []", + $"{rootUri}/test2.cs -> []", + $"{rootUri}/Test.csproj -> []", ], workspaceResults2.Select(Inspect)); // deactivate EnC session: @@ -1307,7 +1311,7 @@ public async Task EditAndContinue(bool useVSDiagnostics, bool mutatingLspWorkspa testLspServer, openDocument.GetURI(), previousResultId: documentResults2.Single().ResultId, useVSDiagnostics: useVSDiagnostics, category: PullDiagnosticCategories.EditAndContinue); AssertEx.Equal( [ - "file:///C:/test1.cs -> []", + $"{rootUri}/test1.cs -> []", ], documentResults3.Select(Inspect)); var workspaceResults3 = await RunGetWorkspacePullDiagnosticsAsync( @@ -1318,27 +1322,23 @@ static DiagnosticData CreateDocumentDiagnostic(string id, Document document) => CreateDiagnostic(id, document.Project, document); static DiagnosticData CreateDiagnostic(string id, Project project, Document? document = null) - { - return new( - id, - category: "EditAndContinue", - message: "test message", - severity: DiagnosticSeverity.Error, - defaultSeverity: DiagnosticSeverity.Error, - isEnabledByDefault: true, - warningLevel: 0, - projectId: project.Id, - customTags: [], - properties: ImmutableDictionary.Empty, - location: new DiagnosticDataLocation(new FileLinePositionSpan("file", span: default), document?.Id), - additionalLocations: [], - language: project.Language); - } + => new( + id, + category: "EditAndContinue", + message: "test message", + severity: DiagnosticSeverity.Error, + defaultSeverity: DiagnosticSeverity.Error, + isEnabledByDefault: true, + warningLevel: 0, + projectId: project.Id, + customTags: [], + properties: ImmutableDictionary.Empty, + location: new DiagnosticDataLocation(new FileLinePositionSpan("file", span: default), document?.Id), + additionalLocations: [], + language: project.Language); static string Inspect(TestDiagnosticResult result) - { - return $"{result.TextDocument.DocumentUri} -> [{string.Join(",", result.Diagnostics?.Select(d => d.Code?.Value) ?? [])}]"; - } + => $"{result.TextDocument.DocumentUri} -> [{string.Join(",", result.Diagnostics?.Select(d => d.Code?.Value) ?? [])}]"; } [Theory, CombinatorialData] @@ -1584,7 +1584,7 @@ class A { var results = await RunGetWorkspacePullDiagnosticsAsync(testLspServer, useVSDiagnostics); Assert.Equal(3, results.Length); - Assert.Equal(ProtocolConversions.CreateAbsoluteDocumentUri(@"C:\test1.cs"), results[0].TextDocument!.DocumentUri); + Assert.Equal(ProtocolConversions.CreateAbsoluteDocumentUri(Path.Combine(TestWorkspace.RootDirectory, "test1.cs")), results[0].TextDocument!.DocumentUri); Assert.Equal("CS1513", results[0].Diagnostics!.Single().Code); Assert.Equal(1, results[0].Diagnostics!.Single().Range.Start.Line); AssertEx.Empty(results[1].Diagnostics); @@ -2000,11 +2000,11 @@ public async Task TestWorkspaceDiagnosticsDoesNotThrowIfProjectWithoutFilePathEx var workspaceXml = $""" - - {csharpMarkup} + + {csharpMarkup} - - + + """; @@ -2013,10 +2013,14 @@ public async Task TestWorkspaceDiagnosticsDoesNotThrowIfProjectWithoutFilePathEx var results = await RunGetWorkspacePullDiagnosticsAsync(testLspServer, useVSDiagnostics); - Assert.Equal(3, results.Length); - Assert.Equal(@"C:/C.cs", results[0].TextDocument.DocumentUri.GetRequiredParsedUri().AbsolutePath); - Assert.Equal(@"C:/CSProj1.csproj", results[1].TextDocument.DocumentUri.GetRequiredParsedUri().AbsolutePath); - Assert.Equal(@"C:/C2.cs", results[2].TextDocument.DocumentUri.GetRequiredParsedUri().AbsolutePath); + var dir = TestWorkspace.RootDirectory.Replace("\\", "/"); + + AssertEx.SequenceEqual( + [ + $"{dir}/C.cs", + $"{dir}/CSProj1.csproj", + $"{dir}/C2.cs" + ], results.Select(r => r.TextDocument.DocumentUri.GetRequiredParsedUri().AbsolutePath)); } [Theory, CombinatorialData] diff --git a/src/roslyn/src/Tools/ExternalAccess/Xaml/External/ConversionHelpers.cs b/src/roslyn/src/Tools/ExternalAccess/Xaml/External/ConversionHelpers.cs index e3b37c1663b..a114efe081a 100644 --- a/src/roslyn/src/Tools/ExternalAccess/Xaml/External/ConversionHelpers.cs +++ b/src/roslyn/src/Tools/ExternalAccess/Xaml/External/ConversionHelpers.cs @@ -7,14 +7,15 @@ using System.Linq; using Microsoft.CodeAnalysis.LanguageServer; using Microsoft.CodeAnalysis.QuickInfo; +using Roslyn.LanguageServer.Protocol; using LSP = Roslyn.LanguageServer.Protocol; namespace Microsoft.CodeAnalysis.ExternalAccess.Xaml; internal static class ConversionHelpers { - public static Uri CreateAbsoluteUri(string absolutePath) - => ProtocolConversions.CreateAbsoluteUri(absolutePath); + public static DocumentUri CreateAbsoluteDocumentUri(string absolutePath) + => ProtocolConversions.CreateAbsoluteDocumentUri(absolutePath); public static (string content, bool isMarkdown) CreateMarkdownContent(TextDocument document, QuickInfoItem info, XamlRequestContext context) { diff --git a/src/roslyn/src/Tools/ExternalAccess/Xaml/External/IResolveCachedDataService.cs b/src/roslyn/src/Tools/ExternalAccess/Xaml/External/IResolveCachedDataService.cs index a74ca5f4836..e37fd28c717 100644 --- a/src/roslyn/src/Tools/ExternalAccess/Xaml/External/IResolveCachedDataService.cs +++ b/src/roslyn/src/Tools/ExternalAccess/Xaml/External/IResolveCachedDataService.cs @@ -3,6 +3,7 @@ // See the LICENSE file in the project root for more information. using System; +using Roslyn.LanguageServer.Protocol; namespace Microsoft.CodeAnalysis.ExternalAccess.Xaml; @@ -14,6 +15,6 @@ namespace Microsoft.CodeAnalysis.ExternalAccess.Xaml; /// internal interface IResolveCachedDataService { - object ToResolveData(object data, Uri uri); - (object? data, Uri? uri) FromResolveData(object? resolveData); + object ToResolveData(object data, DocumentUri uri); + (object? data, DocumentUri? uri) FromResolveData(object? resolveData); } diff --git a/src/roslyn/src/Tools/ExternalAccess/Xaml/External/ResolveDataConversions.cs b/src/roslyn/src/Tools/ExternalAccess/Xaml/External/ResolveDataConversions.cs index bddbc65bb49..98ce5a2893c 100644 --- a/src/roslyn/src/Tools/ExternalAccess/Xaml/External/ResolveDataConversions.cs +++ b/src/roslyn/src/Tools/ExternalAccess/Xaml/External/ResolveDataConversions.cs @@ -17,24 +17,24 @@ internal static class ResolveDataConversions private record DataResolveData(object Data, LSP.TextDocumentIdentifier Document) : DocumentResolveData(Document); private record DataIdResolveData(long DataId, LSP.TextDocumentIdentifier Document) : DocumentResolveData(Document); - public static object ToResolveData(object data, Uri uri) - => new DataResolveData(data, new LSP.TextDocumentIdentifier { DocumentUri = new(uri) }); + public static object ToResolveData(object data, DocumentUri uri) + => new DataResolveData(data, new LSP.TextDocumentIdentifier { DocumentUri = uri }); - public static (object? data, Uri? uri) FromResolveData(object? requestData) + public static (object? data, DocumentUri? uri) FromResolveData(object? requestData) { Contract.ThrowIfNull(requestData); var resolveData = JsonSerializer.Deserialize((JsonElement)requestData); - return (resolveData?.Data, resolveData?.Document.DocumentUri.GetRequiredParsedUri()); + return (resolveData?.Data, resolveData?.Document.DocumentUri); } - internal static object ToCachedResolveData(object data, Uri uri, ResolveDataCache resolveDataCache) + internal static object ToCachedResolveData(object data, DocumentUri uri, ResolveDataCache resolveDataCache) { var dataId = resolveDataCache.UpdateCache(data); - return new DataIdResolveData(dataId, new LSP.TextDocumentIdentifier { DocumentUri = new(uri) }); + return new DataIdResolveData(dataId, new LSP.TextDocumentIdentifier { DocumentUri = uri }); } - internal static (object? data, Uri? uri) FromCachedResolveData(object? lspData, ResolveDataCache resolveDataCache) + internal static (object? data, DocumentUri? uri) FromCachedResolveData(object? lspData, ResolveDataCache resolveDataCache) { DataIdResolveData? resolveData; if (lspData is JsonElement token) @@ -50,6 +50,6 @@ internal static (object? data, Uri? uri) FromCachedResolveData(object? lspData, var data = resolveDataCache.GetCachedEntry(resolveData.DataId); var document = resolveData.Document; - return (data, document.DocumentUri.GetRequiredParsedUri()); + return (data, document.DocumentUri); } } diff --git a/src/roslyn/src/Tools/ExternalAccess/Xaml/External/XamlRequestContext.cs b/src/roslyn/src/Tools/ExternalAccess/Xaml/External/XamlRequestContext.cs index 2daefd1be36..6b8c85e3eb4 100644 --- a/src/roslyn/src/Tools/ExternalAccess/Xaml/External/XamlRequestContext.cs +++ b/src/roslyn/src/Tools/ExternalAccess/Xaml/External/XamlRequestContext.cs @@ -4,6 +4,7 @@ using System; using Microsoft.CodeAnalysis.LanguageServer.Handler; +using Roslyn.LanguageServer.Protocol; using LSP = Roslyn.LanguageServer.Protocol; namespace Microsoft.CodeAnalysis.ExternalAccess.Xaml; @@ -27,14 +28,14 @@ private XamlRequestContext(RequestContext context) [Obsolete("Use ClientCapabilities instead.")] public readonly IClientCapabilityProvider ClientCapabilityProvider => new ClientCapabilityProvider(_context.GetRequiredClientCapabilities()); - public object ToCachedResolveData(object data, Uri uri) + public object ToCachedResolveData(object data, DocumentUri uri) { var resolveDataCache = _context.GetRequiredLspService(); return ResolveDataConversions.ToCachedResolveData(data, uri, resolveDataCache); } - public (object? data, Uri? uri) FromCachedResolveData(object? lspData) + public (object? data, DocumentUri? uri) FromCachedResolveData(object? lspData) { var resolveDataCache = _context.GetRequiredLspService(); diff --git a/src/roslyn/src/Tools/ExternalAccess/Xaml/External/XamlRequestHandlerBase.cs b/src/roslyn/src/Tools/ExternalAccess/Xaml/External/XamlRequestHandlerBase.cs index d48c2dd7f4b..40cf39b97a4 100644 --- a/src/roslyn/src/Tools/ExternalAccess/Xaml/External/XamlRequestHandlerBase.cs +++ b/src/roslyn/src/Tools/ExternalAccess/Xaml/External/XamlRequestHandlerBase.cs @@ -25,9 +25,9 @@ public XamlRequestHandlerBase(IXamlRequestHandler? xamlRequ public bool RequiresLSPSolution => true; public LSP.TextDocumentIdentifier GetTextDocumentIdentifier(TRequest request) - => new() { DocumentUri = new(GetTextDocumentUri(request)) }; + => new() { DocumentUri = GetTextDocumentUri(request) }; - public abstract Uri GetTextDocumentUri(TRequest request); + public abstract DocumentUri GetTextDocumentUri(TRequest request); public Task HandleRequestAsync(TRequest request, RequestContext context, CancellationToken cancellationToken) => _xamlRequestHandler?.HandleRequestAsync(request, XamlRequestContext.FromRequestContext(context), cancellationToken) ?? throw new NotImplementedException(); diff --git a/src/roslyn/src/Tools/ExternalAccess/Xaml/External/XamlRequestHandlerFactoryBase.cs b/src/roslyn/src/Tools/ExternalAccess/Xaml/External/XamlRequestHandlerFactoryBase.cs index 1a054e1b2a2..05bc70cad00 100644 --- a/src/roslyn/src/Tools/ExternalAccess/Xaml/External/XamlRequestHandlerFactoryBase.cs +++ b/src/roslyn/src/Tools/ExternalAccess/Xaml/External/XamlRequestHandlerFactoryBase.cs @@ -5,6 +5,7 @@ using System; using Microsoft.CodeAnalysis.LanguageServer; using Microsoft.CodeAnalysis.LanguageServer.Handler; +using Roslyn.LanguageServer.Protocol; namespace Microsoft.CodeAnalysis.ExternalAccess.Xaml; @@ -36,10 +37,10 @@ public ResolveCachedDataService(ResolveDataCache resolveDataCache) _resolveDataCache = resolveDataCache ?? throw new ArgumentNullException(nameof(resolveDataCache)); } - public object ToResolveData(object data, Uri uri) + public object ToResolveData(object data, DocumentUri uri) => ResolveDataConversions.ToCachedResolveData(data, uri, _resolveDataCache); - public (object? data, Uri? uri) FromResolveData(object? lspData) + public (object? data, DocumentUri? uri) FromResolveData(object? lspData) => ResolveDataConversions.FromCachedResolveData(lspData, _resolveDataCache); } } diff --git a/src/roslyn/src/Tools/ExternalAccess/Xaml/InternalAPI.Unshipped.txt b/src/roslyn/src/Tools/ExternalAccess/Xaml/InternalAPI.Unshipped.txt index a135ca41126..a19de2f763e 100644 --- a/src/roslyn/src/Tools/ExternalAccess/Xaml/InternalAPI.Unshipped.txt +++ b/src/roslyn/src/Tools/ExternalAccess/Xaml/InternalAPI.Unshipped.txt @@ -1,4 +1,4 @@ -abstract Microsoft.CodeAnalysis.ExternalAccess.Xaml.XamlRequestHandlerBase.GetTextDocumentUri(TRequest request) -> System.Uri! +abstract Microsoft.CodeAnalysis.ExternalAccess.Xaml.XamlRequestHandlerBase.GetTextDocumentUri(TRequest request) -> Roslyn.LanguageServer.Protocol.DocumentUri! abstract Microsoft.CodeAnalysis.ExternalAccess.Xaml.XamlRequestHandlerFactoryBase.CreateHandler(Microsoft.CodeAnalysis.ExternalAccess.Xaml.IXamlRequestHandler? xamlRequestHandler, Microsoft.CodeAnalysis.ExternalAccess.Xaml.IResolveCachedDataService! resolveDataService) -> Microsoft.CodeAnalysis.ExternalAccess.Xaml.XamlRequestHandlerBase! const Microsoft.CodeAnalysis.ExternalAccess.Xaml.Constants.DiagnosticSourceProviderName = "XamlDiagnostics" -> string! const Microsoft.CodeAnalysis.ExternalAccess.Xaml.StringConstants.FactoryMethodMessage = "This factory method only provides services for the MEF export provider." -> string! @@ -40,8 +40,8 @@ Microsoft.CodeAnalysis.ExternalAccess.Xaml.ILocationService.GetSymbolLocationsAs Microsoft.CodeAnalysis.ExternalAccess.Xaml.IOnInitializedService Microsoft.CodeAnalysis.ExternalAccess.Xaml.IOnInitializedService.OnInitializedAsync(Microsoft.CodeAnalysis.ExternalAccess.Xaml.IClientRequestManager! clientRequestManager, Roslyn.LanguageServer.Protocol.ClientCapabilities! clientCapabilities, System.Threading.CancellationToken cancellationToken) -> System.Threading.Tasks.Task! Microsoft.CodeAnalysis.ExternalAccess.Xaml.IResolveCachedDataService -Microsoft.CodeAnalysis.ExternalAccess.Xaml.IResolveCachedDataService.FromResolveData(object? resolveData) -> (object? data, System.Uri? uri) -Microsoft.CodeAnalysis.ExternalAccess.Xaml.IResolveCachedDataService.ToResolveData(object! data, System.Uri! uri) -> object! +Microsoft.CodeAnalysis.ExternalAccess.Xaml.IResolveCachedDataService.FromResolveData(object? resolveData) -> (object? data, Roslyn.LanguageServer.Protocol.DocumentUri? uri) +Microsoft.CodeAnalysis.ExternalAccess.Xaml.IResolveCachedDataService.ToResolveData(object! data, Roslyn.LanguageServer.Protocol.DocumentUri! uri) -> object! Microsoft.CodeAnalysis.ExternalAccess.Xaml.IXamlDiagnosticSource Microsoft.CodeAnalysis.ExternalAccess.Xaml.IXamlDiagnosticSource.GetDiagnosticsAsync(Microsoft.CodeAnalysis.ExternalAccess.Xaml.XamlRequestContext context, System.Threading.CancellationToken cancellationToken) -> System.Threading.Tasks.Task>! Microsoft.CodeAnalysis.ExternalAccess.Xaml.IXamlRequestHandler @@ -67,9 +67,9 @@ Microsoft.CodeAnalysis.ExternalAccess.Xaml.XamlMethodAttribute.XamlMethodAttribu Microsoft.CodeAnalysis.ExternalAccess.Xaml.XamlRequestContext Microsoft.CodeAnalysis.ExternalAccess.Xaml.XamlRequestContext.ClientCapabilities.get -> Roslyn.LanguageServer.Protocol.ClientCapabilities! Microsoft.CodeAnalysis.ExternalAccess.Xaml.XamlRequestContext.ClientCapabilityProvider.get -> Microsoft.CodeAnalysis.ExternalAccess.Xaml.IClientCapabilityProvider! -Microsoft.CodeAnalysis.ExternalAccess.Xaml.XamlRequestContext.FromCachedResolveData(object? lspData) -> (object? data, System.Uri? uri) +Microsoft.CodeAnalysis.ExternalAccess.Xaml.XamlRequestContext.FromCachedResolveData(object? lspData) -> (object? data, Roslyn.LanguageServer.Protocol.DocumentUri? uri) Microsoft.CodeAnalysis.ExternalAccess.Xaml.XamlRequestContext.TextDocument.get -> Microsoft.CodeAnalysis.TextDocument? -Microsoft.CodeAnalysis.ExternalAccess.Xaml.XamlRequestContext.ToCachedResolveData(object! data, System.Uri! uri) -> object! +Microsoft.CodeAnalysis.ExternalAccess.Xaml.XamlRequestContext.ToCachedResolveData(object! data, Roslyn.LanguageServer.Protocol.DocumentUri! uri) -> object! Microsoft.CodeAnalysis.ExternalAccess.Xaml.XamlRequestContext.XamlRequestContext() -> void Microsoft.CodeAnalysis.ExternalAccess.Xaml.XamlRequestHandlerBase Microsoft.CodeAnalysis.ExternalAccess.Xaml.XamlRequestHandlerBase.GetTextDocumentIdentifier(TRequest request) -> Roslyn.LanguageServer.Protocol.TextDocumentIdentifier! @@ -80,11 +80,10 @@ Microsoft.CodeAnalysis.ExternalAccess.Xaml.XamlRequestHandlerBase Microsoft.CodeAnalysis.ExternalAccess.Xaml.XamlRequestHandlerFactoryBase.CreateILspService(Microsoft.CodeAnalysis.LanguageServer.LspServices! lspServices, Microsoft.CodeAnalysis.LanguageServer.WellKnownLspServerKinds serverKind) -> Microsoft.CodeAnalysis.LanguageServer.ILspService! Microsoft.CodeAnalysis.ExternalAccess.Xaml.XamlRequestHandlerFactoryBase.XamlRequestHandlerFactoryBase(Microsoft.CodeAnalysis.ExternalAccess.Xaml.IXamlRequestHandler? xamlRequestHandler) -> void -static Microsoft.CodeAnalysis.ExternalAccess.Xaml.ConversionHelpers.CreateAbsoluteUri(string! absolutePath) -> System.Uri! -static Microsoft.CodeAnalysis.ExternalAccess.Xaml.ConversionHelpers.CreateHoverResultAsync(Microsoft.CodeAnalysis.TextDocument! document, Microsoft.CodeAnalysis.QuickInfo.QuickInfoItem! info, Microsoft.CodeAnalysis.ExternalAccess.Xaml.XamlRequestContext context, System.Threading.CancellationToken cancellationToken) -> System.Threading.Tasks.Task! +static Microsoft.CodeAnalysis.ExternalAccess.Xaml.ConversionHelpers.CreateAbsoluteDocumentUri(string! absolutePath) -> Roslyn.LanguageServer.Protocol.DocumentUri! static Microsoft.CodeAnalysis.ExternalAccess.Xaml.ConversionHelpers.CreateMarkdownContent(Microsoft.CodeAnalysis.TextDocument! document, Microsoft.CodeAnalysis.QuickInfo.QuickInfoItem! info, Microsoft.CodeAnalysis.ExternalAccess.Xaml.XamlRequestContext context) -> (string! content, bool isMarkdown) -static Microsoft.CodeAnalysis.ExternalAccess.Xaml.ResolveDataConversions.FromCachedResolveData(object? lspData, Microsoft.CodeAnalysis.LanguageServer.Handler.ResolveDataCache! resolveDataCache) -> (object? data, System.Uri? uri) -static Microsoft.CodeAnalysis.ExternalAccess.Xaml.ResolveDataConversions.FromResolveData(object? requestData) -> (object? data, System.Uri? uri) -static Microsoft.CodeAnalysis.ExternalAccess.Xaml.ResolveDataConversions.ToCachedResolveData(object! data, System.Uri! uri, Microsoft.CodeAnalysis.LanguageServer.Handler.ResolveDataCache! resolveDataCache) -> object! -static Microsoft.CodeAnalysis.ExternalAccess.Xaml.ResolveDataConversions.ToResolveData(object! data, System.Uri! uri) -> object! +static Microsoft.CodeAnalysis.ExternalAccess.Xaml.ResolveDataConversions.FromCachedResolveData(object? lspData, Microsoft.CodeAnalysis.LanguageServer.Handler.ResolveDataCache! resolveDataCache) -> (object? data, Roslyn.LanguageServer.Protocol.DocumentUri? uri) +static Microsoft.CodeAnalysis.ExternalAccess.Xaml.ResolveDataConversions.FromResolveData(object? requestData) -> (object? data, Roslyn.LanguageServer.Protocol.DocumentUri? uri) +static Microsoft.CodeAnalysis.ExternalAccess.Xaml.ResolveDataConversions.ToCachedResolveData(object! data, Roslyn.LanguageServer.Protocol.DocumentUri! uri, Microsoft.CodeAnalysis.LanguageServer.Handler.ResolveDataCache! resolveDataCache) -> object! +static Microsoft.CodeAnalysis.ExternalAccess.Xaml.ResolveDataConversions.ToResolveData(object! data, Roslyn.LanguageServer.Protocol.DocumentUri! uri) -> object! static Microsoft.CodeAnalysis.ExternalAccess.Xaml.XamlRequestContext.FromRequestContext(Microsoft.CodeAnalysis.LanguageServer.Handler.RequestContext context) -> Microsoft.CodeAnalysis.ExternalAccess.Xaml.XamlRequestContext \ No newline at end of file diff --git a/src/roslyn/src/VisualStudio/CSharp/Test/DesignerAttribute/DesignerAttributeServiceTests.cs b/src/roslyn/src/VisualStudio/CSharp/Test/DesignerAttribute/DesignerAttributeServiceTests.cs index 49ac9488999..5ab513cc86b 100644 --- a/src/roslyn/src/VisualStudio/CSharp/Test/DesignerAttribute/DesignerAttributeServiceTests.cs +++ b/src/roslyn/src/VisualStudio/CSharp/Test/DesignerAttribute/DesignerAttributeServiceTests.cs @@ -5,6 +5,7 @@ using System.Linq; using System.Threading; using System.Threading.Tasks; +using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.DesignerAttribute; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Test.Utilities; diff --git a/src/roslyn/src/VisualStudio/CSharp/Test/DocumentOutline/DocumentOutlineTestsBase.cs b/src/roslyn/src/VisualStudio/CSharp/Test/DocumentOutline/DocumentOutlineTestsBase.cs index d0e17de34c5..87819c159de 100644 --- a/src/roslyn/src/VisualStudio/CSharp/Test/DocumentOutline/DocumentOutlineTestsBase.cs +++ b/src/roslyn/src/VisualStudio/CSharp/Test/DocumentOutline/DocumentOutlineTestsBase.cs @@ -5,6 +5,7 @@ using System.Collections.Generic; using System.Linq; using System.Runtime.Serialization; +using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; @@ -19,9 +20,8 @@ using Microsoft.VisualStudio.LanguageServer.Client; using Microsoft.VisualStudio.LanguageServices.DocumentOutline; using Microsoft.VisualStudio.Text; -using Roslyn.LanguageServer.Protocol; using Roslyn.Test.Utilities; -using StreamJsonRpc; +using Roslyn.Utilities; using Xunit.Abstractions; using static Roslyn.Test.Utilities.AbstractLanguageServerProtocolTests; using IAsyncDisposable = System.IAsyncDisposable; @@ -31,8 +31,6 @@ namespace Roslyn.VisualStudio.CSharp.UnitTests.DocumentOutline; [UseExportProvider] public abstract class DocumentOutlineTestsBase { - private const string PathRoot = "C:\\\ue25b\\"; - private readonly TestOutputLspLogger _logger; protected DocumentOutlineTestsBase(ITestOutputHelper testOutputHelper) { @@ -64,7 +62,7 @@ internal DocumentOutlineTestMocks( internal ITextBuffer TextBuffer { get; } internal string FilePath - => PathRoot + _workspace.Documents.Single().FilePath!; + => _workspace.Documents.Single().FilePath!; public ValueTask DisposeAsync() => _disposable.DisposeAsync(); @@ -97,30 +95,10 @@ protected async Task CreateMocksAsync(string code) private async Task CreateTestLspServerAsync(EditorTestWorkspace workspace) { - var solution = workspace.CurrentSolution; - - foreach (var document in workspace.Documents) - { - if (document.IsSourceGenerated) - continue; - - solution = solution.WithDocumentFilePath(document.Id, PathRoot + document.Name); - - var documentText = await solution.GetRequiredDocument(document.Id).GetTextAsync(CancellationToken.None); - solution = solution.WithDocumentText(document.Id, SourceText.From(documentText.ToString(), System.Text.Encoding.UTF8)); - } - - foreach (var project in workspace.Projects) - { - // Ensure all the projects have a valid file path. - solution = solution.WithProjectFilePath(project.Id, PathRoot + project.Name); - } - - solution = solution.WithAnalyzerReferences([new TestAnalyzerReferenceByLanguage(DiagnosticExtensions.GetCompilerDiagnosticAnalyzersMap())]); - await workspace.ChangeSolutionAsync(solution); + await workspace.ChangeSolutionAsync( + workspace.CurrentSolution.WithAnalyzerReferences([new TestAnalyzerReferenceByLanguage(DiagnosticExtensions.GetCompilerDiagnosticAnalyzersMap())])); - var server = await EditorTestLspServer.CreateAsync(workspace, new InitializationOptions(), _logger); - return server; + return await EditorTestLspServer.CreateAsync(workspace, new InitializationOptions(), _logger); } internal sealed class EditorTestLspServer : AbstractTestLspServer diff --git a/src/roslyn/src/VisualStudio/CodeLens/ReferenceCodeLensProvider.cs b/src/roslyn/src/VisualStudio/CodeLens/ReferenceCodeLensProvider.cs index c05b0582d6a..76c74fd6474 100644 --- a/src/roslyn/src/VisualStudio/CodeLens/ReferenceCodeLensProvider.cs +++ b/src/roslyn/src/VisualStudio/CodeLens/ReferenceCodeLensProvider.cs @@ -11,6 +11,7 @@ using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CodeLens; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.Editor; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.LanguageServer; diff --git a/src/roslyn/src/VisualStudio/Core/Def/Utilities/AutomationDelegatingListView.cs b/src/roslyn/src/VisualStudio/Core/Def/Utilities/AutomationDelegatingListView.cs index fc644311833..831c47f1349 100644 --- a/src/roslyn/src/VisualStudio/Core/Def/Utilities/AutomationDelegatingListView.cs +++ b/src/roslyn/src/VisualStudio/Core/Def/Utilities/AutomationDelegatingListView.cs @@ -3,15 +3,15 @@ // See the LICENSE file in the project root for more information. extern alias slowautomation; - using System.Collections.Generic; using System.Linq; using System.Windows; -using slowautomation::System.Windows.Automation; using System.Windows.Automation.Peers; using System.Windows.Controls; using System.Windows.Input; +using Microsoft.CodeAnalysis.Collections; using Roslyn.Utilities; +using slowautomation::System.Windows.Automation; namespace Microsoft.VisualStudio.LanguageServices.Implementation.Utilities; diff --git a/src/roslyn/src/VisualStudio/Core/Impl/CodeModel/AbstractCodeModelService.cs b/src/roslyn/src/VisualStudio/Core/Impl/CodeModel/AbstractCodeModelService.cs index 0859fa370db..a9131b1c901 100644 --- a/src/roslyn/src/VisualStudio/Core/Impl/CodeModel/AbstractCodeModelService.cs +++ b/src/roslyn/src/VisualStudio/Core/Impl/CodeModel/AbstractCodeModelService.cs @@ -11,6 +11,7 @@ using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CodeGeneration; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Editor; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; diff --git a/src/roslyn/src/VisualStudio/Core/Test.Next/Options/VisualStudioOptionStorageTests.cs b/src/roslyn/src/VisualStudio/Core/Test.Next/Options/VisualStudioOptionStorageTests.cs index 69bdea12dfb..45277c3e2aa 100644 --- a/src/roslyn/src/VisualStudio/Core/Test.Next/Options/VisualStudioOptionStorageTests.cs +++ b/src/roslyn/src/VisualStudio/Core/Test.Next/Options/VisualStudioOptionStorageTests.cs @@ -236,6 +236,7 @@ public void OptionHasStorageIfNecessary(string configName) "dotnet_style_prefer_foreach_explicit_cast_in_source", // For a small customer segment, doesn't warrant VS UI. "dotnet_binary_log_path", // VSCode only option for the VS Code project system; does not apply to VS "dotnet_enable_automatic_restore", // VSCode only option for the VS Code project system; does not apply to VS + "dotnet_enable_file_based_programs", // VSCode only option for the VS Code project system; does not apply to VS "dotnet_lsp_using_devkit", // VSCode internal only option. Does not need any UI. "dotnet_enable_references_code_lens", // VSCode only option. Does not apply to VS. "dotnet_enable_tests_code_lens", // VSCode only option. Does not apply to VS. diff --git a/src/roslyn/src/VisualStudio/Core/Test/CodeModel/CSharp/RootCodeModelTests.vb b/src/roslyn/src/VisualStudio/Core/Test/CodeModel/CSharp/RootCodeModelTests.vb index 594df394db8..1dabe997b83 100644 --- a/src/roslyn/src/VisualStudio/Core/Test/CodeModel/CSharp/RootCodeModelTests.vb +++ b/src/roslyn/src/VisualStudio/Core/Test/CodeModel/CSharp/RootCodeModelTests.vb @@ -2,6 +2,7 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. +Imports System.IO Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel @@ -176,7 +177,7 @@ namespace N Assert.NotNull(underlyingFileCodeModel) Dim filePath = underlyingFileCodeModel.Workspace.GetFilePath(underlyingFileCodeModel.GetDocumentId()) - Assert.Equal("C.cs", filePath) + Assert.Equal(Path.Combine(TestWorkspace.RootDirectory, "C.cs"), filePath) End Sub) End Sub @@ -213,7 +214,7 @@ namespace N Assert.NotNull(underlyingFileCodeModel) Dim filePath = underlyingFileCodeModel.Workspace.GetFilePath(underlyingFileCodeModel.GetDocumentId()) - Assert.Equal("C.g.cs", filePath) + Assert.Equal(Path.Combine(TestWorkspace.RootDirectory, "C.g.cs"), filePath) End Sub) End Sub @@ -258,7 +259,7 @@ namespace N Assert.NotNull(underlyingFileCodeModel) Dim filePath = underlyingFileCodeModel.Workspace.GetFilePath(underlyingFileCodeModel.GetDocumentId()) - Assert.Equal("C.cs", filePath) + Assert.Equal(Path.Combine(TestWorkspace.RootDirectory, "C.cs"), filePath) End Sub) End Sub @@ -303,7 +304,7 @@ namespace N Assert.NotNull(underlyingFileCodeModel) Dim filePath = underlyingFileCodeModel.Workspace.GetFilePath(underlyingFileCodeModel.GetDocumentId()) - Assert.Equal("C.cs", filePath) + Assert.Equal(Path.Combine(TestWorkspace.RootDirectory, "C.cs"), filePath) End Sub) End Sub diff --git a/src/roslyn/src/VisualStudio/Core/Test/CodeModel/VisualBasic/RootCodeModelTests.vb b/src/roslyn/src/VisualStudio/Core/Test/CodeModel/VisualBasic/RootCodeModelTests.vb index e1cad09cec8..6d59e00d61b 100644 --- a/src/roslyn/src/VisualStudio/Core/Test/CodeModel/VisualBasic/RootCodeModelTests.vb +++ b/src/roslyn/src/VisualStudio/Core/Test/CodeModel/VisualBasic/RootCodeModelTests.vb @@ -2,6 +2,7 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. +Imports System.IO Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel @@ -111,7 +112,7 @@ End Namespace Assert.NotNull(underlyingFileCodeModel) Dim filePath = underlyingFileCodeModel.Workspace.GetFilePath(underlyingFileCodeModel.GetDocumentId()) - Assert.Equal("C.vb", filePath) + Assert.Equal(Path.Combine(TestWorkspace.RootDirectory, "C.vb"), filePath) End Sub) End Sub @@ -146,7 +147,7 @@ End Namespace Assert.NotNull(underlyingFileCodeModel) Dim filePath = underlyingFileCodeModel.Workspace.GetFilePath(underlyingFileCodeModel.GetDocumentId()) - Assert.Equal("C.g.vb", filePath) + Assert.Equal(Path.Combine(TestWorkspace.RootDirectory, "C.g.vb"), filePath) End Sub) End Sub @@ -187,7 +188,7 @@ End Namespace Assert.NotNull(underlyingFileCodeModel) Dim filePath = underlyingFileCodeModel.Workspace.GetFilePath(underlyingFileCodeModel.GetDocumentId()) - Assert.Equal("C.vb", filePath) + Assert.Equal(Path.Combine(TestWorkspace.RootDirectory, "C.vb"), filePath) End Sub) End Sub @@ -228,7 +229,7 @@ End Namespace Assert.NotNull(underlyingFileCodeModel) Dim filePath = underlyingFileCodeModel.Workspace.GetFilePath(underlyingFileCodeModel.GetDocumentId()) - Assert.Equal("C.vb", filePath) + Assert.Equal(Path.Combine(TestWorkspace.RootDirectory, "C.vb"), filePath) End Sub) End Sub diff --git a/src/roslyn/src/VisualStudio/Core/Test/MoveStaticMembers/MoveStaticMembersViewModelTest.vb b/src/roslyn/src/VisualStudio/Core/Test/MoveStaticMembers/MoveStaticMembersViewModelTest.vb index 65f171ebd2b..7c21c5d629c 100644 --- a/src/roslyn/src/VisualStudio/Core/Test/MoveStaticMembers/MoveStaticMembersViewModelTest.vb +++ b/src/roslyn/src/VisualStudio/Core/Test/MoveStaticMembers/MoveStaticMembersViewModelTest.vb @@ -3,6 +3,7 @@ ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable +Imports System.IO Imports System.Threading Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces @@ -106,7 +107,7 @@ Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.MoveStaticMembers Dim options = VisualStudioMoveStaticMembersOptionsService.GenerateOptions(LanguageNames.CSharp, viewModel, True) Assert.False(options.IsCancelled) - Assert.Equal("TestClassHelpers.cs", options.FileName) + Assert.Equal("TestClassHelpers.cs", options.FilePath) Assert.Equal("TestClassHelpers", options.TypeName) Assert.Equal("TestNs.ExtraNs", options.NamespaceDisplay) End Function @@ -425,7 +426,7 @@ Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.MoveStaticMembers Assert.False(options.IsCancelled) Assert.NotNull(options.Destination) Assert.Equal("TestNs.ConflictingClassName", options.Destination.ToDisplayString()) - Assert.Equal("TestFile.cs", options.FileName) + Assert.Equal(Path.Combine(TestWorkspace.RootDirectory, "TestFile.cs"), options.FilePath) End Function @@ -550,7 +551,7 @@ Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.MoveStaticMembers Dim options = VisualStudioMoveStaticMembersOptionsService.GenerateOptions(LanguageNames.VisualBasic, viewModel, True) Assert.False(options.IsCancelled) - Assert.Equal("TestClassHelpers.vb", options.FileName) + Assert.Equal("TestClassHelpers.vb", options.FilePath) Assert.Equal("TestClassHelpers", options.TypeName) Assert.Equal("TestNs.ExtraNs", options.NamespaceDisplay) End Function @@ -865,7 +866,7 @@ Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.MoveStaticMembers Assert.False(options.IsCancelled) Assert.NotNull(options.Destination) Assert.Equal("TestNs.ConflictingClassName", options.Destination.ToDisplayString()) - Assert.Equal("TestFile.vb", options.FileName) + Assert.Equal(Path.Combine(TestWorkspace.RootDirectory, "TestFile.vb"), options.FilePath) End Function #End Region End Class diff --git a/src/roslyn/src/VisualStudio/Core/Test/Progression/InheritsFromGraphQueryTests.vb b/src/roslyn/src/VisualStudio/Core/Test/Progression/InheritsFromGraphQueryTests.vb index 8379a19d621..1faa562860c 100644 --- a/src/roslyn/src/VisualStudio/Core/Test/Progression/InheritsFromGraphQueryTests.vb +++ b/src/roslyn/src/VisualStudio/Core/Test/Progression/InheritsFromGraphQueryTests.vb @@ -2,7 +2,9 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. +Imports System.IO Imports System.Threading.Tasks +Imports Microsoft.CodeAnalysis.LanguageServer Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.VisualStudio.GraphModel Imports Microsoft.VisualStudio.LanguageServices.Implementation.Progression @@ -79,21 +81,23 @@ Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.Progression Using testState = ProgressionTestState.Create( - public class A { } + public class A { } ProjectA - public class B : A { } + public class B : A { } ProjectB - public class C : B$$ { } + public class C : B$$ { } ) Dim inputGraph = Await testState.GetGraphWithMarkedSymbolNodeAsync() Dim outputContext = Await testState.GetGraphContextAfterQuery(inputGraph, New InheritsGraphQuery(), GraphContextDirection.Target) + Dim dirUri = ProtocolConversions.GetAbsoluteUriString(Path.Combine(TestWorkspace.RootDirectory, "bin")) & "/" + AssertSimplifiedGraphIs( outputContext.Graph, @@ -105,8 +109,8 @@ Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.Progression - - + /> + /> ) End Using diff --git a/src/roslyn/src/VisualStudio/Core/Test/Snippets/SnippetCompletionProviderTests.vb b/src/roslyn/src/VisualStudio/Core/Test/Snippets/SnippetCompletionProviderTests.vb index 403f1480ad5..a81ea2457c8 100644 --- a/src/roslyn/src/VisualStudio/Core/Test/Snippets/SnippetCompletionProviderTests.vb +++ b/src/roslyn/src/VisualStudio/Core/Test/Snippets/SnippetCompletionProviderTests.vb @@ -4,6 +4,7 @@ Imports System.Composition Imports Microsoft.CodeAnalysis +Imports Microsoft.CodeAnalysis.Collections Imports Microsoft.CodeAnalysis.Completion Imports Microsoft.CodeAnalysis.Host.Mef Imports Microsoft.CodeAnalysis.LanguageService diff --git a/src/roslyn/src/VisualStudio/Core/Test/SolutionExplorer/CpsDiagnosticItemSourceTests.vb b/src/roslyn/src/VisualStudio/Core/Test/SolutionExplorer/CpsDiagnosticItemSourceTests.vb index fd1a95b6ad9..95bb70cf9d4 100644 --- a/src/roslyn/src/VisualStudio/Core/Test/SolutionExplorer/CpsDiagnosticItemSourceTests.vb +++ b/src/roslyn/src/VisualStudio/Core/Test/SolutionExplorer/CpsDiagnosticItemSourceTests.vb @@ -3,10 +3,12 @@ ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable +Imports System.IO Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Diagnostics Imports Microsoft.CodeAnalysis.Editor.[Shared].Utilities Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces +Imports Microsoft.CodeAnalysis.Host Imports Microsoft.CodeAnalysis.[Shared].TestHooks Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.Internal.VisualStudio.PlatformUI @@ -44,7 +46,7 @@ Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.SolutionExplorer workspace, project.FilePath, project.Id, - New MockHierarchyItem() With {.CanonicalName = "\net472\analyzerdependency\" + analyzerPath}, + New MockHierarchyItem() With {.CanonicalName = Path.Combine(TestWorkspace.RootDirectory, "net472", "analyzerdependency") + "\" + analyzerPath}, New FakeAnalyzersCommandHandler(), listenerProvider) diff --git a/src/roslyn/src/VisualStudio/Core/Test/Venus/CSharpContainedLanguageSupportTests.vb b/src/roslyn/src/VisualStudio/Core/Test/Venus/CSharpContainedLanguageSupportTests.vb index 3424c5471b4..88dc3dad88b 100644 --- a/src/roslyn/src/VisualStudio/Core/Test/Venus/CSharpContainedLanguageSupportTests.vb +++ b/src/roslyn/src/VisualStudio/Core/Test/Venus/CSharpContainedLanguageSupportTests.vb @@ -4,6 +4,7 @@ Imports System.Threading Imports Microsoft.CodeAnalysis +Imports Microsoft.CodeAnalysis.Collections Imports Microsoft.CodeAnalysis.Editor Imports Microsoft.CodeAnalysis.Editor.UnitTests.Extensions Imports Microsoft.CodeAnalysis.Test.Utilities diff --git a/src/roslyn/src/VisualStudio/Core/Test/Venus/DocumentService_IntegrationTests.vb b/src/roslyn/src/VisualStudio/Core/Test/Venus/DocumentService_IntegrationTests.vb index 2aec249ad56..aa8daa875ec 100644 --- a/src/roslyn/src/VisualStudio/Core/Test/Venus/DocumentService_IntegrationTests.vb +++ b/src/roslyn/src/VisualStudio/Core/Test/Venus/DocumentService_IntegrationTests.vb @@ -41,7 +41,7 @@ Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.Venus Private Shared ReadOnly s_compositionWithMockDiagnosticUpdateSourceRegistrationService As TestComposition = EditorTestCompositions.EditorFeatures - Public Async Function TestFindUsageIntegration() As System.Threading.Tasks.Task + Public Async Function TestFindUsageIntegration() As Task Dim input = @@ -87,8 +87,9 @@ class {|Definition:C1|} Dim definitionSpan = definitionDocument.AnnotatedSpans("Definition").Single() Dim referenceSpan = definitionDocument.SelectedSpans.First() Dim expected = { - (definitionDocument.Name, definitionText.Lines.GetLinePositionSpan(definitionSpan).Start, definitionText.Lines.GetLineFromPosition(definitionSpan.Start).ToString().Trim()), - (definitionDocument.Name, definitionText.Lines.GetLinePositionSpan(referenceSpan).Start, definitionText.Lines.GetLineFromPosition(referenceSpan.Start).ToString().Trim())} + (definitionDocument.FilePath, definitionText.Lines.GetLinePositionSpan(definitionSpan).Start, definitionText.Lines.GetLineFromPosition(definitionSpan.Start).ToString().Trim()), + (definitionDocument.FilePath, definitionText.Lines.GetLinePositionSpan(referenceSpan).Start, definitionText.Lines.GetLineFromPosition(referenceSpan.Start).ToString().Trim()) + } Dim factory = TestFindAllReferencesService.Instance.LastWindow.MyTableManager.LastSink.LastFactory Dim snapshot = factory.GetCurrentSnapshot() @@ -115,7 +116,7 @@ class {|Definition:C1|} End Function - Public Async Function TestCodeLensIntegration() As System.Threading.Tasks.Task + Public Async Function TestCodeLensIntegration() As Task Dim input = @@ -152,7 +153,9 @@ class {|Definition:C1|} Dim definitionText = Await workspace.CurrentSolution.GetDocument(definitionDocument.Id).GetTextAsync() Dim referenceSpan = definitionDocument.SelectedSpans.First() - Dim expected = {(definitionDocument.Name, definitionText.Lines.GetLinePositionSpan(referenceSpan).Start, definitionText.Lines.GetLineFromPosition(referenceSpan.Start).ToString())} + Dim expected = { + (definitionDocument.FilePath, definitionText.Lines.GetLinePositionSpan(referenceSpan).Start, definitionText.Lines.GetLineFromPosition(referenceSpan.Start).ToString()) + } Dim actual = New List(Of (String, LinePosition, String)) @@ -168,7 +171,7 @@ class {|Definition:C1|} - Public Async Function TestDocumentOperationCanApplyChange(ignoreUnchangeableDocuments As Boolean) As System.Threading.Tasks.Task + Public Async Function TestDocumentOperationCanApplyChange(ignoreUnchangeableDocuments As Boolean) As Task Dim input = @@ -208,7 +211,7 @@ class C { } End Function - Public Async Function TestDocumentOperationCanApplySupportDiagnostics() As System.Threading.Tasks.Task + Public Async Function TestDocumentOperationCanApplySupportDiagnostics() As Task Dim input = diff --git a/src/roslyn/src/VisualStudio/Core/Test/Venus/VisualBasicContainedLanguageSupportTests.vb b/src/roslyn/src/VisualStudio/Core/Test/Venus/VisualBasicContainedLanguageSupportTests.vb index f142815dc28..1be586c271a 100644 --- a/src/roslyn/src/VisualStudio/Core/Test/Venus/VisualBasicContainedLanguageSupportTests.vb +++ b/src/roslyn/src/VisualStudio/Core/Test/Venus/VisualBasicContainedLanguageSupportTests.vb @@ -4,6 +4,7 @@ Imports System.Threading Imports Microsoft.CodeAnalysis +Imports Microsoft.CodeAnalysis.Collections Imports Microsoft.CodeAnalysis.Editor Imports Microsoft.CodeAnalysis.Editor.UnitTests.Extensions Imports Microsoft.CodeAnalysis.Editor.VisualBasic.Utilities diff --git a/src/roslyn/src/VisualStudio/ExternalAccess/FSharp/Editor/FSharpNavigationBarItem.cs b/src/roslyn/src/VisualStudio/ExternalAccess/FSharp/Editor/FSharpNavigationBarItem.cs index 0cab98f3253..fbe16f91e99 100644 --- a/src/roslyn/src/VisualStudio/ExternalAccess/FSharp/Editor/FSharpNavigationBarItem.cs +++ b/src/roslyn/src/VisualStudio/ExternalAccess/FSharp/Editor/FSharpNavigationBarItem.cs @@ -5,6 +5,7 @@ #nullable disable using System.Collections.Generic; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Text; using Roslyn.Utilities; diff --git a/src/roslyn/src/VisualStudio/ExternalAccess/FSharp/Internal/Editor/FSharpNavigationBarItemService.cs b/src/roslyn/src/VisualStudio/ExternalAccess/FSharp/Internal/Editor/FSharpNavigationBarItemService.cs index bb55e9adb95..588640960a8 100644 --- a/src/roslyn/src/VisualStudio/ExternalAccess/FSharp/Internal/Editor/FSharpNavigationBarItemService.cs +++ b/src/roslyn/src/VisualStudio/ExternalAccess/FSharp/Internal/Editor/FSharpNavigationBarItemService.cs @@ -9,6 +9,7 @@ using System.Linq; using System.Threading; using System.Threading.Tasks; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.Editor; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.ExternalAccess.FSharp.Editor; diff --git a/src/roslyn/src/VisualStudio/VisualBasic/Impl/CodeModel/VisualBasicCodeModelService.vb b/src/roslyn/src/VisualStudio/VisualBasic/Impl/CodeModel/VisualBasicCodeModelService.vb index 48046032023..4647c60471c 100644 --- a/src/roslyn/src/VisualStudio/VisualBasic/Impl/CodeModel/VisualBasicCodeModelService.vb +++ b/src/roslyn/src/VisualStudio/VisualBasic/Impl/CodeModel/VisualBasicCodeModelService.vb @@ -6,6 +6,7 @@ Imports System.Text Imports System.Threading Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.CodeGeneration +Imports Microsoft.CodeAnalysis.Collections Imports Microsoft.CodeAnalysis.Editor Imports Microsoft.CodeAnalysis.Editor.Shared.Utilities Imports Microsoft.CodeAnalysis.Editor.VisualBasic.LineCommit diff --git a/src/roslyn/src/VisualStudio/VisualBasic/Impl/Venus/ContainedLanguageStaticEventBinding.vb b/src/roslyn/src/VisualStudio/VisualBasic/Impl/Venus/ContainedLanguageStaticEventBinding.vb index 94bcc886757..bbfaca0e3ff 100644 --- a/src/roslyn/src/VisualStudio/VisualBasic/Impl/Venus/ContainedLanguageStaticEventBinding.vb +++ b/src/roslyn/src/VisualStudio/VisualBasic/Impl/Venus/ContainedLanguageStaticEventBinding.vb @@ -4,6 +4,7 @@ Imports System.Threading Imports Microsoft.CodeAnalysis +Imports Microsoft.CodeAnalysis.Collections Imports Microsoft.CodeAnalysis.LanguageService Imports Microsoft.CodeAnalysis.Shared.Extensions Imports Microsoft.CodeAnalysis.Text diff --git a/src/roslyn/src/Workspaces/Core/Portable/FindSymbols/FindReferences/DependentTypeFinder.cs b/src/roslyn/src/Workspaces/Core/Portable/FindSymbols/FindReferences/DependentTypeFinder.cs index 1c86e9ee4a4..abd911f656e 100644 --- a/src/roslyn/src/Workspaces/Core/Portable/FindSymbols/FindReferences/DependentTypeFinder.cs +++ b/src/roslyn/src/Workspaces/Core/Portable/FindSymbols/FindReferences/DependentTypeFinder.cs @@ -10,6 +10,7 @@ using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.Utilities; diff --git a/src/roslyn/src/Workspaces/Core/Portable/Formatting/Formatter.cs b/src/roslyn/src/Workspaces/Core/Portable/Formatting/Formatter.cs index 0af997b7d48..f793f2098f8 100644 --- a/src/roslyn/src/Workspaces/Core/Portable/Formatting/Formatter.cs +++ b/src/roslyn/src/Workspaces/Core/Portable/Formatting/Formatter.cs @@ -7,6 +7,7 @@ using System.Collections.Immutable; using System.Threading; using System.Threading.Tasks; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.Formatting.Rules; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Options; diff --git a/src/roslyn/src/Workspaces/Core/Portable/Microsoft.CodeAnalysis.Workspaces.csproj b/src/roslyn/src/Workspaces/Core/Portable/Microsoft.CodeAnalysis.Workspaces.csproj index 15f533b000a..62b8d4de443 100644 --- a/src/roslyn/src/Workspaces/Core/Portable/Microsoft.CodeAnalysis.Workspaces.csproj +++ b/src/roslyn/src/Workspaces/Core/Portable/Microsoft.CodeAnalysis.Workspaces.csproj @@ -167,6 +167,7 @@ + diff --git a/src/roslyn/src/Workspaces/Core/Portable/Recommendations/AbstractRecommendationService.cs b/src/roslyn/src/Workspaces/Core/Portable/Recommendations/AbstractRecommendationService.cs index b347cedebee..04f43188acc 100644 --- a/src/roslyn/src/Workspaces/Core/Portable/Recommendations/AbstractRecommendationService.cs +++ b/src/roslyn/src/Workspaces/Core/Portable/Recommendations/AbstractRecommendationService.cs @@ -6,6 +6,7 @@ using System.Collections.Immutable; using System.Linq; using System.Threading; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.Extensions.ContextQuery; using Roslyn.Utilities; diff --git a/src/roslyn/src/Workspaces/Core/Portable/Workspace/Solution/ProjectInfo.cs b/src/roslyn/src/Workspaces/Core/Portable/Workspace/Solution/ProjectInfo.cs index dadb0b59604..62b4497bb47 100644 --- a/src/roslyn/src/Workspaces/Core/Portable/Workspace/Solution/ProjectInfo.cs +++ b/src/roslyn/src/Workspaces/Core/Portable/Workspace/Solution/ProjectInfo.cs @@ -6,6 +6,7 @@ using System.Collections.Generic; using System.Diagnostics; using System.Text.RegularExpressions; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; diff --git a/src/roslyn/src/Workspaces/Core/Portable/Workspace/Solution/Solution.cs b/src/roslyn/src/Workspaces/Core/Portable/Workspace/Solution/Solution.cs index f2087991393..e219806aa4d 100644 --- a/src/roslyn/src/Workspaces/Core/Portable/Workspace/Solution/Solution.cs +++ b/src/roslyn/src/Workspaces/Core/Portable/Workspace/Solution/Solution.cs @@ -986,6 +986,8 @@ public Solution AddDocument(DocumentId documentId, string name, SyntaxNode synta throw new ArgumentNullException(nameof(syntaxRoot)); var project = GetRequiredProjectState(documentId.ProjectId); + + // The empty text is replaced in WithDocumentSyntaxRoot with the actual text that matches the syntax tree. var sourceText = SourceText.From(string.Empty, encoding: null, project.ChecksumAlgorithm); return AddDocumentImpl(project, documentId, name, sourceText, PublicContract.ToBoxedImmutableArrayWithNonNullItems(folders, nameof(folders)), filePath, isGenerated). diff --git a/src/roslyn/src/Workspaces/Core/Portable/Workspace/Solution/SolutionState.cs b/src/roslyn/src/Workspaces/Core/Portable/Workspace/Solution/SolutionState.cs index cb879e94737..307f2a3cf64 100644 --- a/src/roslyn/src/Workspaces/Core/Portable/Workspace/Solution/SolutionState.cs +++ b/src/roslyn/src/Workspaces/Core/Portable/Workspace/Solution/SolutionState.cs @@ -9,6 +9,7 @@ using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Host; diff --git a/src/roslyn/src/Workspaces/CoreTest/CodeCleanup/CodeCleanupTests.cs b/src/roslyn/src/Workspaces/CoreTest/CodeCleanup/CodeCleanupTests.cs index d3d6f9466bf..892d6804e01 100644 --- a/src/roslyn/src/Workspaces/CoreTest/CodeCleanup/CodeCleanupTests.cs +++ b/src/roslyn/src/Workspaces/CoreTest/CodeCleanup/CodeCleanupTests.cs @@ -11,6 +11,7 @@ using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeCleanup; using Microsoft.CodeAnalysis.CodeCleanup.Providers; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; diff --git a/src/roslyn/src/Workspaces/CoreTest/SolutionTests/SolutionTests.cs b/src/roslyn/src/Workspaces/CoreTest/SolutionTests/SolutionTests.cs index a9c341632e6..2b040629dcc 100644 --- a/src/roslyn/src/Workspaces/CoreTest/SolutionTests/SolutionTests.cs +++ b/src/roslyn/src/Workspaces/CoreTest/SolutionTests/SolutionTests.cs @@ -2501,7 +2501,7 @@ public void AddDocument_SyntaxRoot_ExplicitTree() var filePath = Path.Combine(TempRoot.Root, "x.cs"); var folders = new[] { "folder1", "folder2" }; - var root = CSharp.SyntaxFactory.ParseSyntaxTree(SourceText.From("class C {}", encoding: null, SourceHashAlgorithm.Sha1)).GetRoot(); + var root = CSharp.SyntaxFactory.ParseSyntaxTree(SourceText.From("class C {}", encoding: Encoding.ASCII, SourceHashAlgorithm.Sha1)).GetRoot(); Assert.Equal(SourceHashAlgorithm.Sha1, root.SyntaxTree.GetText().ChecksumAlgorithm); var solution2 = solution.AddDocument(documentId, "name", root, folders, filePath); @@ -2512,6 +2512,9 @@ public void AddDocument_SyntaxRoot_ExplicitTree() // the checksum algorithm of the tree is ignored, instead the one set on the project is used: Assert.Equal(SourceHashAlgorithms.Default, sourceText.ChecksumAlgorithm); + // the encoding is preserved: + Assert.Equal(Encoding.ASCII, sourceText.Encoding); + AssertEx.Equal(folders, document2.Folders); Assert.Equal(filePath, document2.FilePath); Assert.False(document2.State.Attributes.IsGenerated); diff --git a/src/roslyn/src/Workspaces/CoreTest/UtilityTest/SpecializedTasksTests.cs b/src/roslyn/src/Workspaces/CoreTest/UtilityTest/SpecializedTasksTests.cs index 1cfcaef886b..ed9cd1bde4d 100644 --- a/src/roslyn/src/Workspaces/CoreTest/UtilityTest/SpecializedTasksTests.cs +++ b/src/roslyn/src/Workspaces/CoreTest/UtilityTest/SpecializedTasksTests.cs @@ -8,6 +8,7 @@ using System.Diagnostics.CodeAnalysis; using System.Threading; using System.Threading.Tasks; +using Microsoft.CodeAnalysis.Collections; using Roslyn.Utilities; using Xunit; diff --git a/src/roslyn/src/Workspaces/CoreTestUtilities/SolutionUtilities.cs b/src/roslyn/src/Workspaces/CoreTestUtilities/SolutionUtilities.cs index 228cb2057c9..5457e905eb8 100644 --- a/src/roslyn/src/Workspaces/CoreTestUtilities/SolutionUtilities.cs +++ b/src/roslyn/src/Workspaces/CoreTestUtilities/SolutionUtilities.cs @@ -69,7 +69,7 @@ public static Document GetSingleAddedDocument(Solution oldSolution, Solution new var projectDifferences = GetSingleChangedProjectChanges(oldSolution, newSolution); var documentId = projectDifferences.GetAddedDocuments().Single(); - return newSolution.GetDocument(documentId)!; + return newSolution.GetRequiredDocument(documentId); } public static IEnumerable GetTextChangedDocuments(Solution oldSolution, Solution newSolution) diff --git a/src/roslyn/src/Workspaces/CoreTestUtilities/Workspaces/TestHostDocument.cs b/src/roslyn/src/Workspaces/CoreTestUtilities/Workspaces/TestHostDocument.cs index 11b3e983608..4eee565e433 100644 --- a/src/roslyn/src/Workspaces/CoreTestUtilities/Workspaces/TestHostDocument.cs +++ b/src/roslyn/src/Workspaces/CoreTestUtilities/Workspaces/TestHostDocument.cs @@ -6,6 +6,7 @@ using System.Collections.Immutable; using System.Diagnostics.CodeAnalysis; using System.Linq; +using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Host; @@ -186,7 +187,7 @@ internal override string? FilePath => _hostDocument.FilePath; public override Task LoadTextAndVersionAsync(LoadTextOptions options, CancellationToken cancellationToken) - => Task.FromResult(TextAndVersion.Create(SourceText.From(_text, encoding: null, options.ChecksumAlgorithm), VersionStamp.Create(), _hostDocument.FilePath)); + => Task.FromResult(TextAndVersion.Create(SourceText.From(_text, encoding: Encoding.UTF8, options.ChecksumAlgorithm), VersionStamp.Create(), _hostDocument.FilePath)); } public TextLoader Loader => _loader; diff --git a/src/roslyn/src/Workspaces/CoreTestUtilities/Workspaces/TestHostProject`1.cs b/src/roslyn/src/Workspaces/CoreTestUtilities/Workspaces/TestHostProject`1.cs index bea4490ccf0..aa14c3c3fee 100644 --- a/src/roslyn/src/Workspaces/CoreTestUtilities/Workspaces/TestHostProject`1.cs +++ b/src/roslyn/src/Workspaces/CoreTestUtilities/Workspaces/TestHostProject`1.cs @@ -9,6 +9,7 @@ using System.IO; using System.Linq; using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Host; using Roslyn.Test.Utilities; diff --git a/src/roslyn/src/Workspaces/CoreTestUtilities/Workspaces/TestWorkspace.cs b/src/roslyn/src/Workspaces/CoreTestUtilities/Workspaces/TestWorkspace.cs index 3012bbc2a56..001839622e6 100644 --- a/src/roslyn/src/Workspaces/CoreTestUtilities/Workspaces/TestWorkspace.cs +++ b/src/roslyn/src/Workspaces/CoreTestUtilities/Workspaces/TestWorkspace.cs @@ -14,6 +14,8 @@ namespace Microsoft.CodeAnalysis.Test.Utilities; public partial class TestWorkspace : TestWorkspace { + public static string RootDirectory => TempRoot.Root; + internal TestWorkspace( TestComposition? composition = null, string? workspaceKind = WorkspaceKind.Host, diff --git a/src/roslyn/src/Workspaces/CoreTestUtilities/Workspaces/TestWorkspace_XmlConsumption.cs b/src/roslyn/src/Workspaces/CoreTestUtilities/Workspaces/TestWorkspace_XmlConsumption.cs index 276c64ce263..383d24c93fa 100644 --- a/src/roslyn/src/Workspaces/CoreTestUtilities/Workspaces/TestWorkspace_XmlConsumption.cs +++ b/src/roslyn/src/Workspaces/CoreTestUtilities/Workspaces/TestWorkspace_XmlConsumption.cs @@ -146,6 +146,11 @@ private TProject CreateProject( language == LanguageNames.VisualBasic ? ".vbproj" : ("." + language)); } + if (projectFilePath != null) + { + projectFilePath = PathUtilities.CombinePaths(TestWorkspace.RootDirectory, projectFilePath); + } + var projectOutputDir = AbstractTestHostProject.GetTestOutputDirectory(projectFilePath); var languageServices = Services.GetLanguageServices(language); @@ -667,8 +672,10 @@ private TDocument CreateDocument( AssertEx.Fail($"The document attributes on file {fileName} conflicted"); } + var filePath = Path.Combine(TestWorkspace.RootDirectory, fileName); + return CreateDocument( - exportProvider, languageServiceProvider, code, fileName, fileName, cursorPosition, spans, codeKind, folders, isLinkFile, documentServiceProvider); + exportProvider, languageServiceProvider, code, fileName, filePath, cursorPosition, spans, codeKind, folders, isLinkFile, documentServiceProvider); } #nullable enable diff --git a/src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/CompilerExtensions.projitems b/src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/CompilerExtensions.projitems index e27a5cba490..8042b3400c0 100644 --- a/src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/CompilerExtensions.projitems +++ b/src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/CompilerExtensions.projitems @@ -208,20 +208,10 @@ - - - - - - - - - - @@ -495,12 +485,8 @@ - - - - @@ -522,7 +508,6 @@ - @@ -537,22 +522,9 @@ - - - - - - - - - - - - - @@ -563,14 +535,6 @@ - - - - - - - - diff --git a/src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Extensions/CompilationExtensions.cs b/src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Extensions/CompilationExtensions.cs deleted file mode 100644 index bd39bdbd2fe..00000000000 --- a/src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Extensions/CompilationExtensions.cs +++ /dev/null @@ -1,89 +0,0 @@ -// 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.Diagnostics; - -namespace Microsoft.CodeAnalysis.Shared.Extensions; - -internal static class CompilationExtensions -{ - /// - /// Gets a type by its metadata name to use for code analysis within a . This method - /// attempts to find the "best" symbol to use for code analysis, which is the symbol matching the first of the - /// following rules. - /// - /// - /// - /// If only one type with the given name is found within the compilation and its referenced assemblies, that - /// type is returned regardless of accessibility. - /// - /// - /// If the current defines the symbol, that symbol is returned. - /// - /// - /// If exactly one referenced assembly defines the symbol in a manner that makes it visible to the current - /// , that symbol is returned. - /// - /// - /// Otherwise, this method returns . - /// - /// - /// - /// The to consider for analysis. - /// The fully-qualified metadata type name to find. - /// The symbol to use for code analysis; otherwise, . - public static INamedTypeSymbol? GetBestTypeByMetadataName(this Compilation compilation, string fullyQualifiedMetadataName) - { - INamedTypeSymbol? type = null; - - foreach (var currentType in compilation.GetTypesByMetadataName(fullyQualifiedMetadataName)) - { - if (ReferenceEquals(currentType.ContainingAssembly, compilation.Assembly)) - { - Debug.Assert(type is null); - return currentType; - } - - switch (currentType.GetResultantVisibility()) - { - case Utilities.SymbolVisibility.Public: - case Utilities.SymbolVisibility.Internal when currentType.ContainingAssembly.GivesAccessTo(compilation.Assembly): - break; - - default: - continue; - } - - if (type is object) - { - // Multiple visible types with the same metadata name are present - return null; - } - - type = currentType; - } - - return type; - } - - /// - /// Gets implicit method, that wraps top-level statements. - /// - public static IMethodSymbol? GetTopLevelStatementsMethod(this Compilation compilation) - { - foreach (var candidateTopLevelType in compilation.SourceModule.GlobalNamespace.GetTypeMembers(WellKnownMemberNames.TopLevelStatementsEntryPointTypeName, arity: 0)) - { - foreach (var candidateMember in candidateTopLevelType.GetMembers(WellKnownMemberNames.TopLevelStatementsEntryPointMethodName)) - { - if (candidateMember is IMethodSymbol method) - return method; - } - } - - return null; - } - - public static INamedTypeSymbol? TryGetCallingConventionSymbol(this Compilation compilation, string callingConvention) - => compilation.GetBestTypeByMetadataName($"System.Runtime.CompilerServices.CallConv{callingConvention}"); -} diff --git a/src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Extensions/SpecialTypeExtensions.cs b/src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Extensions/SpecialTypeExtensions.cs deleted file mode 100644 index a1f2c9568b1..00000000000 --- a/src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Extensions/SpecialTypeExtensions.cs +++ /dev/null @@ -1,35 +0,0 @@ -// 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 Microsoft.CodeAnalysis.LanguageService; - -namespace Microsoft.CodeAnalysis.Shared.Extensions; - -internal static partial class SpecialTypeExtensions -{ - public static PredefinedType ToPredefinedType(this SpecialType specialType) - => specialType switch - { - SpecialType.System_Object => PredefinedType.Object, - SpecialType.System_Void => PredefinedType.Void, - SpecialType.System_Boolean => PredefinedType.Boolean, - SpecialType.System_Char => PredefinedType.Char, - SpecialType.System_SByte => PredefinedType.SByte, - SpecialType.System_Byte => PredefinedType.Byte, - SpecialType.System_Int16 => PredefinedType.Int16, - SpecialType.System_UInt16 => PredefinedType.UInt16, - SpecialType.System_Int32 => PredefinedType.Int32, - SpecialType.System_UInt32 => PredefinedType.UInt32, - SpecialType.System_Int64 => PredefinedType.Int64, - SpecialType.System_UInt64 => PredefinedType.UInt64, - SpecialType.System_Decimal => PredefinedType.Decimal, - SpecialType.System_Single => PredefinedType.Single, - SpecialType.System_Double => PredefinedType.Double, - SpecialType.System_String => PredefinedType.String, - SpecialType.System_DateTime => PredefinedType.DateTime, - SpecialType.System_IntPtr => PredefinedType.IntPtr, - SpecialType.System_UIntPtr => PredefinedType.UIntPtr, - _ => PredefinedType.None, - }; -} diff --git a/src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/FlowAnalysis/SymbolUsageAnalysis/SymbolUsageAnalysis.DataFlowAnalyzer.cs b/src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/FlowAnalysis/SymbolUsageAnalysis/SymbolUsageAnalysis.DataFlowAnalyzer.cs index 3dd9c86023d..04da50b602c 100644 --- a/src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/FlowAnalysis/SymbolUsageAnalysis/SymbolUsageAnalysis.DataFlowAnalyzer.cs +++ b/src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/FlowAnalysis/SymbolUsageAnalysis/SymbolUsageAnalysis.DataFlowAnalyzer.cs @@ -6,6 +6,7 @@ using System.Diagnostics; using System.Threading; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; diff --git a/src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/FlowAnalysis/SymbolUsageAnalysis/SymbolUsageAnalysis.cs b/src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/FlowAnalysis/SymbolUsageAnalysis/SymbolUsageAnalysis.cs index 0b5f05122a9..ba416d0279a 100644 --- a/src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/FlowAnalysis/SymbolUsageAnalysis/SymbolUsageAnalysis.cs +++ b/src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/FlowAnalysis/SymbolUsageAnalysis/SymbolUsageAnalysis.cs @@ -6,6 +6,7 @@ using System.Linq; using System.Threading; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.Operations; using Roslyn.Utilities; diff --git a/src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/IReadOnlyDictionaryExtensions.cs b/src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/IReadOnlyDictionaryExtensions.cs index a00213fe05c..e00756ede4f 100644 --- a/src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/IReadOnlyDictionaryExtensions.cs +++ b/src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/IReadOnlyDictionaryExtensions.cs @@ -3,6 +3,7 @@ // See the LICENSE file in the project root for more information. using System.Collections.Generic; +using Microsoft.CodeAnalysis.Collections; namespace Roslyn.Utilities; diff --git a/src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/SpecializedTasks.cs b/src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/SpecializedTasks.cs index 47b79e36241..6c8eaa1f7ac 100644 --- a/src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/SpecializedTasks.cs +++ b/src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/SpecializedTasks.cs @@ -9,6 +9,7 @@ using System.Linq; using System.Threading; using System.Threading.Tasks; +using Microsoft.CodeAnalysis.Collections; namespace Roslyn.Utilities; diff --git a/src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Extensions/ICompilationExtensions.cs b/src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Extensions/Compilation/CompilationExtensions.cs similarity index 80% rename from src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Extensions/ICompilationExtensions.cs rename to src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Extensions/Compilation/CompilationExtensions.cs index d28f62304e3..404a65a1b52 100644 --- a/src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Extensions/ICompilationExtensions.cs +++ b/src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Extensions/Compilation/CompilationExtensions.cs @@ -17,10 +17,12 @@ using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.PooledObjects; +using Microsoft.CodeAnalysis.Shared.Utilities; +using Microsoft.CodeAnalysis.Shared.Extensions; -namespace Microsoft.CodeAnalysis.Shared.Extensions; +namespace Microsoft.CodeAnalysis; -internal static class ICompilationExtensions +internal static class CompilationExtensions { public static ImmutableArray GetReferencedCompilations(this Compilation compilation) { @@ -286,4 +288,83 @@ public static ImmutableArray GetReferencedAssemblySymbols(this public static INamedTypeSymbol? InterpolatedStringHandlerAttributeType(this Compilation compilation) => compilation.GetTypeByMetadataName(typeof(InterpolatedStringHandlerAttribute).FullName!); + + /// + /// Gets a type by its metadata name to use for code analysis within a . This method + /// attempts to find the "best" symbol to use for code analysis, which is the symbol matching the first of the + /// following rules. + /// + /// + /// + /// If only one type with the given name is found within the compilation and its referenced assemblies, that + /// type is returned regardless of accessibility. + /// + /// + /// If the current defines the symbol, that symbol is returned. + /// + /// + /// If exactly one referenced assembly defines the symbol in a manner that makes it visible to the current + /// , that symbol is returned. + /// + /// + /// Otherwise, this method returns . + /// + /// + /// + /// The to consider for analysis. + /// The fully-qualified metadata type name to find. + /// The symbol to use for code analysis; otherwise, . + public static INamedTypeSymbol? GetBestTypeByMetadataName(this Compilation compilation, string fullyQualifiedMetadataName) + { + INamedTypeSymbol? type = null; + + foreach (var currentType in compilation.GetTypesByMetadataName(fullyQualifiedMetadataName)) + { + if (ReferenceEquals(currentType.ContainingAssembly, compilation.Assembly)) + { + Debug.Assert(type is null); + return currentType; + } + + switch (currentType.GetResultantVisibility()) + { + case SymbolVisibility.Public: + case SymbolVisibility.Internal when currentType.ContainingAssembly.GivesAccessTo(compilation.Assembly): + break; + + default: + continue; + } + + if (type is object) + { + // Multiple visible types with the same metadata name are present + return null; + } + + type = currentType; + } + + return type; + } + + /// + /// Gets implicit method, that wraps top-level statements. + /// + public static IMethodSymbol? GetTopLevelStatementsMethod(this Compilation compilation) + { + foreach (var candidateTopLevelType in compilation.SourceModule.GlobalNamespace.GetTypeMembers(WellKnownMemberNames.TopLevelStatementsEntryPointTypeName, arity: 0)) + { + foreach (var candidateMember in candidateTopLevelType.GetMembers(WellKnownMemberNames.TopLevelStatementsEntryPointMethodName)) + { + if (candidateMember is IMethodSymbol method) + return method; + } + } + + return null; + } + + public static INamedTypeSymbol? TryGetCallingConventionSymbol(this Compilation compilation, string callingConvention) + => compilation.GetBestTypeByMetadataName($"System.Runtime.CompilerServices.CallConv{callingConvention}"); } diff --git a/src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Extensions/Microsoft.CodeAnalysis.Extensions.Package.csproj b/src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Extensions/Microsoft.CodeAnalysis.Extensions.Package.csproj new file mode 100644 index 00000000000..6e7c49cc478 --- /dev/null +++ b/src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Extensions/Microsoft.CodeAnalysis.Extensions.Package.csproj @@ -0,0 +1,34 @@ + + + + + netstandard2.0 + false + none + false + true + + + true + true + Microsoft.CodeAnalysis.Extensions + false + + Package containing sources of Microsoft .NET Compiler Platform ("Roslyn") extensions. + + + $(NoWarn);NU5128 + + + + + + + + + + + + + + diff --git a/src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Extensions/Microsoft.CodeAnalysis.Extensions.projitems b/src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Extensions/Microsoft.CodeAnalysis.Extensions.projitems new file mode 100644 index 00000000000..efcad0831aa --- /dev/null +++ b/src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Extensions/Microsoft.CodeAnalysis.Extensions.projitems @@ -0,0 +1,51 @@ + + + + + $(MSBuildAllProjects);$(MSBuildThisFileFullPath) + true + 02BCC112-0A29-43AA-84FA-C71C18A9486C + + + Microsoft.CodeAnalysis + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Extensions/Microsoft.CodeAnalysis.Extensions.shproj b/src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Extensions/Microsoft.CodeAnalysis.Extensions.shproj new file mode 100644 index 00000000000..7add8fd2e54 --- /dev/null +++ b/src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Extensions/Microsoft.CodeAnalysis.Extensions.shproj @@ -0,0 +1,14 @@ + + + + + 02BCC112-0A29-43AA-84FA-C71C18A9486C + 14.0 + + + + + + + + \ No newline at end of file diff --git a/src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Extensions/AccessibilityUtilities.cs b/src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Extensions/Symbols/AccessibilityUtilities.cs similarity index 100% rename from src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Extensions/AccessibilityUtilities.cs rename to src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Extensions/Symbols/AccessibilityUtilities.cs diff --git a/src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Extensions/IAssemblySymbolExtensions.cs b/src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Extensions/Symbols/IAssemblySymbolExtensions.cs similarity index 100% rename from src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Extensions/IAssemblySymbolExtensions.cs rename to src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Extensions/Symbols/IAssemblySymbolExtensions.cs diff --git a/src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Extensions/IMethodSymbolExtensions.cs b/src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Extensions/Symbols/IMethodSymbolExtensions.cs similarity index 100% rename from src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Extensions/IMethodSymbolExtensions.cs rename to src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Extensions/Symbols/IMethodSymbolExtensions.cs diff --git a/src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Extensions/INamedTypeSymbolExtensions.cs b/src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Extensions/Symbols/INamedTypeSymbolExtensions.cs similarity index 100% rename from src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Extensions/INamedTypeSymbolExtensions.cs rename to src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Extensions/Symbols/INamedTypeSymbolExtensions.cs diff --git a/src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Extensions/INamespaceOrTypeSymbolExtensions.cs b/src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Extensions/Symbols/INamespaceOrTypeSymbolExtensions.cs similarity index 100% rename from src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Extensions/INamespaceOrTypeSymbolExtensions.cs rename to src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Extensions/Symbols/INamespaceOrTypeSymbolExtensions.cs diff --git a/src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Extensions/IParameterSymbolExtensions.cs b/src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Extensions/Symbols/IParameterSymbolExtensions.cs similarity index 100% rename from src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Extensions/IParameterSymbolExtensions.cs rename to src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Extensions/Symbols/IParameterSymbolExtensions.cs diff --git a/src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Extensions/IPropertySymbolExtensions.cs b/src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Extensions/Symbols/IPropertySymbolExtensions.cs similarity index 100% rename from src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Extensions/IPropertySymbolExtensions.cs rename to src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Extensions/Symbols/IPropertySymbolExtensions.cs diff --git a/src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Extensions/ISymbolExtensions.RequiresUnsafeModifierVisitor.cs b/src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Extensions/Symbols/ISymbolExtensions.RequiresUnsafeModifierVisitor.cs similarity index 100% rename from src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Extensions/ISymbolExtensions.RequiresUnsafeModifierVisitor.cs rename to src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Extensions/Symbols/ISymbolExtensions.RequiresUnsafeModifierVisitor.cs diff --git a/src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Extensions/ISymbolExtensions.cs b/src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Extensions/Symbols/ISymbolExtensions.cs similarity index 100% rename from src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Extensions/ISymbolExtensions.cs rename to src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Extensions/Symbols/ISymbolExtensions.cs diff --git a/src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Extensions/ISymbolExtensions_Accessibility.cs b/src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Extensions/Symbols/ISymbolExtensions_Accessibility.cs similarity index 100% rename from src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Extensions/ISymbolExtensions_Accessibility.cs rename to src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Extensions/Symbols/ISymbolExtensions_Accessibility.cs diff --git a/src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Extensions/ITypeGenerator.cs b/src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Extensions/Symbols/ITypeGenerator.cs similarity index 100% rename from src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Extensions/ITypeGenerator.cs rename to src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Extensions/Symbols/ITypeGenerator.cs diff --git a/src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Extensions/ITypeParameterSymbolExtensions.cs b/src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Extensions/Symbols/ITypeParameterSymbolExtensions.cs similarity index 100% rename from src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Extensions/ITypeParameterSymbolExtensions.cs rename to src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Extensions/Symbols/ITypeParameterSymbolExtensions.cs diff --git a/src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Extensions/ITypeSymbolExtensions.AnonymousTypeRemover.cs b/src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Extensions/Symbols/ITypeSymbolExtensions.AnonymousTypeRemover.cs similarity index 100% rename from src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Extensions/ITypeSymbolExtensions.AnonymousTypeRemover.cs rename to src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Extensions/Symbols/ITypeSymbolExtensions.AnonymousTypeRemover.cs diff --git a/src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Extensions/ITypeSymbolExtensions.CollectTypeParameterSymbolsVisitor.cs b/src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Extensions/Symbols/ITypeSymbolExtensions.CollectTypeParameterSymbolsVisitor.cs similarity index 100% rename from src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Extensions/ITypeSymbolExtensions.CollectTypeParameterSymbolsVisitor.cs rename to src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Extensions/Symbols/ITypeSymbolExtensions.CollectTypeParameterSymbolsVisitor.cs diff --git a/src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Extensions/ITypeSymbolExtensions.CompilationTypeGenerator.cs b/src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Extensions/Symbols/ITypeSymbolExtensions.CompilationTypeGenerator.cs similarity index 100% rename from src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Extensions/ITypeSymbolExtensions.CompilationTypeGenerator.cs rename to src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Extensions/Symbols/ITypeSymbolExtensions.CompilationTypeGenerator.cs diff --git a/src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Extensions/ITypeSymbolExtensions.MinimalAccessibilityVisitor.cs b/src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Extensions/Symbols/ITypeSymbolExtensions.MinimalAccessibilityVisitor.cs similarity index 100% rename from src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Extensions/ITypeSymbolExtensions.MinimalAccessibilityVisitor.cs rename to src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Extensions/Symbols/ITypeSymbolExtensions.MinimalAccessibilityVisitor.cs diff --git a/src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Extensions/ITypeSymbolExtensions.SubstituteTypesVisitor.cs b/src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Extensions/Symbols/ITypeSymbolExtensions.SubstituteTypesVisitor.cs similarity index 100% rename from src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Extensions/ITypeSymbolExtensions.SubstituteTypesVisitor.cs rename to src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Extensions/Symbols/ITypeSymbolExtensions.SubstituteTypesVisitor.cs diff --git a/src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Extensions/ITypeSymbolExtensions.UnavailableTypeParameterRemover.cs b/src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Extensions/Symbols/ITypeSymbolExtensions.UnavailableTypeParameterRemover.cs similarity index 100% rename from src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Extensions/ITypeSymbolExtensions.UnavailableTypeParameterRemover.cs rename to src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Extensions/Symbols/ITypeSymbolExtensions.UnavailableTypeParameterRemover.cs diff --git a/src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Extensions/ITypeSymbolExtensions.UnnamedErrorTypeRemover.cs b/src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Extensions/Symbols/ITypeSymbolExtensions.UnnamedErrorTypeRemover.cs similarity index 100% rename from src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Extensions/ITypeSymbolExtensions.UnnamedErrorTypeRemover.cs rename to src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Extensions/Symbols/ITypeSymbolExtensions.UnnamedErrorTypeRemover.cs diff --git a/src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Extensions/ITypeSymbolExtensions.cs b/src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Extensions/Symbols/ITypeSymbolExtensions.cs similarity index 100% rename from src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Extensions/ITypeSymbolExtensions.cs rename to src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Extensions/Symbols/ITypeSymbolExtensions.cs diff --git a/src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Extensions/MethodKindExtensions.cs b/src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Extensions/Symbols/MethodKindExtensions.cs similarity index 100% rename from src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Extensions/MethodKindExtensions.cs rename to src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Extensions/Symbols/MethodKindExtensions.cs diff --git a/src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/PredefinedOperator.cs b/src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Extensions/Symbols/PredefinedOperator.cs similarity index 100% rename from src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/PredefinedOperator.cs rename to src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Extensions/Symbols/PredefinedOperator.cs diff --git a/src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/PredefinedType.cs b/src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Extensions/Symbols/PredefinedType.cs similarity index 100% rename from src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/PredefinedType.cs rename to src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Extensions/Symbols/PredefinedType.cs diff --git a/src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Extensions/PredefinedTypeExtensions.cs b/src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Extensions/Symbols/PredefinedTypeExtensions.cs similarity index 55% rename from src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Extensions/PredefinedTypeExtensions.cs rename to src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Extensions/Symbols/PredefinedTypeExtensions.cs index 2568cce2baa..7547cbbb630 100644 --- a/src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Extensions/PredefinedTypeExtensions.cs +++ b/src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Extensions/Symbols/PredefinedTypeExtensions.cs @@ -32,4 +32,29 @@ public static SpecialType ToSpecialType(this PredefinedType predefinedType) PredefinedType.UIntPtr => SpecialType.System_UIntPtr, _ => SpecialType.None, }; + + public static PredefinedType ToPredefinedType(this SpecialType specialType) + => specialType switch + { + SpecialType.System_Object => PredefinedType.Object, + SpecialType.System_Void => PredefinedType.Void, + SpecialType.System_Boolean => PredefinedType.Boolean, + SpecialType.System_Char => PredefinedType.Char, + SpecialType.System_SByte => PredefinedType.SByte, + SpecialType.System_Byte => PredefinedType.Byte, + SpecialType.System_Int16 => PredefinedType.Int16, + SpecialType.System_UInt16 => PredefinedType.UInt16, + SpecialType.System_Int32 => PredefinedType.Int32, + SpecialType.System_UInt32 => PredefinedType.UInt32, + SpecialType.System_Int64 => PredefinedType.Int64, + SpecialType.System_UInt64 => PredefinedType.UInt64, + SpecialType.System_Decimal => PredefinedType.Decimal, + SpecialType.System_Single => PredefinedType.Single, + SpecialType.System_Double => PredefinedType.Double, + SpecialType.System_String => PredefinedType.String, + SpecialType.System_DateTime => PredefinedType.DateTime, + SpecialType.System_IntPtr => PredefinedType.IntPtr, + SpecialType.System_UIntPtr => PredefinedType.UIntPtr, + _ => PredefinedType.None, + }; } diff --git a/src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/SignatureComparer.cs b/src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Extensions/Symbols/SignatureComparer.cs similarity index 100% rename from src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/SignatureComparer.cs rename to src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Extensions/Symbols/SignatureComparer.cs diff --git a/src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/SymbolDisplayFormats.cs b/src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Extensions/Symbols/SymbolDisplayFormats.cs similarity index 100% rename from src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/SymbolDisplayFormats.cs rename to src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Extensions/Symbols/SymbolDisplayFormats.cs diff --git a/src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/SymbolEquivalenceComparer.AssemblyComparers.cs b/src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Extensions/Symbols/SymbolEquivalenceComparer.AssemblyComparers.cs similarity index 100% rename from src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/SymbolEquivalenceComparer.AssemblyComparers.cs rename to src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Extensions/Symbols/SymbolEquivalenceComparer.AssemblyComparers.cs diff --git a/src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/SymbolEquivalenceComparer.EquivalenceVisitor.cs b/src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Extensions/Symbols/SymbolEquivalenceComparer.EquivalenceVisitor.cs similarity index 100% rename from src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/SymbolEquivalenceComparer.EquivalenceVisitor.cs rename to src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Extensions/Symbols/SymbolEquivalenceComparer.EquivalenceVisitor.cs diff --git a/src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/SymbolEquivalenceComparer.GetHashCodeVisitor.cs b/src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Extensions/Symbols/SymbolEquivalenceComparer.GetHashCodeVisitor.cs similarity index 100% rename from src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/SymbolEquivalenceComparer.GetHashCodeVisitor.cs rename to src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Extensions/Symbols/SymbolEquivalenceComparer.GetHashCodeVisitor.cs diff --git a/src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/SymbolEquivalenceComparer.ParameterSymbolEqualityComparer.cs b/src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Extensions/Symbols/SymbolEquivalenceComparer.ParameterSymbolEqualityComparer.cs similarity index 100% rename from src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/SymbolEquivalenceComparer.ParameterSymbolEqualityComparer.cs rename to src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Extensions/Symbols/SymbolEquivalenceComparer.ParameterSymbolEqualityComparer.cs diff --git a/src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/SymbolEquivalenceComparer.SignatureTypeSymbolEquivalenceComparer.cs b/src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Extensions/Symbols/SymbolEquivalenceComparer.SignatureTypeSymbolEquivalenceComparer.cs similarity index 100% rename from src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/SymbolEquivalenceComparer.SignatureTypeSymbolEquivalenceComparer.cs rename to src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Extensions/Symbols/SymbolEquivalenceComparer.SignatureTypeSymbolEquivalenceComparer.cs diff --git a/src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/SymbolEquivalenceComparer.cs b/src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Extensions/Symbols/SymbolEquivalenceComparer.cs similarity index 100% rename from src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/SymbolEquivalenceComparer.cs rename to src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Extensions/Symbols/SymbolEquivalenceComparer.cs diff --git a/src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/SymbolVisibility.cs b/src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Extensions/Symbols/SymbolVisibility.cs similarity index 100% rename from src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/SymbolVisibility.cs rename to src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Extensions/Symbols/SymbolVisibility.cs diff --git a/src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/VisualBasic/Extensions/SemanticModelExtensions.vb b/src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/VisualBasic/Extensions/SemanticModelExtensions.vb index 72b3513d0a0..1e4fd92e225 100644 --- a/src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/VisualBasic/Extensions/SemanticModelExtensions.vb +++ b/src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/VisualBasic/Extensions/SemanticModelExtensions.vb @@ -5,6 +5,7 @@ Imports System.Runtime.CompilerServices Imports System.Threading Imports Microsoft.CodeAnalysis +Imports Microsoft.CodeAnalysis.Collections Imports Microsoft.CodeAnalysis.Utilities Imports Microsoft.CodeAnalysis.VisualBasic.LanguageService Imports Microsoft.CodeAnalysis.VisualBasic.Syntax diff --git a/src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/VisualBasic/Extensions/SyntaxNodeExtensions.vb b/src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/VisualBasic/Extensions/SyntaxNodeExtensions.vb index 9871ba0073b..0574feab908 100644 --- a/src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/VisualBasic/Extensions/SyntaxNodeExtensions.vb +++ b/src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/VisualBasic/Extensions/SyntaxNodeExtensions.vb @@ -6,6 +6,7 @@ Imports System.Collections.Immutable Imports System.Runtime.CompilerServices Imports System.Threading Imports Microsoft.CodeAnalysis +Imports Microsoft.CodeAnalysis.Collections Imports Microsoft.CodeAnalysis.LanguageService Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.LanguageService diff --git a/src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/VisualBasic/Indentation/VisualBasicSmartTokenFormatter.vb b/src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/VisualBasic/Indentation/VisualBasicSmartTokenFormatter.vb index bb1204a4fb8..32890a77637 100644 --- a/src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/VisualBasic/Indentation/VisualBasicSmartTokenFormatter.vb +++ b/src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/VisualBasic/Indentation/VisualBasicSmartTokenFormatter.vb @@ -2,14 +2,15 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. +Imports System.Collections.Immutable Imports System.Threading +Imports Microsoft.CodeAnalysis.Collections Imports Microsoft.CodeAnalysis.Formatting Imports Microsoft.CodeAnalysis.Formatting.Rules Imports Microsoft.CodeAnalysis.Indentation Imports Microsoft.CodeAnalysis.Text -Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Microsoft.CodeAnalysis.VisualBasic.Formatting -Imports System.Collections.Immutable +Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.Indentation Friend Class VisualBasicSmartTokenFormatter diff --git a/src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/VisualBasic/Services/SemanticFacts/VisualBasicSemanticFacts.vb b/src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/VisualBasic/Services/SemanticFacts/VisualBasicSemanticFacts.vb index 31b8674d601..1db91249f50 100644 --- a/src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/VisualBasic/Services/SemanticFacts/VisualBasicSemanticFacts.vb +++ b/src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/VisualBasic/Services/SemanticFacts/VisualBasicSemanticFacts.vb @@ -7,6 +7,7 @@ Imports System.Diagnostics.CodeAnalysis Imports System.Runtime.InteropServices Imports System.Threading Imports Microsoft.CodeAnalysis +Imports Microsoft.CodeAnalysis.Collections Imports Microsoft.CodeAnalysis.LanguageService Imports Microsoft.CodeAnalysis.VisualBasic.LanguageService Imports Microsoft.CodeAnalysis.VisualBasic.Syntax diff --git a/src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/VisualBasic/Services/SyntaxFacts/VisualBasicSyntaxFacts.vb b/src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/VisualBasic/Services/SyntaxFacts/VisualBasicSyntaxFacts.vb index 1a7b3fdd1e2..adb019471d9 100644 --- a/src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/VisualBasic/Services/SyntaxFacts/VisualBasicSyntaxFacts.vb +++ b/src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/VisualBasic/Services/SyntaxFacts/VisualBasicSyntaxFacts.vb @@ -15,8 +15,10 @@ Imports System.Diagnostics.CodeAnalysis #If CODE_STYLE Then Imports Microsoft.CodeAnalysis.Internal.Editing +Imports Microsoft.CodeAnalysis.Collections #Else Imports Microsoft.CodeAnalysis.Editing +Imports Microsoft.CodeAnalysis.Collections #End If Namespace Microsoft.CodeAnalysis.VisualBasic.LanguageService diff --git a/src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/CSharp/Extensions/ContextQuery/SyntaxTreeExtensions.cs b/src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/CSharp/Extensions/ContextQuery/SyntaxTreeExtensions.cs index 2858f4a16ee..72568fd3a17 100644 --- a/src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/CSharp/Extensions/ContextQuery/SyntaxTreeExtensions.cs +++ b/src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/CSharp/Extensions/ContextQuery/SyntaxTreeExtensions.cs @@ -6,6 +6,7 @@ using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Threading; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Utilities; using Microsoft.CodeAnalysis.Shared.Extensions; diff --git a/src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/CSharp/Extensions/SemanticModelExtensions.cs b/src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/CSharp/Extensions/SemanticModelExtensions.cs index 579d936c6e8..75deb0e4a45 100644 --- a/src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/CSharp/Extensions/SemanticModelExtensions.cs +++ b/src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/CSharp/Extensions/SemanticModelExtensions.cs @@ -10,6 +10,7 @@ using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CodeGeneration; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Shared.Utilities; using Roslyn.Utilities; diff --git a/src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/CodeGeneration/Symbols/CodeGenerationNamespaceInfo.cs b/src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/CodeGeneration/Symbols/CodeGenerationNamespaceInfo.cs index 663ecc77347..a7a6c8d26e3 100644 --- a/src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/CodeGeneration/Symbols/CodeGenerationNamespaceInfo.cs +++ b/src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/CodeGeneration/Symbols/CodeGenerationNamespaceInfo.cs @@ -6,6 +6,7 @@ using System.Collections.Generic; using System.Runtime.CompilerServices; +using Microsoft.CodeAnalysis.Collections; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CodeGeneration; diff --git a/src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/CodeGeneration/Symbols/CodeGenerationNamespaceSymbol.cs b/src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/CodeGeneration/Symbols/CodeGenerationNamespaceSymbol.cs index f8d0224f0f4..418fa8aa45b 100644 --- a/src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/CodeGeneration/Symbols/CodeGenerationNamespaceSymbol.cs +++ b/src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/CodeGeneration/Symbols/CodeGenerationNamespaceSymbol.cs @@ -7,6 +7,7 @@ using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; +using Microsoft.CodeAnalysis.Collections; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CodeGeneration; diff --git a/src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/Extensions/DocumentExtensions.cs b/src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/Extensions/DocumentExtensions.cs index 555379d5924..98679691b27 100644 --- a/src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/Extensions/DocumentExtensions.cs +++ b/src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/Extensions/DocumentExtensions.cs @@ -17,6 +17,7 @@ #if DEBUG using System.Collections.Immutable; using System.Diagnostics; +using Microsoft.CodeAnalysis.Collections; #endif namespace Microsoft.CodeAnalysis.Shared.Extensions; diff --git a/src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/VisualBasic/Extensions/SemanticModelExtensions.vb b/src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/VisualBasic/Extensions/SemanticModelExtensions.vb index 6513086878e..c41275047df 100644 --- a/src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/VisualBasic/Extensions/SemanticModelExtensions.vb +++ b/src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/VisualBasic/Extensions/SemanticModelExtensions.vb @@ -7,6 +7,7 @@ Imports System.Runtime.CompilerServices Imports System.Threading Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.CodeGeneration +Imports Microsoft.CodeAnalysis.Collections Imports Microsoft.CodeAnalysis.Diagnostics.Analyzers.NamingStyles Imports Microsoft.CodeAnalysis.VisualBasic.Syntax diff --git a/src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/VisualBasic/Indentation/SpecialFormattingOperation.vb b/src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/VisualBasic/Indentation/SpecialFormattingOperation.vb index 0fd8a219aa2..77327ddfb3e 100644 --- a/src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/VisualBasic/Indentation/SpecialFormattingOperation.vb +++ b/src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/VisualBasic/Indentation/SpecialFormattingOperation.vb @@ -3,6 +3,7 @@ ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis +Imports Microsoft.CodeAnalysis.Collections Imports Microsoft.CodeAnalysis.Formatting Imports Microsoft.CodeAnalysis.Formatting.Rules Imports Microsoft.CodeAnalysis.PooledObjects diff --git a/src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/VisualBasic/LanguageServices/VisualBasicSyntaxGeneratorInternal.vb b/src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/VisualBasic/LanguageServices/VisualBasicSyntaxGeneratorInternal.vb index d67202e734f..bfc40c9847c 100644 --- a/src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/VisualBasic/LanguageServices/VisualBasicSyntaxGeneratorInternal.vb +++ b/src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/VisualBasic/LanguageServices/VisualBasicSyntaxGeneratorInternal.vb @@ -5,6 +5,7 @@ Imports System.Composition Imports System.Diagnostics.CodeAnalysis Imports Microsoft.CodeAnalysis +Imports Microsoft.CodeAnalysis.Collections Imports Microsoft.CodeAnalysis.Editing Imports Microsoft.CodeAnalysis.Host.Mef Imports Microsoft.CodeAnalysis.LanguageService diff --git a/src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/VisualBasic/LanguageServices/VisualBasicTypeInferenceService.TypeInferrer.vb b/src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/VisualBasic/LanguageServices/VisualBasicTypeInferenceService.TypeInferrer.vb index ded2d6fb9db..33c89d5524e 100644 --- a/src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/VisualBasic/LanguageServices/VisualBasicTypeInferenceService.TypeInferrer.vb +++ b/src/roslyn/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/VisualBasic/LanguageServices/VisualBasicTypeInferenceService.TypeInferrer.vb @@ -5,6 +5,7 @@ Imports System.Collections.Immutable Imports System.Threading Imports Microsoft.CodeAnalysis +Imports Microsoft.CodeAnalysis.Collections Imports Microsoft.CodeAnalysis.LanguageService Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax diff --git a/src/roslyn/src/Workspaces/VisualBasic/Portable/CodeCleanup/Providers/AddMissingTokensCodeCleanupProvider.vb b/src/roslyn/src/Workspaces/VisualBasic/Portable/CodeCleanup/Providers/AddMissingTokensCodeCleanupProvider.vb index f456bf60f08..90b5561939e 100644 --- a/src/roslyn/src/Workspaces/VisualBasic/Portable/CodeCleanup/Providers/AddMissingTokensCodeCleanupProvider.vb +++ b/src/roslyn/src/Workspaces/VisualBasic/Portable/CodeCleanup/Providers/AddMissingTokensCodeCleanupProvider.vb @@ -6,6 +6,7 @@ Imports System.Collections.Immutable Imports System.Composition Imports System.Diagnostics.CodeAnalysis Imports System.Threading +Imports Microsoft.CodeAnalysis.Collections Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Syntax diff --git a/src/roslyn/src/Workspaces/VisualBasic/Portable/CodeCleanup/Providers/FixIncorrectTokensCodeCleanupProvider.vb b/src/roslyn/src/Workspaces/VisualBasic/Portable/CodeCleanup/Providers/FixIncorrectTokensCodeCleanupProvider.vb index eca342b8eb9..34e208e2747 100644 --- a/src/roslyn/src/Workspaces/VisualBasic/Portable/CodeCleanup/Providers/FixIncorrectTokensCodeCleanupProvider.vb +++ b/src/roslyn/src/Workspaces/VisualBasic/Portable/CodeCleanup/Providers/FixIncorrectTokensCodeCleanupProvider.vb @@ -7,6 +7,7 @@ Imports System.Composition Imports System.Diagnostics.CodeAnalysis Imports System.Threading Imports Microsoft.CodeAnalysis +Imports Microsoft.CodeAnalysis.Collections Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Syntax diff --git a/src/roslyn/src/Workspaces/VisualBasic/Portable/CodeCleanup/Providers/NormalizeModifiersOrOperatorsCodeCleanupProvider.vb b/src/roslyn/src/Workspaces/VisualBasic/Portable/CodeCleanup/Providers/NormalizeModifiersOrOperatorsCodeCleanupProvider.vb index eb70c766ccb..190aa7bd1de 100644 --- a/src/roslyn/src/Workspaces/VisualBasic/Portable/CodeCleanup/Providers/NormalizeModifiersOrOperatorsCodeCleanupProvider.vb +++ b/src/roslyn/src/Workspaces/VisualBasic/Portable/CodeCleanup/Providers/NormalizeModifiersOrOperatorsCodeCleanupProvider.vb @@ -8,6 +8,7 @@ Imports System.Diagnostics.CodeAnalysis Imports System.Threading Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.CodeStyle +Imports Microsoft.CodeAnalysis.Collections Imports Microsoft.CodeAnalysis.Formatting Imports Microsoft.CodeAnalysis.Host Imports Microsoft.CodeAnalysis.Shared.Collections diff --git a/src/roslyn/src/Workspaces/VisualBasic/Portable/CodeGeneration/VisualBasicSyntaxGenerator.vb b/src/roslyn/src/Workspaces/VisualBasic/Portable/CodeGeneration/VisualBasicSyntaxGenerator.vb index c0aa21a3319..82b2ecf4f29 100644 --- a/src/roslyn/src/Workspaces/VisualBasic/Portable/CodeGeneration/VisualBasicSyntaxGenerator.vb +++ b/src/roslyn/src/Workspaces/VisualBasic/Portable/CodeGeneration/VisualBasicSyntaxGenerator.vb @@ -6,6 +6,7 @@ Imports System.Collections.Immutable Imports System.Composition Imports System.Diagnostics.CodeAnalysis Imports Microsoft.CodeAnalysis +Imports Microsoft.CodeAnalysis.Collections Imports Microsoft.CodeAnalysis.Editing Imports Microsoft.CodeAnalysis.Host.Mef Imports Microsoft.CodeAnalysis.PooledObjects diff --git a/src/roslyn/src/Workspaces/VisualBasic/Portable/Formatting/Engine/Trivia/TriviaDataFactory.AbstractLineBreakTrivia.vb b/src/roslyn/src/Workspaces/VisualBasic/Portable/Formatting/Engine/Trivia/TriviaDataFactory.AbstractLineBreakTrivia.vb index 4b543b4e32e..7a86870f4d5 100644 --- a/src/roslyn/src/Workspaces/VisualBasic/Portable/Formatting/Engine/Trivia/TriviaDataFactory.AbstractLineBreakTrivia.vb +++ b/src/roslyn/src/Workspaces/VisualBasic/Portable/Formatting/Engine/Trivia/TriviaDataFactory.AbstractLineBreakTrivia.vb @@ -3,6 +3,7 @@ ' See the LICENSE file in the project root for more information. Imports System.Threading +Imports Microsoft.CodeAnalysis.Collections Imports Microsoft.CodeAnalysis.Diagnostics Imports Microsoft.CodeAnalysis.Formatting Imports Microsoft.CodeAnalysis.Text diff --git a/src/roslyn/src/Workspaces/VisualBasic/Portable/Formatting/Rules/ElasticTriviaFormattingRule.vb b/src/roslyn/src/Workspaces/VisualBasic/Portable/Formatting/Rules/ElasticTriviaFormattingRule.vb index c7fcde489bd..712aacbb4cd 100644 --- a/src/roslyn/src/Workspaces/VisualBasic/Portable/Formatting/Rules/ElasticTriviaFormattingRule.vb +++ b/src/roslyn/src/Workspaces/VisualBasic/Portable/Formatting/Rules/ElasticTriviaFormattingRule.vb @@ -2,6 +2,7 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. +Imports Microsoft.CodeAnalysis.Collections Imports Microsoft.CodeAnalysis.Formatting Imports Microsoft.CodeAnalysis.Formatting.Rules Imports Microsoft.CodeAnalysis.PooledObjects diff --git a/src/roslyn/src/Workspaces/VisualBasic/Portable/Rename/VisualBasicRenameRewriterLanguageService.vb b/src/roslyn/src/Workspaces/VisualBasic/Portable/Rename/VisualBasicRenameRewriterLanguageService.vb index 270760732b5..8f9ffd50734 100644 --- a/src/roslyn/src/Workspaces/VisualBasic/Portable/Rename/VisualBasicRenameRewriterLanguageService.vb +++ b/src/roslyn/src/Workspaces/VisualBasic/Portable/Rename/VisualBasicRenameRewriterLanguageService.vb @@ -5,6 +5,7 @@ Imports System.Collections.Immutable Imports System.Threading Imports Microsoft.CodeAnalysis +Imports Microsoft.CodeAnalysis.Collections Imports Microsoft.CodeAnalysis.FindSymbols Imports Microsoft.CodeAnalysis.LanguageService Imports Microsoft.CodeAnalysis.PooledObjects diff --git a/src/roslyn/src/Workspaces/VisualBasicTest/Formatting/VisualBasicFormattingTestBase.vb b/src/roslyn/src/Workspaces/VisualBasicTest/Formatting/VisualBasicFormattingTestBase.vb index a1057b51771..761cff6eebb 100644 --- a/src/roslyn/src/Workspaces/VisualBasicTest/Formatting/VisualBasicFormattingTestBase.vb +++ b/src/roslyn/src/Workspaces/VisualBasicTest/Formatting/VisualBasicFormattingTestBase.vb @@ -4,6 +4,7 @@ Imports System.Collections.Immutable Imports System.Threading +Imports Microsoft.CodeAnalysis.Collections Imports Microsoft.CodeAnalysis.Diagnostics Imports Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions Imports Microsoft.CodeAnalysis.Formatting diff --git a/src/source-manifest.json b/src/source-manifest.json index 4818fd60105..cd99be974f7 100644 --- a/src/source-manifest.json +++ b/src/source-manifest.json @@ -92,11 +92,11 @@ "commitSha": "c971e1c19e2d56f9d8a396f7a72b245495340bae" }, { - "packageVersion": "5.0.0-1.25262.9", - "barId": 267943, + "packageVersion": "5.0.0-1.25264.5", + "barId": 268299, "path": "roslyn", "remoteUri": "https://github.com/dotnet/roslyn", - "commitSha": "4215d71efbdb059bbb092fe9d385c11aba1c8969" + "commitSha": "4358d1222f26078b302f1f79c18dee05a5f2766b" }, { "packageVersion": "10.0.0-preview.25260.1", From 9435eab6a6dafd56842e38c871e0512f5ca4c387 Mon Sep 17 00:00:00 2001 From: Nikola Milosavljevic Date: Thu, 15 May 2025 06:20:50 -0700 Subject: [PATCH 07/11] Improve resilience with malformed NuGet.config files (#554) --- .../UpdateNuGetConfigPackageSourcesMappings.cs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/eng/tools/tasks/Microsoft.DotNet.UnifiedBuild.Tasks/UpdateNuGetConfigPackageSourcesMappings.cs b/eng/tools/tasks/Microsoft.DotNet.UnifiedBuild.Tasks/UpdateNuGetConfigPackageSourcesMappings.cs index 5a6c99ae3bc..4bc201c91c2 100644 --- a/eng/tools/tasks/Microsoft.DotNet.UnifiedBuild.Tasks/UpdateNuGetConfigPackageSourcesMappings.cs +++ b/eng/tools/tasks/Microsoft.DotNet.UnifiedBuild.Tasks/UpdateNuGetConfigPackageSourcesMappings.cs @@ -81,7 +81,7 @@ public override bool Execute() string xml = File.ReadAllText(NuGetConfigFile); string newLineChars = FileUtilities.DetectNewLineChars(xml); XDocument document = XDocument.Parse(xml); - XElement pkgSourcesElement = document.Root.Descendants().FirstOrDefault(e => e.Name == "packageSources"); + XElement pkgSourcesElement = document.Root.Elements().FirstOrDefault(e => e.Name == "packageSources"); if (pkgSourcesElement == null) { Log.LogMessage(MessageImportance.Low, "Package sources are missing."); @@ -89,7 +89,7 @@ public override bool Execute() return true; } - XElement pkgSrcMappingElement = document.Root.Descendants().FirstOrDefault(e => e.Name == "packageSourceMapping"); + XElement pkgSrcMappingElement = document.Root.Elements().FirstOrDefault(e => e.Name == "packageSourceMapping"); if (pkgSrcMappingElement == null) { pkgSrcMappingElement = new XElement("packageSourceMapping"); @@ -115,7 +115,7 @@ public override bool Execute() // Remove all packageSourceMappings pkgSrcMappingElement.ReplaceNodes(new XElement("clear")); - XElement pkgSrcMappingClearElement = pkgSrcMappingElement.Descendants().FirstOrDefault(e => e.Name == "clear"); + XElement pkgSrcMappingClearElement = pkgSrcMappingElement.Elements().FirstOrDefault(e => e.Name == "clear"); // Add package source mappings for local package sources foreach (string packageSource in allSourcesPackages.Keys) From 29c02a27d36b99640889f5f823b6d11ba5859cb2 Mon Sep 17 00:00:00 2001 From: Viktor Hofer Date: Thu, 15 May 2025 15:52:39 +0200 Subject: [PATCH 08/11] Fix sourcebuild switch in live eng/common layout Fixes https://github.com/dotnet/source-build/issues/5192 Manually forward port https://github.com/dotnet/arcade/commit/6b63184d8ff276115846b232816ece935a26a22c until the arcade -> dotnet ff PR is unblocked. Regressed with https://github.com/dotnet/dotnet/commit/d78071715ad117cc541e15b856922ebe49b28923 which already took a dependency on the new switch without updating the eng/common layout or waiting for the arcade ff PR to get merged. --- src/arcade/eng/common/build.sh | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/arcade/eng/common/build.sh b/src/arcade/eng/common/build.sh index 27ae2c85601..08f99154b7d 100755 --- a/src/arcade/eng/common/build.sh +++ b/src/arcade/eng/common/build.sh @@ -129,14 +129,14 @@ while [[ $# > 0 ]]; do -pack) pack=true ;; - -sourcebuild|-sb) + -sourcebuild|-source-build|-sb) build=true source_build=true product_build=true restore=true pack=true ;; - -productbuild|-pb) + -productbuild|-product-build|-pb) build=true product_build=true restore=true From b34e9cc7b0069badbefad3749e4df78d1b5bca69 Mon Sep 17 00:00:00 2001 From: Viktor Hofer Date: Thu, 15 May 2025 17:06:15 +0200 Subject: [PATCH 09/11] Update outgoing src/arcade/global.json sdk version (#570) --- src/arcade/global.json | 4 ++-- .../Sdk/tools/dotnet-cli/DotNetCli.props | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/arcade/global.json b/src/arcade/global.json index 2310fb93991..8696508044b 100644 --- a/src/arcade/global.json +++ b/src/arcade/global.json @@ -1,10 +1,10 @@ { "sdk": { - "version": "10.0.100-preview.3.25201.16", + "version": "10.0.100-preview.5.25230.108", "rollForward": "latestFeature" }, "tools": { - "dotnet": "10.0.100-preview.3.25201.16" + "dotnet": "10.0.100-preview.5.25230.108" }, "msbuild-sdks": { "Microsoft.DotNet.Arcade.Sdk": "10.0.0-beta.25256.1", diff --git a/src/arcade/src/Microsoft.DotNet.Helix/Sdk/tools/dotnet-cli/DotNetCli.props b/src/arcade/src/Microsoft.DotNet.Helix/Sdk/tools/dotnet-cli/DotNetCli.props index f90a939fd9a..6540304a0a9 100644 --- a/src/arcade/src/Microsoft.DotNet.Helix/Sdk/tools/dotnet-cli/DotNetCli.props +++ b/src/arcade/src/Microsoft.DotNet.Helix/Sdk/tools/dotnet-cli/DotNetCli.props @@ -3,7 +3,7 @@ false - 10.0.0-preview.3.25172.1 + 10.0.0-preview.5.25230.108 runtime $(BundledNETCoreAppPackageVersion) From 20248d664be0492851a99db19095e10cf1bf3eaa Mon Sep 17 00:00:00 2001 From: Viktor Hofer Date: Thu, 15 May 2025 17:36:37 +0200 Subject: [PATCH 10/11] Fix productbuild switch in bootstrap eng/common layout (#571) --- eng/common/build.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/eng/common/build.sh b/eng/common/build.sh index 36fba82a379..27ae2c85601 100755 --- a/eng/common/build.sh +++ b/eng/common/build.sh @@ -136,7 +136,7 @@ while [[ $# > 0 ]]; do restore=true pack=true ;; - -productBuild|-pb) + -productbuild|-pb) build=true product_build=true restore=true From 094631c46bc1d3cf5f3749e57bb584671f9e10f3 Mon Sep 17 00:00:00 2001 From: Nikola Milosavljevic Date: Thu, 15 May 2025 09:25:09 -0700 Subject: [PATCH 11/11] Reintroduce support for building VMR from repo PR/CI (#548) --- eng/pipelines/templates/jobs/vmr-build.yml | 26 ++++++++-- .../stages/source-build-and-validate.yml | 7 +++ .../templates/stages/source-build-stages.yml | 6 +++ .../templates/stages/vmr-build-with-join.yml | 18 ++++++- eng/pipelines/templates/stages/vmr-build.yml | 13 ++++- .../templates/stages/vmr-verticals.yml | 50 +++++++++++++++++++ 6 files changed, 112 insertions(+), 8 deletions(-) diff --git a/eng/pipelines/templates/jobs/vmr-build.yml b/eng/pipelines/templates/jobs/vmr-build.yml index b3f46059a4e..0add8ee8c6d 100644 --- a/eng/pipelines/templates/jobs/vmr-build.yml +++ b/eng/pipelines/templates/jobs/vmr-build.yml @@ -114,6 +114,12 @@ parameters: type: stepList default: [] +#### repo parameters #### + +- name: isBuiltFromVmr + displayName: True when build is running from dotnet/dotnet directly + type: boolean + jobs: - job: ${{ parameters.buildName }}_${{ parameters.targetArchitecture }}${{ replace(format('_BuildPass{0}', coalesce(parameters.buildPass, '1')), '_BuildPass1', '') }} pool: ${{ parameters.pool }} @@ -160,8 +166,13 @@ jobs: value: '' - name: runTestsTimeout value: 30 - - name: vmrPath - value: $(Build.SourcesDirectory) + + - ${{ if parameters.isBuiltFromVmr }}: + - name: vmrPath + value: $(Build.SourcesDirectory) + - ${{ else }}: + - name: vmrPath + value: $(Agent.BuildDirectory)/vmr # Location of the VMR sources # We either build the repo directly, or we extract them outside (which is what partners do) @@ -270,7 +281,7 @@ jobs: timeoutInMinutes: 720 ## Currently, CodeQL slows the build down too much ## https://github.com/dotnet/source-build/issues/4276 - ${{ elseif and(startswith(parameters.buildName, 'Windows'), eq(variables['System.TeamProject'], 'internal'), ne(variables['Build.Reason'], 'PullRequest')) }}: + ${{ elseif and(parameters.isBuiltFromVmr, startswith(parameters.buildName, 'Windows'), eq(variables['System.TeamProject'], 'internal'), ne(variables['Build.Reason'], 'PullRequest')) }}: timeoutInMinutes: 720 ${{ else }}: timeoutInMinutes: 240 @@ -312,6 +323,13 @@ jobs: sbomEnabled: false steps: + - ${{ if not(parameters.isBuiltFromVmr) }}: + # Synchronize new content in the VMR during PRs + - template: /eng/common/templates/steps/vmr-pull-updates.yml@self + parameters: + vmrPath: $(vmrPath) + targetRef: $(Build.SourceVersion) # Synchronize the current repo commit + - ${{ if parameters.buildFromArchive }}: - script: | set -ex @@ -323,7 +341,7 @@ jobs: - ${{ if ne(parameters.reuseBuildArtifactsFrom,'') }}: - ${{ each reuseBuildArtifacts in parameters.reuseBuildArtifactsFrom }}: - ${{ if eq(parameters.buildSourceOnly, true) }}: - - template: ../steps/download-artifacts.yml@self + - template: ../steps/download-artifacts.yml parameters: artifactDescription: Previous Build (${{ reuseBuildArtifacts }} - Source Build artifacts) artifactName: ${{ reuseBuildArtifacts }}_Artifacts diff --git a/eng/pipelines/templates/stages/source-build-and-validate.yml b/eng/pipelines/templates/stages/source-build-and-validate.yml index 2ae5096297b..5bc2427f59b 100644 --- a/eng/pipelines/templates/stages/source-build-and-validate.yml +++ b/eng/pipelines/templates/stages/source-build-and-validate.yml @@ -15,6 +15,11 @@ parameters: - name: legs type: object +# True when build is running from dotnet/dotnet directly +- name: isBuiltFromVmr + type: boolean + default: true + stages: - stage: VMR_SourceOnly_Build displayName: VMR Source-Only Build @@ -83,6 +88,7 @@ stages: targetRid: ${{ variables.alpineX64Rid }} targetArchitecture: ${{ leg.targetArchitecture }} + isBuiltFromVmr: ${{ parameters.isBuiltFromVmr }} ${{ if eq(leg.targetArchitecture, 'arm64') }}: pool: ${{ parameters.pool_LinuxArm64 }} ${{ else }}: @@ -150,6 +156,7 @@ stages: targetRid: ${{ variables.alpineX64Rid }} targetArchitecture: ${{ leg.targetArchitecture }} + isBuiltFromVmr: ${{ parameters.isBuiltFromVmr }} ${{ if eq(leg.targetArchitecture, 'arm64') }}: pool: ${{ parameters.pool_LinuxArm64 }} ${{ else }}: diff --git a/eng/pipelines/templates/stages/source-build-stages.yml b/eng/pipelines/templates/stages/source-build-stages.yml index e885c95ade4..c8572eea6ea 100644 --- a/eng/pipelines/templates/stages/source-build-stages.yml +++ b/eng/pipelines/templates/stages/source-build-stages.yml @@ -14,6 +14,11 @@ parameters: type: boolean default: true +# True when build is running from dotnet/dotnet directly +- name: isBuiltFromVmr + type: boolean + default: true + # Temporarily needed to enable SB PR legs from the unified build pipeline # This parameter should be removed with https://github.com/dotnet/dotnet/pull/400 - name: officialBuildId @@ -27,6 +32,7 @@ stages: pool_LinuxArm64: ${{ parameters.pool_LinuxArm64 }} scope: ${{ parameters.scope }} useMicrosoftBuildAssetsForTests: ${{ parameters.useMicrosoftBuildAssetsForTests }} + isBuiltFromVmr: ${{ parameters.isBuiltFromVmr }} # Description of the source build legs to run. # This is described here as a parameter to allow two separate stages to be produced from this list (one for building diff --git a/eng/pipelines/templates/stages/vmr-build-with-join.yml b/eng/pipelines/templates/stages/vmr-build-with-join.yml index 47a1e4c9d8e..01be49bad62 100644 --- a/eng/pipelines/templates/stages/vmr-build-with-join.yml +++ b/eng/pipelines/templates/stages/vmr-build-with-join.yml @@ -10,6 +10,11 @@ parameters: - name: finalJoinCondition type: boolean +#### repo parameters #### +- name: isBuiltFromVmr + displayName: True when build is running from dotnet/dotnet directly + type: boolean + # These are not expected to be passed it but rather just object variables reused below - name: pool_Linux type: object @@ -66,8 +71,12 @@ stages: - ${{ if ne(stage.templateContext.validationOnly, 'true') }}: - ${{ stage.stage }} variables: - - name: vmrPath - value: $(Build.SourcesDirectory) + - ${{ if parameters.isBuiltFromVmr }}: + - name: vmrPath + value: $(Build.SourcesDirectory) + - ${{ else }}: + - name: vmrPath + value: $(Agent.BuildDirectory)/vmr - template: ../variables/vmr-build.yml jobs: - job: FinalJoin @@ -129,6 +138,11 @@ stages: inputs: path: $(Build.ArtifactStagingDirectory)/VerticalArtifacts/${{ vertical.job }} artifactName: ${{ vertical.job }}_Artifacts + - ${{ if not(parameters.isBuiltFromVmr) }}: + - template: /eng/common/templates/steps/vmr-pull-updates.yml@self + parameters: + vmrPath: ${{ variables.vmrPath }} + targetRef: $(Build.SourceVersion) # Synchronize the current repo commit - template: ../steps/vmr-join-verticals.yml parameters: dotNetBuildPass: final diff --git a/eng/pipelines/templates/stages/vmr-build.yml b/eng/pipelines/templates/stages/vmr-build.yml index 9e6f35126c7..7da7b66e898 100644 --- a/eng/pipelines/templates/stages/vmr-build.yml +++ b/eng/pipelines/templates/stages/vmr-build.yml @@ -21,6 +21,11 @@ parameters: # run everything - full +# True when build is running from dotnet/dotnet directly +- name: isBuiltFromVmr + type: boolean + default: true + # True when building the VMR in source-only mode - name: isSourceOnlyBuild type: boolean @@ -76,15 +81,17 @@ stages: parameters: desiredSigning: ${{ parameters.desiredSigning }} desiredIbc: ${{ parameters.desiredIbc }} + isBuiltFromVmr: ${{ parameters.isBuiltFromVmr }} scope: ${{ parameters.scope }} isSourceOnlyBuild: ${{ parameters.isSourceOnlyBuild }} finalJoinCondition: ${{ and(not(parameters.isSourceOnlyBuild), eq(parameters.scope, 'full')) }} + isBuiltFromVmr: ${{ parameters.isBuiltFromVmr }} postJoinStages: - - ${{ if and(not(parameters.isSourceOnlyBuild), eq(variables['System.TeamProject'], 'internal'), ne(variables['Build.Reason'], 'PullRequest')) }}: + - ${{ if and(parameters.isBuiltFromVmr, not(parameters.isSourceOnlyBuild), eq(variables['System.TeamProject'], 'internal'), ne(variables['Build.Reason'], 'PullRequest')) }}: - stage: Publish_Build_Assets displayName: Publish Assets jobs: - - template: /eng/common/templates-official/job/publish-build-assets.yml@self + - template: /eng/common/templates-official/job/publish-build-assets.yml parameters: publishUsingPipelines: true publishAssetsImmediately: true @@ -104,11 +111,13 @@ stages: pool_LinuxArm64: ${{ parameters.pool_LinuxArm64 }} scope: ${{ parameters.scope }} useMicrosoftBuildAssetsForTests: false + isBuiltFromVmr: ${{ parameters.isBuiltFromVmr }} - ${{ else }}: - template: source-build-stages.yml parameters: pool_Linux: ${{ parameters.pool_Linux }} pool_LinuxArm64: ${{ parameters.pool_LinuxArm64 }} + isBuiltFromVmr: ${{ parameters.isBuiltFromVmr }} ${{ if eq(variables['Build.Reason'], 'PullRequest') }}: scope: ultralite # Temporarily needed to enable SB PR legs from the unified build pipeline diff --git a/eng/pipelines/templates/stages/vmr-verticals.yml b/eng/pipelines/templates/stages/vmr-verticals.yml index 906d2172696..1971666bfdf 100644 --- a/eng/pipelines/templates/stages/vmr-verticals.yml +++ b/eng/pipelines/templates/stages/vmr-verticals.yml @@ -21,6 +21,11 @@ parameters: # run everything - full +# True when build is running from dotnet/dotnet directly +- name: isBuiltFromVmr + type: boolean + default: true + # True when building the VMR in source-only mode - name: isSourceOnlyBuild type: boolean @@ -84,6 +89,7 @@ stages: - template: ../jobs/vmr-build.yml parameters: buildName: ${{ format('{0}_Ubuntu_BuildTests', variables.ubuntuName) }} + isBuiltFromVmr: ${{ parameters.isBuiltFromVmr }} pool: ${{ parameters.pool_Linux }} container: name: ${{ variables.ubuntuContainerName }} @@ -96,6 +102,7 @@ stages: - template: ../jobs/vmr-build.yml parameters: buildName: Windows_BuildTests + isBuiltFromVmr: ${{ parameters.isBuiltFromVmr }} pool: ${{ parameters.pool_Windows }} targetOS: windows targetArchitecture: x64 @@ -116,6 +123,7 @@ stages: - template: ../jobs/vmr-build.yml parameters: buildName: Windows + isBuiltFromVmr: ${{ parameters.isBuiltFromVmr }} sign: ${{ variables.signEnabled }} signDac: ${{ variables.signDacEnabled }} pool: ${{ parameters.pool_Windows }} @@ -126,6 +134,7 @@ stages: - template: ../jobs/vmr-build.yml parameters: buildName: Windows + isBuiltFromVmr: ${{ parameters.isBuiltFromVmr }} sign: ${{ variables.signEnabled }} signDac: ${{ variables.signDacEnabled }} pool: ${{ parameters.pool_Windows }} @@ -135,6 +144,7 @@ stages: - template: ../jobs/vmr-build.yml parameters: buildName: Android_Shortstack + isBuiltFromVmr: ${{ parameters.isBuiltFromVmr }} sign: ${{ variables.signEnabled }} pool: ${{ parameters.pool_Linux_Shortstack }} container: @@ -146,6 +156,7 @@ stages: - template: ../jobs/vmr-build.yml parameters: buildName: Browser_Shortstack + isBuiltFromVmr: ${{ parameters.isBuiltFromVmr }} sign: ${{ variables.signEnabled }} pool: ${{ parameters.pool_Linux_Shortstack }} container: @@ -158,6 +169,7 @@ stages: - template: ../jobs/vmr-build.yml parameters: buildName: iOSSimulator_Shortstack + isBuiltFromVmr: ${{ parameters.isBuiltFromVmr }} sign: ${{ variables.signEnabled }} pool: ${{ parameters.pool_Mac }} targetOS: iossimulator @@ -169,6 +181,7 @@ stages: - template: ../jobs/vmr-build.yml parameters: buildName: Android_Shortstack + isBuiltFromVmr: ${{ parameters.isBuiltFromVmr }} sign: ${{ variables.signEnabled }} pool: ${{ parameters.pool_Linux_Shortstack }} container: @@ -180,6 +193,7 @@ stages: - template: ../jobs/vmr-build.yml parameters: buildName: Android_Shortstack + isBuiltFromVmr: ${{ parameters.isBuiltFromVmr }} sign: ${{ variables.signEnabled }} pool: ${{ parameters.pool_Linux_Shortstack }} container: @@ -191,6 +205,7 @@ stages: - template: ../jobs/vmr-build.yml parameters: buildName: Android_Shortstack + isBuiltFromVmr: ${{ parameters.isBuiltFromVmr }} sign: ${{ variables.signEnabled }} pool: ${{ parameters.pool_Linux_Shortstack }} container: @@ -202,6 +217,7 @@ stages: - template: ../jobs/vmr-build.yml parameters: buildName: Browser_Multithreaded_Shortstack + isBuiltFromVmr: ${{ parameters.isBuiltFromVmr }} sign: ${{ variables.signEnabled }} pool: ${{ parameters.pool_Linux_Shortstack }} container: @@ -215,6 +231,7 @@ stages: - template: ../jobs/vmr-build.yml parameters: buildName: LinuxBionic_Shortstack + isBuiltFromVmr: ${{ parameters.isBuiltFromVmr }} sign: ${{ variables.signEnabled }} pool: ${{ parameters.pool_Linux_Shortstack }} container: @@ -226,6 +243,7 @@ stages: - template: ../jobs/vmr-build.yml parameters: buildName: LinuxBionic_Shortstack + isBuiltFromVmr: ${{ parameters.isBuiltFromVmr }} sign: ${{ variables.signEnabled }} pool: ${{ parameters.pool_Linux_Shortstack }} container: @@ -237,6 +255,7 @@ stages: - template: ../jobs/vmr-build.yml parameters: buildName: LinuxBionic_Shortstack + isBuiltFromVmr: ${{ parameters.isBuiltFromVmr }} sign: ${{ variables.signEnabled }} pool: ${{ parameters.pool_Linux_Shortstack }} container: @@ -248,6 +267,7 @@ stages: - template: ../jobs/vmr-build.yml parameters: buildName: iOS_Shortstack + isBuiltFromVmr: ${{ parameters.isBuiltFromVmr }} sign: ${{ variables.signEnabled }} pool: ${{ parameters.pool_Mac }} targetOS: ios @@ -256,6 +276,7 @@ stages: - template: ../jobs/vmr-build.yml parameters: buildName: iOSSimulator_Shortstack + isBuiltFromVmr: ${{ parameters.isBuiltFromVmr }} sign: ${{ variables.signEnabled }} pool: ${{ parameters.pool_Mac }} targetOS: iossimulator @@ -264,6 +285,7 @@ stages: - template: ../jobs/vmr-build.yml parameters: buildName: MacCatalyst_Shortstack + isBuiltFromVmr: ${{ parameters.isBuiltFromVmr }} sign: ${{ variables.signEnabled }} pool: ${{ parameters.pool_Mac }} targetOS: maccatalyst @@ -272,6 +294,7 @@ stages: - template: ../jobs/vmr-build.yml parameters: buildName: MacCatalyst_Shortstack + isBuiltFromVmr: ${{ parameters.isBuiltFromVmr }} sign: ${{ variables.signEnabled }} pool: ${{ parameters.pool_Mac }} targetOS: maccatalyst @@ -280,6 +303,7 @@ stages: - template: ../jobs/vmr-build.yml parameters: buildName: tvOS_Shortstack + isBuiltFromVmr: ${{ parameters.isBuiltFromVmr }} sign: ${{ variables.signEnabled }} pool: ${{ parameters.pool_Mac }} targetOS: tvos @@ -288,6 +312,7 @@ stages: - template: ../jobs/vmr-build.yml parameters: buildName: tvOSSimulator_Shortstack + isBuiltFromVmr: ${{ parameters.isBuiltFromVmr }} sign: ${{ variables.signEnabled }} pool: ${{ parameters.pool_Mac }} targetOS: tvossimulator @@ -296,6 +321,7 @@ stages: - template: ../jobs/vmr-build.yml parameters: buildName: tvOSSimulator_Shortstack + isBuiltFromVmr: ${{ parameters.isBuiltFromVmr }} sign: ${{ variables.signEnabled }} pool: ${{ parameters.pool_Mac }} targetOS: tvossimulator @@ -304,6 +330,7 @@ stages: - template: ../jobs/vmr-build.yml parameters: buildName: Wasi_Shortstack + isBuiltFromVmr: ${{ parameters.isBuiltFromVmr }} sign: ${{ variables.signEnabled }} pool: ${{ parameters.pool_Linux_Shortstack }} container: @@ -316,6 +343,7 @@ stages: - template: ../jobs/vmr-build.yml parameters: buildName: OSX + isBuiltFromVmr: ${{ parameters.isBuiltFromVmr }} sign: ${{ variables.signEnabled }} pool: ${{ parameters.pool_Mac }} targetOS: osx @@ -324,6 +352,7 @@ stages: - template: ../jobs/vmr-build.yml parameters: buildName: OSX_Shortstack_Mono_LLVMAOT + isBuiltFromVmr: ${{ parameters.isBuiltFromVmr }} sign: ${{ variables.signEnabled }} pool: ${{ parameters.pool_Mac }} useMonoRuntime: true @@ -334,6 +363,7 @@ stages: - template: ../jobs/vmr-build.yml parameters: buildName: AzureLinux_x64_Cross + isBuiltFromVmr: ${{ parameters.isBuiltFromVmr }} sign: ${{ variables.signEnabled }} pool: ${{ parameters.pool_Linux }} container: @@ -346,6 +376,7 @@ stages: - template: ../jobs/vmr-build.yml parameters: buildName: AzureLinux_x64_Cross_Pgo + isBuiltFromVmr: ${{ parameters.isBuiltFromVmr }} sign: false pool: ${{ parameters.pool_Linux }} container: @@ -359,6 +390,7 @@ stages: - template: ../jobs/vmr-build.yml parameters: buildName: AzureLinux_x64_Cross_Shortstack_Mono_LLVMAOT + isBuiltFromVmr: ${{ parameters.isBuiltFromVmr }} sign: ${{ variables.signEnabled }} pool: ${{ parameters.pool_Linux_Shortstack }} container: @@ -373,6 +405,7 @@ stages: - template: ../jobs/vmr-build.yml parameters: buildName: AzureLinux_x64_Cross + isBuiltFromVmr: ${{ parameters.isBuiltFromVmr }} sign: ${{ variables.signEnabled }} pool: ${{ parameters.pool_Linux }} container: @@ -385,6 +418,7 @@ stages: - template: ../jobs/vmr-build.yml parameters: buildName: AzureLinux_x64_Cross + isBuiltFromVmr: ${{ parameters.isBuiltFromVmr }} sign: ${{ variables.signEnabled }} pool: ${{ parameters.pool_Linux }} container: @@ -397,6 +431,7 @@ stages: - template: ../jobs/vmr-build.yml parameters: buildName: AzureLinux_x64_Cross_Pgo + isBuiltFromVmr: ${{ parameters.isBuiltFromVmr }} sign: false pool: ${{ parameters.pool_Linux }} container: @@ -410,6 +445,7 @@ stages: - template: ../jobs/vmr-build.yml parameters: buildName: AzureLinux_x64_Cross_Alpine + isBuiltFromVmr: ${{ parameters.isBuiltFromVmr }} sign: ${{ variables.signEnabled }} pool: ${{ parameters.pool_Linux }} container: @@ -423,6 +459,7 @@ stages: - template: ../jobs/vmr-build.yml parameters: buildName: AzureLinux_x64_Cross_Alpine + isBuiltFromVmr: ${{ parameters.isBuiltFromVmr }} sign: ${{ variables.signEnabled }} pool: ${{ parameters.pool_Linux }} container: @@ -436,6 +473,7 @@ stages: - template: ../jobs/vmr-build.yml parameters: buildName: AzureLinux_x64_Cross_Alpine + isBuiltFromVmr: ${{ parameters.isBuiltFromVmr }} sign: ${{ variables.signEnabled }} pool: ${{ parameters.pool_Linux }} container: @@ -449,6 +487,7 @@ stages: - template: ../jobs/vmr-build.yml parameters: buildName: AzureLinux_x64_Cross_Shortstack_Mono_LLVMAOT + isBuiltFromVmr: ${{ parameters.isBuiltFromVmr }} sign: ${{ variables.signEnabled }} pool: ${{ parameters.pool_Linux_Shortstack }} container: @@ -463,6 +502,7 @@ stages: - template: ../jobs/vmr-build.yml parameters: buildName: OSX + isBuiltFromVmr: ${{ parameters.isBuiltFromVmr }} sign: ${{ variables.signEnabled }} pool: ${{ parameters.pool_Mac }} targetOS: osx @@ -471,6 +511,7 @@ stages: - template: ../jobs/vmr-build.yml parameters: buildName: Windows + isBuiltFromVmr: ${{ parameters.isBuiltFromVmr }} sign: ${{ variables.signEnabled }} signDac: ${{ variables.signDacEnabled }} pool: ${{ parameters.pool_Windows }} @@ -481,6 +522,7 @@ stages: - template: ../jobs/vmr-build.yml parameters: buildName: Windows_Pgo + isBuiltFromVmr: ${{ parameters.isBuiltFromVmr }} sign: false pool: ${{ parameters.pool_Windows }} targetOS: windows @@ -490,6 +532,7 @@ stages: - template: ../jobs/vmr-build.yml parameters: buildName: Windows_Pgo + isBuiltFromVmr: ${{ parameters.isBuiltFromVmr }} sign: false pool: ${{ parameters.pool_Windows }} targetOS: windows @@ -500,6 +543,7 @@ stages: - template: ../jobs/vmr-build.yml parameters: buildName: Windows_Pgo + isBuiltFromVmr: ${{ parameters.isBuiltFromVmr }} sign: false pool: ${{ parameters.pool_Windows }} targetOS: windows @@ -512,6 +556,7 @@ stages: - template: ../jobs/vmr-build.yml parameters: buildName: Windows + isBuiltFromVmr: ${{ parameters.isBuiltFromVmr }} sign: ${{ variables.signEnabled }} signDac: ${{ variables.signDacEnabled }} pool: ${{ parameters.pool_Windows }} @@ -533,6 +578,7 @@ stages: - template: ../jobs/vmr-build.yml parameters: buildName: Windows + isBuiltFromVmr: ${{ parameters.isBuiltFromVmr }} sign: ${{ variables.signEnabled }} pool: ${{ parameters.pool_Windows }} targetOS: windows @@ -547,6 +593,7 @@ stages: - template: ../jobs/vmr-build.yml parameters: buildName: Windows_Workloads + isBuiltFromVmr: ${{ parameters.isBuiltFromVmr }} sign: ${{ variables.signEnabled }} pool: ${{ parameters.pool_Windows }} targetOS: windows @@ -579,6 +626,7 @@ stages: - template: ../jobs/vmr-build.yml parameters: buildName: Windows + isBuiltFromVmr: ${{ parameters.isBuiltFromVmr }} sign: ${{ variables.signEnabled }} pool: ${{ parameters.pool_Windows }} targetOS: windows @@ -593,6 +641,7 @@ stages: - template: ../jobs/vmr-build.yml parameters: buildName: Windows + isBuiltFromVmr: ${{ parameters.isBuiltFromVmr }} sign: ${{ variables.signEnabled }} pool: ${{ parameters.pool_Windows }} targetOS: windows @@ -607,6 +656,7 @@ stages: - template: ../jobs/vmr-build.yml parameters: buildName: Windows + isBuiltFromVmr: ${{ parameters.isBuiltFromVmr }} sign: ${{ variables.signEnabled }} pool: ${{ parameters.pool_Windows }} targetOS: windows