From d75984b5e85bbf55f9c82c89845e0bfd167513ec Mon Sep 17 00:00:00 2001 From: Anthony Martin <38542602+anthony-c-martin@users.noreply.github.com> Date: Thu, 13 Jun 2024 09:49:49 -0400 Subject: [PATCH] Run dotnet format --- .editorconfig | 1 + .../BuildCommandTests.cs | 18 +- .../BuildParamsCommandTests.cs | 8 +- .../DecompileCommandTests.cs | 6 +- .../DecompileParamsCommandTests.cs | 6 +- .../JsonRpcCommandTests.cs | 28 +-- .../PublishCommandTests.cs | 8 +- .../PublishProviderCommandTests.cs | 6 +- .../ArgumentParserTests.cs | 48 ++-- src/Bicep.Cli/Helpers/ParamsFileHelper.cs | 2 +- src/Bicep.Cli/Rpc/CliJsonRpcServer.cs | 6 +- src/Bicep.Cli/Services/TemplateEvaluator.cs | 4 +- .../DirectResourceCollectionTests.cs | 6 +- .../Emit/TemplateEmitterTests.cs | 2 +- .../Extensibility/BarNamespaceType.cs | 6 +- .../Extensibility/FooNamespaceType.cs | 6 +- .../NestedResourceTests.cs | 12 +- .../Scenarios/NullabilityTests.cs | 6 +- .../Semantics/ExpressionCollectorVisitor.cs | 2 +- .../Semantics/NamespaceTests.cs | 2 +- .../TypeSystem/TypeValidationTests.cs | 8 +- src/Bicep.Core.Samples/DataSetsExtensions.cs | 4 +- .../ApiVersion/ApiVersionProviderTests.cs | 2 +- .../Configuration/BicepConfigSchemaTests.cs | 6 +- .../Configuration/RootConfigurationTests.cs | 10 +- .../Diagnostics/ErrorBuilderTests.cs | 2 +- .../ArtifactsParametersRuleTests.cs | 107 +++----- .../NoLocationExprOutsideParamsRuleTests.cs | 4 +- .../NoUnnecessaryDependsOnRuleTests.cs | 52 ++-- .../PreferInterpolationRuleTests.cs | 2 +- .../PreferUnquotedPropertyNamesRuleTests.cs | 2 +- ...ecureParamsInNestedDeploymentsRuleTests.cs | 84 +++---- .../UseParentPropertyRuleTests.cs | 2 +- ...ingsForCommandToExecuteSecretsRuleTests.cs | 32 +-- .../UseRecentApiVersionRuleTests.cs | 122 +++++----- ...iVersionRule_InReferenceFunctions_Tests.cs | 2 +- .../UseResourceIdFunctionsRuleTests.cs | 10 +- .../UseResourceSymbolReferenceRuleTests.cs | 2 +- .../FileSystem/PathHelperTests.cs | 2 +- .../IServiceCollectionExtensions.cs | 2 +- .../Mock/FakeResourceTypes.cs | 2 +- .../Modules/ArtifactAddressComponentsTests.cs | 2 +- .../Parsing/LexerTests.cs | 6 +- .../Registry/ArtifactDispatcherTests.cs | 2 +- .../Registry/CachedModules.cs | 4 +- .../Registry/DescriptorFactoryTests.cs | 2 +- .../Registry/TokenCredentialFactoryTests.cs | 4 +- .../ArmTemplateSemanticModelTests.cs | 2 +- .../Semantics/ObjectDeserializationTests.cs | 10 +- .../SourceCodeDocumentLinkHelperTests.cs | 16 +- .../SourceCode/SourceCodePathHelperTests.cs | 152 +++++------- .../Syntax/SeparatedSyntaxListTests.cs | 4 +- .../Syntax/SyntaxCollectorVisitor.cs | 2 +- .../Text/SpellCheckerTests.cs | 2 +- .../Az/AzResourceTypeProviderTests.cs | 8 +- .../TypeSystem/FunctionResolverTests.cs | 230 +++++++++--------- .../TypeSystem/OperatorTests.cs | 4 +- .../ResourceDerivedTypeResolverTests.cs | 68 +++--- .../TypeSystem/TypeHelperTests.cs | 12 +- .../TypeValidatorAssignabilityTests.cs | 20 +- .../TypeValidatorCompileTimeConstantTests.cs | 2 +- .../TypeSystem/UnionTypeTests.cs | 2 +- .../Utils/BuiltInTestTypes.cs | 4 +- .../Utils/CycleDetectorTests.cs | 16 +- src/Bicep.Core.UnitTests/Utils/PrintHelper.cs | 2 +- .../Utils/TestTypeHelper.cs | 6 +- .../Utils/TextByteArray.cs | 8 +- .../Utils/ThirdPartyTypeHelper.cs | 12 +- .../Linter/ApiVersions/ApiVersionProvider.cs | 2 +- .../Linter/Common/LinterExpressionHelper.cs | 2 +- .../Analyzers/Linter/LinterAnalyzer.cs | 2 +- .../Analyzers/Linter/LinterRuleBase.cs | 4 +- .../Linter/Rules/LocationRuleBase.cs | 8 +- .../Linter/Rules/MaxNumberOutputsRule.cs | 2 +- .../Linter/Rules/MaxNumberParametersRule.cs | 2 +- .../Linter/Rules/MaxNumberResourcesRule.cs | 2 +- .../Linter/Rules/MaxNumberVariablesRule.cs | 2 +- .../Linter/Rules/NoConflictingMetadataRule.cs | 6 +- .../Rules/NoHardcodedEnvironmentUrlsRule.cs | 4 +- .../Rules/NoUnusedExistingResourcesRule.cs | 2 +- ...dSettingsForCommandToExecuteSecretsRule.cs | 7 +- .../Linter/Rules/UseRecentApiVersionRule.cs | 4 +- .../Rules/UseResourceIdFunctionsRule.cs | 116 ++++----- .../Rules/UseResourceSymbolReferenceRule.cs | 2 +- .../Linter/Rules/UseStableVMImageRule.cs | 2 +- .../Fixes/DecoratorCodeFixProvider.cs | 4 +- .../Collections/Trees/IntervalTreeNode.cs | 2 +- .../Configuration/CloudConfiguration.cs | 2 +- .../DataFlow/LocalSymbolDependencyVisitor.cs | 2 +- .../Diagnostics/EmptyDiagnosticLookup.cs | 2 +- .../ArmDeclarationToExpressionConverter.cs | 11 +- src/Bicep.Core/Emit/ExpressionConverter.cs | 44 ++-- src/Bicep.Core/Emit/ExpressionEmitter.cs | 4 +- .../Emit/InlineDependencyVisitor.cs | 6 +- .../PlaceholderParametersBicepParamWriter.cs | 4 +- .../Emit/PositionTrackingJsonTextWriter.cs | 2 +- .../Emit/ResourceDependencyVisitor.cs | 2 +- src/Bicep.Core/Emit/ScopeHelper.cs | 4 +- src/Bicep.Core/Emit/TemplateEmitter.cs | 2 +- src/Bicep.Core/Emit/TemplateWriter.cs | 8 +- .../Extensions/JsonNodeExtensions.cs | 2 +- src/Bicep.Core/FileSystem/FileResolver.cs | 4 +- .../Intermediate/ExpressionBuilder.cs | 36 +-- .../Intermediate/ExpressionExtensions.cs | 4 +- src/Bicep.Core/LanguageConstants.cs | 8 +- .../Modules/LocalModuleReference.cs | 4 +- src/Bicep.Core/Parsing/BaseParser.cs | 22 +- src/Bicep.Core/Parsing/Lexer.cs | 4 +- src/Bicep.Core/Parsing/Parser.cs | 4 +- .../PrettyPrint/DocumentBuildVisitor.cs | 8 +- .../PrettyPrint/Documents/NestDocument.cs | 2 +- .../PrettyPrint/Documents/TextDocument.cs | 2 +- .../Documents/DocumentOperators.cs | 2 +- .../SyntaxLayouts.SyntaxVisitor.cs | 2 +- src/Bicep.Core/PrettyPrintV2/SyntaxLayouts.cs | 2 +- src/Bicep.Core/Registry/ModuleDispatcher.cs | 2 +- .../Registry/Oci/OciArtifactReference.cs | 2 +- .../Resources/ResourceTypeReference.cs | 2 +- .../Semantics/ArmTemplateSemanticModel.cs | 2 +- .../Semantics/AuxiliaryFileCache.cs | 2 +- src/Bicep.Core/Semantics/Compilation.cs | 2 +- .../Semantics/DeclarationVisitor.cs | 14 +- .../Semantics/DeclaredFunctionSymbol.cs | 2 +- src/Bicep.Core/Semantics/FunctionOverload.cs | 2 +- .../Semantics/ISemanticModelLookup.cs | 2 +- .../Semantics/ImportedFunctionSymbol.cs | 2 +- .../Semantics/NameBindingVisitor.cs | 2 +- .../Semantics/Namespaces/AzNamespaceType.cs | 28 +-- .../Semantics/Namespaces/NamespaceResolver.cs | 2 +- .../Namespaces/SystemNamespaceType.cs | 35 +-- .../Semantics/ResourceAncestorGraph.cs | 2 +- .../Semantics/ResourceSymbolVisitor.cs | 2 +- src/Bicep.Core/Semantics/SemanticModel.cs | 6 +- .../WildcardImportInstanceFunctionSymbol.cs | 2 +- src/Bicep.Core/SourceCode/SourceArchive.cs | 2 +- .../SourceCodeDocumentLinkHelper.cs | 2 +- .../Syntax/ParameterAssignmentSyntax.cs | 2 +- src/Bicep.Core/Syntax/SyntaxFactory.cs | 8 +- .../Syntax/UsingDeclarationSyntax.cs | 2 +- .../Text/TextCoordinateConverter.cs | 2 +- .../Tracing/DiagnosticOptionsExtensions.cs | 20 +- .../ArmFunctionReturnTypeEvaluator.cs | 2 +- .../TypeSystem/ArmTemplateTypeLoader.cs | 6 +- .../TypeSystem/DeployTimeConstantValidator.cs | 2 +- .../DiscriminatedObjectTypeBuilder.cs | 2 +- .../OperationReturnTypeEvaluator.cs | 21 +- .../Providers/Az/AzResourceTypeLoader.cs | 2 +- .../Providers/Az/AzResourceTypeProvider.cs | 18 +- .../Providers/EmptyResourceTypeProvider.cs | 2 +- .../Providers/K8s/K8sResourceTypeProvider.cs | 10 +- .../MicrosoftGraphResourceTypeProvider.cs | 8 +- .../ThirdPartyResourceTypeProvider.cs | 6 +- .../ResourceDerivedTypeDiagnosticReporter.cs | 2 +- src/Bicep.Core/TypeSystem/TypeAssignment.cs | 2 +- .../TypeSystem/TypeAssignmentVisitor.cs | 10 +- src/Bicep.Core/TypeSystem/TypeFactory.cs | 2 +- src/Bicep.Core/TypeSystem/TypeHelper.cs | 8 +- src/Bicep.Core/TypeSystem/TypeValidator.cs | 6 +- src/Bicep.Core/TypeSystem/Types/ErrorType.cs | 2 +- .../Workspaces/SourceFileFactory.cs | 2 +- .../Workspaces/SourceFileGrouping.cs | 2 +- .../ArmHelpers/ExpressionHelpersTests.cs | 2 +- .../ArmHelpers/ExpressionHelpers.cs | 8 +- .../ArmHelpers/TemplateHelpers.cs | 4 +- src/Bicep.Decompiler/TemplateConverter.cs | 15 +- .../Assertions/AssertionScopeExtensions.cs | 2 +- .../CodeLensTests.cs | 2 +- .../Helpers/ServerRequestHelper.cs | 2 +- .../HoverTests.cs | 4 +- .../Registry/ModuleRestoreSchedulerTests.cs | 2 +- .../BicepCompletionProviderTests.cs | 6 +- ...blicRegistryModuleMetadataProviderTests.cs | 2 +- .../BicepDecompileCommandHandlerTests.cs | 20 +- .../BicepEditLinterRuleCommandHandlerTests.cs | 2 +- ...etRecommendedConfigLocationHandlerTests.cs | 18 +- .../BicepCompilationManager.cs | 6 +- .../Completions/BicepCompletionContext.cs | 21 +- .../Completions/BicepCompletionProvider.cs | 82 +++---- .../ModuleReferenceCompletionProvider.cs | 10 +- .../PublicRegistryModuleMetadataClient.cs | 2 +- .../PublicRegistryModuleMetadataProvider.cs | 2 +- .../SyntaxPatterns/SyntaxPattern.cs | 2 +- .../Deploy/DeploymentParametersHelper.cs | 2 +- .../Handlers/BicepDecompileCommandHandler.cs | 4 +- .../BicepDecompileSaveCommandHandler.cs | 6 +- .../BicepDeploymentParametersHandler.cs | 2 +- .../BicepEditLinterRuleCommandHandler.cs | 2 +- .../ImportKubernetesManifestHandler.cs | 2 +- .../Handlers/LocalDeployHandler.cs | 16 +- src/Bicep.LangServer/Snippets/Snippet.cs | 11 +- .../Snippets/SnippetCacheBuilder.cs | 4 +- .../Snippets/SnippetsProvider.cs | 17 +- .../Telemetry/TelemetryHelper.cs | 2 +- .../Utils/DocumentSelectorFactory.cs | 16 +- .../LocalDeploymentSettings.cs | 58 ++--- .../Commands/GenerateCommandTests.cs | 6 +- .../Samples/Sample.cs | 2 +- .../ITypeReferenceExtensionsTests.cs | 15 +- .../Commands/BaseCommandHandler.cs | 2 +- .../ModuleFileValidators/TestValidator.cs | 2 +- src/Bicep.Wasm/EmptyModuleRegistryProvider.cs | 2 +- 201 files changed, 1075 insertions(+), 1194 deletions(-) diff --git a/.editorconfig b/.editorconfig index 9e27c427bc7..db7d1265c85 100644 --- a/.editorconfig +++ b/.editorconfig @@ -39,6 +39,7 @@ dotnet_diagnostic.IDE0051.severity = warning # Use collection expression for array dotnet_diagnostic.IDE0300.severity = warning +dotnet_style_prefer_collection_expression = true # Use collection expression for empty dotnet_diagnostic.IDE0301.severity = warning # Use collection expression for stackalloc diff --git a/src/Bicep.Cli.IntegrationTests/BuildCommandTests.cs b/src/Bicep.Cli.IntegrationTests/BuildCommandTests.cs index da656bc7173..ee788628d8b 100644 --- a/src/Bicep.Cli.IntegrationTests/BuildCommandTests.cs +++ b/src/Bicep.Cli.IntegrationTests/BuildCommandTests.cs @@ -179,7 +179,7 @@ public async Task Build_Valid_SingleFile_WithProviderDeclarationStatement( .AddSingleton(settings.ClientFactory) .AddSingleton(settings.TemplateSpecRepositoryFactory); }) - .RunAsync(new[] { "build", bicepFilePath }, CancellationToken.None)); + .RunAsync(["build", bicepFilePath], CancellationToken.None)); // ASSERT // 6. assert 'bicep build' completed successfully @@ -411,9 +411,9 @@ public async Task Build_WithNonExistentOutDir_ShouldFail_WithExpectedErrorMessag error.Should().MatchRegex(@"The specified output directory "".*outputdir"" does not exist"); } - [DataRow(new string[] { })] - [DataRow(new[] { "--diagnostics-format", "defAULt" })] - [DataRow(new[] { "--diagnostics-format", "sArif" })] + [DataRow([])] + [DataRow(["--diagnostics-format", "defAULt"])] + [DataRow(["--diagnostics-format", "sArif"])] [DataTestMethod] public async Task Build_WithOutDir_ShouldSucceed(string[] args) { @@ -429,7 +429,7 @@ public async Task Build_WithOutDir_ShouldSucceed(string[] args) var expectedOutputFile = Path.Combine(outputFileDir, "input.json"); File.Exists(expectedOutputFile).Should().BeFalse(); - var (output, error, result) = await Bicep(new[] { "build", "--outdir", outputFileDir, bicepPath }.Concat(args).ToArray()); + var (output, error, result) = await Bicep(["build", "--outdir", outputFileDir, bicepPath, .. args]); File.Exists(expectedOutputFile).Should().BeTrue(); output.Should().BeEmpty(); @@ -477,7 +477,7 @@ public async Task Build_WithOutDir_ShouldSucceed(string[] args) [DataTestMethod] public async Task Build_InvalidInputPaths_ShouldProduceExpectedError(string badPath, string[] args, string expectedErrorRegex) { - var (output, error, result) = await Bicep(new[] { "build" }.Concat(args).Append(badPath).ToArray()); + var (output, error, result) = await Bicep(["build", .. args, badPath]); result.Should().Be(1); output.Should().BeEmpty(); @@ -544,8 +544,8 @@ public async Task Build_WithInvalidBicepConfig_ShouldProduceConfigurationError() error.Should().StartWith($"{inputFile}(1,1) : Error BCP271: Failed to parse the contents of the Bicep configuration file \"{configurationPath}\" as valid JSON: Expected depth to be zero at the end of the JSON payload. There is an open JSON object or array that should be closed. LineNumber: 8 | BytePositionInLine: 0."); } - [DataRow(new string[] { })] - [DataRow(new[] { "--diagnostics-format", "defAULt" })] + [DataRow([])] + [DataRow(["--diagnostics-format", "defAULt"])] [DataTestMethod] public async Task Build_WithValidBicepConfig_ShouldProduceOutputFileAndExpectedError(string[] args) { @@ -574,7 +574,7 @@ public async Task Build_WithValidBicepConfig_ShouldProduceOutputFileAndExpectedE var expectedOutputFile = Path.Combine(testOutputPath, "main.json"); File.Exists(expectedOutputFile).Should().BeFalse(); - var (output, error, result) = await Bicep(new[] { "build", "--outdir", testOutputPath, inputFile }.Concat(args).ToArray()); + var (output, error, result) = await Bicep(["build", "--outdir", testOutputPath, inputFile, .. args]); File.Exists(expectedOutputFile).Should().BeTrue(); result.Should().Be(0); diff --git a/src/Bicep.Cli.IntegrationTests/BuildParamsCommandTests.cs b/src/Bicep.Cli.IntegrationTests/BuildParamsCommandTests.cs index d4dbc1c39e8..fe23dabe174 100644 --- a/src/Bicep.Cli.IntegrationTests/BuildParamsCommandTests.cs +++ b/src/Bicep.Cli.IntegrationTests/BuildParamsCommandTests.cs @@ -438,9 +438,9 @@ public async Task Build_bicepparam_should_fail_with_error_diagnostics_for_regist result.Stderr.Should().Contain("main.bicepparam(1,7) : Error BCP192: Unable to restore the artifact with reference \"br:mockregistry.io/parameters/basic:v1\": Mock registry request failure."); } - [DataRow(new string[] { })] - [DataRow(new[] { "--diagnostics-format", "defAULt" })] - [DataRow(new[] { "--diagnostics-format", "sArif" })] + [DataRow([])] + [DataRow(["--diagnostics-format", "defAULt"])] + [DataRow(["--diagnostics-format", "sArif"])] [TestMethod] public async Task BuildParams_supports_sarif_diagnostics_format(string[] args) { @@ -459,7 +459,7 @@ param unusedParam int var expectedOutputFile = FileHelper.GetResultFilePath(TestContext, "main.json", outputPath); File.Exists(expectedOutputFile).Should().BeFalse(); - var (output, error, result) = await Bicep(new[] { "build-params", inputFile }.Concat(args).ToArray()); + var (output, error, result) = await Bicep(["build-params", inputFile, .. args]); File.Exists(expectedOutputFile).Should().BeTrue(); output.Should().BeEmpty(); diff --git a/src/Bicep.Cli.IntegrationTests/DecompileCommandTests.cs b/src/Bicep.Cli.IntegrationTests/DecompileCommandTests.cs index 6a113f5fd18..673e24dc1d0 100644 --- a/src/Bicep.Cli.IntegrationTests/DecompileCommandTests.cs +++ b/src/Bicep.Cli.IntegrationTests/DecompileCommandTests.cs @@ -87,12 +87,12 @@ public class DecompileCommandTests : TestBase } }"; - private readonly string[] DecompilationDisclaimer = new[] - { + private readonly string[] DecompilationDisclaimer = + [ "WARNING: Decompilation is a best-effort process, as there is no guaranteed mapping from ARM JSON to Bicep Template or Bicep Parameters.", "You may need to fix warnings and errors in the generated bicep/bicepparam file(s), or decompilation may fail entirely if an accurate conversion is not possible.", "If you would like to report any issues or inaccurate conversions, please see https://github.com/Azure/bicep/issues." - }; + ]; [TestMethod] diff --git a/src/Bicep.Cli.IntegrationTests/DecompileParamsCommandTests.cs b/src/Bicep.Cli.IntegrationTests/DecompileParamsCommandTests.cs index efa26ec2214..2925ca59f67 100644 --- a/src/Bicep.Cli.IntegrationTests/DecompileParamsCommandTests.cs +++ b/src/Bicep.Cli.IntegrationTests/DecompileParamsCommandTests.cs @@ -13,12 +13,12 @@ namespace Bicep.Cli.IntegrationTests [TestClass] public class DecompileParamsCommandTests : TestBase { - private readonly string[] DecompilationDisclaimer = new[] - { + private readonly string[] DecompilationDisclaimer = + [ "WARNING: Decompilation is a best-effort process, as there is no guaranteed mapping from ARM JSON to Bicep Template or Bicep Parameters.", "You may need to fix warnings and errors in the generated bicep/bicepparam file(s), or decompilation may fail entirely if an accurate conversion is not possible.", "If you would like to report any issues or inaccurate conversions, please see https://github.com/Azure/bicep/issues." - }; + ]; [TestMethod] diff --git a/src/Bicep.Cli.IntegrationTests/JsonRpcCommandTests.cs b/src/Bicep.Cli.IntegrationTests/JsonRpcCommandTests.cs index 463c1e13d33..7a5740893a3 100644 --- a/src/Bicep.Cli.IntegrationTests/JsonRpcCommandTests.cs +++ b/src/Bicep.Cli.IntegrationTests/JsonRpcCommandTests.cs @@ -132,20 +132,20 @@ await RunServerTest( async (client, token) => { var response = await client.GetMetadata(new("/main.bicep"), token); - response.Metadata.Should().Equal(new GetMetadataResponse.MetadataDefinition[] { + response.Metadata.Should().Equal([ new("description", "my file"), - }); - response.Parameters.Should().Equal(new GetMetadataResponse.SymbolDefinition[] { + ]); + response.Parameters.Should().Equal([ new(new(new(2, 0), new(3, 16)), "foo", new(null, "string"), "foo param"), new(new(new(5, 0), new(7, 1)), "inlineType", new(null, "{ sdf: string }"), null), new(new(new(9, 0), new(9, 23)), "declaredType", new(new(new(11, 0), new(15, 1)), "asdf"), null), - }); - response.Outputs.Should().Equal(new GetMetadataResponse.SymbolDefinition[] { + ]); + response.Outputs.Should().Equal([ new(new(new(17, 0), new(18, 23)), "bar", new(null, "string"), "bar output"), - }); - response.Exports.Should().Equal(new GetMetadataResponse.ExportDefinition[] { + ]); + response.Exports.Should().Equal([ new(new(new(11, 0), new(15, 1)), "asdf", "TypeAlias", "asdf type"), - }); + ]); }); } @@ -176,15 +176,15 @@ await RunServerTest( async (client, token) => { var response = await client.GetDeploymentGraph(new("/main.bicep"), token); - response.Nodes.Should().Equal(new GetDeploymentGraphResponse.Node[] { + response.Nodes.Should().Equal([ new(new(new(4, 0), new(7, 1)), "bar", "My.Rp/foo", true, null), new(new(new(9, 0), new(12, 1)), "baz", "My.Rp/foo", false, null), new(new(new(0, 0), new(2, 1)), "foo", "My.Rp/foo", false, null), - }); - response.Edges.Should().Equal(new GetDeploymentGraphResponse.Edge[] { + ]); + response.Edges.Should().Equal([ new("bar", "foo"), new("baz", "bar"), - }); + ]); }); } @@ -218,13 +218,13 @@ await RunServerTest( { var response = await client.GetFileReferences(new("/main.bicepparam"), token); - response.FilePaths.Should().Equal(new[] { + response.FilePaths.Should().Equal([ "/bicepconfig.json", "/invalid.txt", "/main.bicep", "/main.bicepparam", "/valid.txt", - }); + ]); }); } } diff --git a/src/Bicep.Cli.IntegrationTests/PublishCommandTests.cs b/src/Bicep.Cli.IntegrationTests/PublishCommandTests.cs index 9ea01240285..efc1fdded2e 100644 --- a/src/Bicep.Cli.IntegrationTests/PublishCommandTests.cs +++ b/src/Bicep.Cli.IntegrationTests/PublishCommandTests.cs @@ -177,7 +177,7 @@ public async Task Publish_AllValidDataSets_ShouldSucceed(string testName, DataSe requiredArgs.Add("--with-source"); } - string[] args = requiredArgs.ToArray(); + string[] args = [.. requiredArgs]; var (output, error, result) = await Bicep(settings, args); result.Should().Be(0); @@ -219,14 +219,14 @@ public async Task Publish_AllValidDataSets_ShouldSucceed(string testName, DataSe // publish the same content again with --force requiredArgs.Add("--force"); - var (output3, error3, result3) = await Bicep(settings, requiredArgs.ToArray()); + var (output3, error3, result3) = await Bicep(settings, [.. requiredArgs]); result3.Should().Be(0); output3.Should().BeEmpty(); AssertNoErrors(error3); // compile to get what the new expected main.json should be List buildArgs = new() { "build", bicepFilePath, "--outfile", $"{compiledFilePath}.modified" }; - var (output4, error4, result4) = await Bicep(settings, buildArgs.ToArray()); + var (output4, error4, result4) = await Bicep(settings, [.. buildArgs]); result4.Should().Be(0); output4.Should().BeEmpty(); AssertNoErrors(error4); @@ -320,7 +320,7 @@ public async Task Publish_ValidArmTemplateFile_WithSource_ShouldFail() var settings = new InvocationSettings(new(TestContext, RegistryEnabled: true), clientFactory, templateSpecRepositoryFactory); var args = new List { "publish", compiledFilePath, "--target", $"br:{registryStr}/{repository}:v1", "--with-source" }; - var (output, error, result) = await Bicep(settings, args.ToArray()); + var (output, error, result) = await Bicep(settings, [.. args]); result.Should().Be(1); output.Should().BeEmpty(); error.Should().MatchRegex("Cannot publish with source when the target is an ARM template file."); diff --git a/src/Bicep.Cli.IntegrationTests/PublishProviderCommandTests.cs b/src/Bicep.Cli.IntegrationTests/PublishProviderCommandTests.cs index 97f23cca823..9768f6cd4e6 100644 --- a/src/Bicep.Cli.IntegrationTests/PublishProviderCommandTests.cs +++ b/src/Bicep.Cli.IntegrationTests/PublishProviderCommandTests.cs @@ -39,7 +39,7 @@ public async Task Publish_provider_should_succeed() List requiredArgs = new() { "publish-provider", indexPath, "--target", $"br:{registryStr}/{repository}:{version}" }; - string[] args = requiredArgs.ToArray(); + string[] args = [.. requiredArgs]; var result = await Bicep(settings, args); result.Should().Succeed().And.NotHaveStdout(); @@ -62,13 +62,13 @@ public async Task Publish_provider_should_succeed() saBodyType.Properties.Keys.Should().Contain("name", "location", "properties", "sku", "tags"); // publishing without --force should fail - result = await Bicep(settings, requiredArgs.ToArray()); + result = await Bicep(settings, [.. requiredArgs]); result.Should().Fail().And.HaveStderrMatch("*The Provider \"*\" already exists. Use --force to overwrite the existing provider.*"); // test with force requiredArgs.Add("--force"); - var result2 = await Bicep(settings, requiredArgs.ToArray()); + var result2 = await Bicep(settings, [.. requiredArgs]); result2.Should().Succeed().And.NotHaveStdout(); // verify the provider was published diff --git a/src/Bicep.Cli.UnitTests/ArgumentParserTests.cs b/src/Bicep.Cli.UnitTests/ArgumentParserTests.cs index a382589f86b..29668dc3eb6 100644 --- a/src/Bicep.Cli.UnitTests/ArgumentParserTests.cs +++ b/src/Bicep.Cli.UnitTests/ArgumentParserTests.cs @@ -18,14 +18,14 @@ public class ArgumentParserTests [TestMethod] public void Empty_parameters_should_return_null() { - var arguments = ArgumentParser.TryParse(Array.Empty(), IO, FileSystem); + var arguments = ArgumentParser.TryParse([], IO, FileSystem); arguments.Should().BeNull(); } [TestMethod] public void Wrong_command_should_return_null() { - var arguments = ArgumentParser.TryParse(new[] { "wrong" }, IO, FileSystem); + var arguments = ArgumentParser.TryParse(["wrong"], IO, FileSystem); arguments.Should().BeNull(); } @@ -74,7 +74,7 @@ public void Invalid_args_trigger_validation_exceptions(string[] parameters, stri [TestMethod] public void BuildOneFile_ShouldReturnOneFile() { - var arguments = ArgumentParser.TryParse(new[] { "build", "file1" }, IO, FileSystem); + var arguments = ArgumentParser.TryParse(["build", "file1"], IO, FileSystem); var buildArguments = (BuildArguments?)arguments; // using classic assert so R# understands the value is not null @@ -89,7 +89,7 @@ public void BuildOneFile_ShouldReturnOneFile() [TestMethod] public void BuildOneFileStdOut_ShouldReturnOneFileAndStdout() { - var arguments = ArgumentParser.TryParse(new[] { "build", "--stdout", "file1" }, IO, FileSystem); + var arguments = ArgumentParser.TryParse(["build", "--stdout", "file1"], IO, FileSystem); var buildArguments = (BuildArguments?)arguments; // using classic assert so R# understands the value is not null @@ -104,7 +104,7 @@ public void BuildOneFileStdOut_ShouldReturnOneFileAndStdout() [TestMethod] public void BuildOneFileStdOut_and_no_restore_ShouldReturnOneFileAndStdout() { - var arguments = ArgumentParser.TryParse(new[] { "build", "--stdout", "--no-restore", "file1" }, IO, FileSystem); + var arguments = ArgumentParser.TryParse(["build", "--stdout", "--no-restore", "file1"], IO, FileSystem); var buildArguments = (BuildArguments?)arguments; // using classic assert so R# understands the value is not null @@ -119,7 +119,7 @@ public void BuildOneFileStdOut_and_no_restore_ShouldReturnOneFileAndStdout() [TestMethod] public void BuildOneFileStdOutAllCaps_ShouldReturnOneFileAndStdout() { - var arguments = ArgumentParser.TryParse(new[] { "build", "--STDOUT", "file1" }, IO, FileSystem); + var arguments = ArgumentParser.TryParse(["build", "--STDOUT", "file1"], IO, FileSystem); var buildArguments = (BuildArguments?)arguments; // using classic assert so R# understands the value is not null @@ -135,7 +135,7 @@ public void BuildOneFileStdOutAllCaps_ShouldReturnOneFileAndStdout() public void Build_with_outputdir_parameter_should_parse_correctly() { // Use relative . to ensure directory exists else the parser will throw. - var arguments = ArgumentParser.TryParse(new[] { "build", "--outdir", ".", "file1" }, IO, FileSystem); + var arguments = ArgumentParser.TryParse(["build", "--outdir", ".", "file1"], IO, FileSystem); var buildArguments = (BuildArguments?)arguments; // using classic assert so R# understands the value is not null @@ -151,7 +151,7 @@ public void Build_with_outputdir_parameter_should_parse_correctly() [TestMethod] public void Build_with_outputfile_parameter_should_parse_correctly() { - var arguments = ArgumentParser.TryParse(new[] { "build", "--outfile", "jsonFile", "file1" }, IO, FileSystem); + var arguments = ArgumentParser.TryParse(["build", "--outfile", "jsonFile", "file1"], IO, FileSystem); var buildArguments = (BuildArguments?)arguments; // using classic assert so R# understands the value is not null @@ -166,7 +166,7 @@ public void Build_with_outputfile_parameter_should_parse_correctly() [TestMethod] public void Build_with_outputfile_and_no_restore_parameter_should_parse_correctly() { - var arguments = ArgumentParser.TryParse(new[] { "build", "--outfile", "jsonFile", "file1", "--no-restore" }, IO, FileSystem); + var arguments = ArgumentParser.TryParse(["build", "--outfile", "jsonFile", "file1", "--no-restore"], IO, FileSystem); var buildArguments = (BuildArguments?)arguments; // using classic assert so R# understands the value is not null @@ -181,7 +181,7 @@ public void Build_with_outputfile_and_no_restore_parameter_should_parse_correctl [TestMethod] public void License_argument_should_return_appropriate_RootArguments_instance() { - var arguments = ArgumentParser.TryParse(new[] { "--license" }, IO, FileSystem); + var arguments = ArgumentParser.TryParse(["--license"], IO, FileSystem); arguments.Should().BeOfType(); if (arguments is RootArguments rootArguments) @@ -196,7 +196,7 @@ public void License_argument_should_return_appropriate_RootArguments_instance() [TestMethod] public void Third_party_notices_argument_should_return_appropriate_RootArguments_instance() { - var arguments = ArgumentParser.TryParse(new[] { "--third-party-notices" }, IO, FileSystem); + var arguments = ArgumentParser.TryParse(["--third-party-notices"], IO, FileSystem); arguments.Should().BeOfType(); if (arguments is RootArguments rootArguments) @@ -211,7 +211,7 @@ public void Third_party_notices_argument_should_return_appropriate_RootArguments [TestMethod] public void Version_argument_should_return_VersionArguments_instance() { - var arguments = ArgumentParser.TryParse(new[] { "--version" }, IO, FileSystem); + var arguments = ArgumentParser.TryParse(["--version"], IO, FileSystem); arguments.Should().BeOfType(); if (arguments is RootArguments rootArguments) @@ -226,7 +226,7 @@ public void Version_argument_should_return_VersionArguments_instance() [TestMethod] public void Help_argument_should_return_HelpArguments_instance() { - var arguments = ArgumentParser.TryParse(new[] { "--help" }, IO, FileSystem); + var arguments = ArgumentParser.TryParse(["--help"], IO, FileSystem); arguments.Should().BeOfType(); if (arguments is RootArguments rootArguments) @@ -241,7 +241,7 @@ public void Help_argument_should_return_HelpArguments_instance() [TestMethod] public void Version_argument_should_return_VersionShortArguments_instance() { - var arguments = ArgumentParser.TryParse(new[] { "-v" }, IO, FileSystem); + var arguments = ArgumentParser.TryParse(["-v"], IO, FileSystem); arguments.Should().BeOfType(); if (arguments is RootArguments rootArguments) @@ -256,7 +256,7 @@ public void Version_argument_should_return_VersionShortArguments_instance() [TestMethod] public void Help_argument_should_return_HelpShortArguments_instance() { - var arguments = ArgumentParser.TryParse(new[] { "-h" }, IO, FileSystem); + var arguments = ArgumentParser.TryParse(["-h"], IO, FileSystem); arguments.Should().BeOfType(); if (arguments is RootArguments rootArguments) @@ -271,7 +271,7 @@ public void Help_argument_should_return_HelpShortArguments_instance() [TestMethod] public void DecompileOneFile_ShouldReturnOneFile() { - var arguments = ArgumentParser.TryParse(new[] { "decompile", "file1" }, IO, FileSystem); + var arguments = ArgumentParser.TryParse(["decompile", "file1"], IO, FileSystem); var bulidOrDecompileArguments = (DecompileArguments?)arguments; // using classic assert so R# understands the value is not null @@ -285,7 +285,7 @@ public void DecompileOneFile_ShouldReturnOneFile() [TestMethod] public void DecompileOneFileStdOut_ShouldReturnOneFileAndStdout() { - var arguments = ArgumentParser.TryParse(new[] { "decompile", "--stdout", "file1" }, IO, FileSystem); + var arguments = ArgumentParser.TryParse(["decompile", "--stdout", "file1"], IO, FileSystem); var bulidOrDecompileArguments = (DecompileArguments?)arguments; // using classic assert so R# understands the value is not null @@ -299,7 +299,7 @@ public void DecompileOneFileStdOut_ShouldReturnOneFileAndStdout() [TestMethod] public void DecompileOneFileStdOutAllCaps_ShouldReturnOneFileAndStdout() { - var arguments = ArgumentParser.TryParse(new[] { "decompile", "--STDOUT", "file1" }, IO, FileSystem); + var arguments = ArgumentParser.TryParse(["decompile", "--STDOUT", "file1"], IO, FileSystem); var bulidOrDecompileArguments = (DecompileArguments?)arguments; // using classic assert so R# understands the value is not null @@ -314,7 +314,7 @@ public void DecompileOneFileStdOutAllCaps_ShouldReturnOneFileAndStdout() public void Decompile_with_outputdir_parameter_should_parse_correctly() { // Use relative . to ensure directory exists else the parser will throw. - var arguments = ArgumentParser.TryParse(new[] { "decompile", "--outdir", ".", "file1" }, IO, FileSystem); + var arguments = ArgumentParser.TryParse(["decompile", "--outdir", ".", "file1"], IO, FileSystem); var bulidOrDecompileArguments = (DecompileArguments?)arguments; // using classic assert so R# understands the value is not null @@ -328,7 +328,7 @@ public void Decompile_with_outputdir_parameter_should_parse_correctly() [TestMethod] public void Decompile_with_outputfile_parameter_should_parse_correctly() { - var arguments = ArgumentParser.TryParse(new[] { "decompile", "--outfile", "jsonFile", "file1" }, IO, FileSystem); + var arguments = ArgumentParser.TryParse(["decompile", "--outfile", "jsonFile", "file1"], IO, FileSystem); var bulidOrDecompileArguments = (DecompileArguments?)arguments; // using classic assert so R# understands the value is not null @@ -342,7 +342,7 @@ public void Decompile_with_outputfile_parameter_should_parse_correctly() [TestMethod] public void Publish_should_parse_correctly() { - var arguments = ArgumentParser.TryParse(new[] { "publish", "file1", "--target", "target1" }, IO, FileSystem); + var arguments = ArgumentParser.TryParse(["publish", "file1", "--target", "target1"], IO, FileSystem); arguments.Should().BeOfType(); var typed = (PublishArguments)arguments!; @@ -354,7 +354,7 @@ public void Publish_should_parse_correctly() [TestMethod] public void Publish_with_no_restore_should_parse_correctly() { - var arguments = ArgumentParser.TryParse(new[] { "publish", "file1", "--target", "target1", "--no-restore" }, IO, FileSystem); + var arguments = ArgumentParser.TryParse(["publish", "file1", "--target", "target1", "--no-restore"], IO, FileSystem); arguments.Should().BeOfType(); var typed = (PublishArguments)arguments!; @@ -366,7 +366,7 @@ public void Publish_with_no_restore_should_parse_correctly() [TestMethod] public void Restore__with_no_force_should_parse_correctly() { - var arguments = ArgumentParser.TryParse(new[] { "restore", "file1" }, IO, FileSystem); + var arguments = ArgumentParser.TryParse(["restore", "file1"], IO, FileSystem); arguments.Should().BeOfType(); var typed = (RestoreArguments)arguments!; @@ -377,7 +377,7 @@ public void Restore__with_no_force_should_parse_correctly() [TestMethod] public void Restore_with_force_should_parse_correctly() { - var arguments = ArgumentParser.TryParse(new[] { "restore", "--force", "file1" }, IO, FileSystem); + var arguments = ArgumentParser.TryParse(["restore", "--force", "file1"], IO, FileSystem); arguments.Should().BeOfType(); var typed = (RestoreArguments)arguments!; diff --git a/src/Bicep.Cli/Helpers/ParamsFileHelper.cs b/src/Bicep.Cli/Helpers/ParamsFileHelper.cs index 2783c95ec5f..6ba2d337702 100644 --- a/src/Bicep.Cli/Helpers/ParamsFileHelper.cs +++ b/src/Bicep.Cli/Helpers/ParamsFileHelper.cs @@ -12,7 +12,7 @@ namespace Bicep.Cli.Helpers; public static class ParamsFileHelper { - private static readonly ImmutableHashSet SupportedJsonTokenTypes = new[] { JTokenType.Object, JTokenType.Array, JTokenType.String, JTokenType.Integer, JTokenType.Float, JTokenType.Boolean, JTokenType.Null }.ToImmutableHashSet(); + private static readonly ImmutableHashSet SupportedJsonTokenTypes = [JTokenType.Object, JTokenType.Array, JTokenType.String, JTokenType.Integer, JTokenType.Float, JTokenType.Boolean, JTokenType.Null]; private static SyntaxBase ConvertJsonToBicepSyntax(JToken token) => token switch diff --git a/src/Bicep.Cli/Rpc/CliJsonRpcServer.cs b/src/Bicep.Cli/Rpc/CliJsonRpcServer.cs index 29082e979e1..879e03a4e07 100644 --- a/src/Bicep.Cli/Rpc/CliJsonRpcServer.cs +++ b/src/Bicep.Cli/Rpc/CliJsonRpcServer.cs @@ -98,7 +98,7 @@ public async Task GetFileReferences(GetFileReferences } return new( - fileUris.Select(x => x.LocalPath).OrderBy(x => x).ToImmutableArray()); + [.. fileUris.Select(x => x.LocalPath).OrderBy(x => x)]); } public async Task GetMetadata(GetMetadataRequest request, CancellationToken cancellationToken) @@ -194,8 +194,8 @@ public async Task GetDeploymentGraph(GetDeploymentGr } return new( - nodesBySymbol.Values.OrderBy(x => x.Name).ToImmutableArray(), - edges.OrderBy(x => x.Source).ThenBy(x => x.Target).ToImmutableArray()); + [.. nodesBySymbol.Values.OrderBy(x => x.Name)], + [.. edges.OrderBy(x => x.Source).ThenBy(x => x.Target)]); } private static async Task GetSemanticModel(BicepCompiler compiler, string filePath) diff --git a/src/Bicep.Cli/Services/TemplateEvaluator.cs b/src/Bicep.Cli/Services/TemplateEvaluator.cs index 1d6bbbb445f..cbe59cc3389 100644 --- a/src/Bicep.Cli/Services/TemplateEvaluator.cs +++ b/src/Bicep.Cli/Services/TemplateEvaluator.cs @@ -183,7 +183,7 @@ private static TestEvaluation EvaluateTemplate(JToken? templateJtoken, JToken? p TemplateEngine.ValidateProcessedTemplate(template, TemplateWriter.NestedDeploymentResourceApiVersion, deploymentScope); - var allAssertions = template.Asserts?.Select(p => new AssertionResult(p.Key, (bool)p.Value.Value)).ToImmutableArray() ?? ImmutableArray.Empty; + var allAssertions = template.Asserts?.Select(p => new AssertionResult(p.Key, (bool)p.Value.Value)).ToImmutableArray() ?? []; var failedAssertions = allAssertions.Where(a => !a.Result).Select(a => a).ToImmutableArray(); return new TestEvaluation(template, null, allAssertions, failedAssertions); } @@ -191,7 +191,7 @@ private static TestEvaluation EvaluateTemplate(JToken? templateJtoken, JToken? p { var error = exception.Message; - return new TestEvaluation(null, error, ImmutableArray.Empty, ImmutableArray.Empty); + return new TestEvaluation(null, error, [], []); } } diff --git a/src/Bicep.Core.IntegrationTests/DirectResourceCollectionTests.cs b/src/Bicep.Core.IntegrationTests/DirectResourceCollectionTests.cs index e0cd84cb85e..e4eaa17ac09 100644 --- a/src/Bicep.Core.IntegrationTests/DirectResourceCollectionTests.cs +++ b/src/Bicep.Core.IntegrationTests/DirectResourceCollectionTests.cs @@ -421,8 +421,8 @@ private static string CreateReferencesBicepContent() private static (string fileName, string fileContents)[] CreateReferencesBicepContentWithModules() { - return new[] - { + return + [ ("main.bicep", """ resource containerWorkers 'Microsoft.ContainerInstance/containerGroups@2022-09-01' = [for i in range(0, 4): { name: 'gh9440-w1-${i}' @@ -491,7 +491,7 @@ private static (string fileName, string fileContents)[] CreateReferencesBicepCon output modOutput1 string = storage.properties.modInput1 """) - }; + ]; } } } diff --git a/src/Bicep.Core.IntegrationTests/Emit/TemplateEmitterTests.cs b/src/Bicep.Core.IntegrationTests/Emit/TemplateEmitterTests.cs index c86f52e5ded..1270fa26208 100644 --- a/src/Bicep.Core.IntegrationTests/Emit/TemplateEmitterTests.cs +++ b/src/Bicep.Core.IntegrationTests/Emit/TemplateEmitterTests.cs @@ -268,7 +268,7 @@ public void Multiline_strings_should_parse_correctly(string newlineSequence) var (template, _, _) = CompilationHelper.Compile(StringUtils.ReplaceNewlines(inputFile, newlineSequence)); - var expected = string.Join(newlineSequence, new[] { "this", " is", " a", " multiline", " string", "" }); + var expected = string.Join(newlineSequence, ["this", " is", " a", " multiline", " string", ""]); template.Should().HaveValueAtPath("$.variables.multiline", expected); } diff --git a/src/Bicep.Core.IntegrationTests/Extensibility/BarNamespaceType.cs b/src/Bicep.Core.IntegrationTests/Extensibility/BarNamespaceType.cs index 68cd27c7537..5dc4ab6fa7f 100644 --- a/src/Bicep.Core.IntegrationTests/Extensibility/BarNamespaceType.cs +++ b/src/Bicep.Core.IntegrationTests/Extensibility/BarNamespaceType.cs @@ -14,10 +14,10 @@ public static class BarNamespaceType { public const string BuiltInName = "bar"; - public static readonly ImmutableHashSet UniqueIdentifierProperties = new[] - { + public static readonly ImmutableHashSet UniqueIdentifierProperties = + [ "name", - }.ToImmutableHashSet(); + ]; public static NamespaceSettings Settings { get; } = new( IsSingleton: false, diff --git a/src/Bicep.Core.IntegrationTests/Extensibility/FooNamespaceType.cs b/src/Bicep.Core.IntegrationTests/Extensibility/FooNamespaceType.cs index 7d0d0c45dcf..b813ae3497f 100644 --- a/src/Bicep.Core.IntegrationTests/Extensibility/FooNamespaceType.cs +++ b/src/Bicep.Core.IntegrationTests/Extensibility/FooNamespaceType.cs @@ -14,10 +14,10 @@ public static class FooNamespaceType { public const string BuiltInName = "foo"; - public static readonly ImmutableHashSet UniqueIdentifierProperties = new[] - { + public static readonly ImmutableHashSet UniqueIdentifierProperties = + [ "uniqueName", - }.ToImmutableHashSet(); + ]; public static NamespaceSettings Settings { get; } = new( IsSingleton: true, diff --git a/src/Bicep.Core.IntegrationTests/NestedResourceTests.cs b/src/Bicep.Core.IntegrationTests/NestedResourceTests.cs index 908bd269d38..1c08c0063b0 100644 --- a/src/Bicep.Core.IntegrationTests/NestedResourceTests.cs +++ b/src/Bicep.Core.IntegrationTests/NestedResourceTests.cs @@ -404,10 +404,10 @@ public void NestedResources_ancestors_are_detected() model.ResourceAncestors.GetAncestors(parent).Should().BeEmpty(); var child = (DeclaredResourceMetadata)model.ResourceMetadata.TryLookup(model.DeclaredResources.Select(x => x.Symbol).Single(r => r.Name == "child").DeclaringSyntax)!; - model.ResourceAncestors.GetAncestors(child).Select(x => x.Resource).Should().Equal(new[] { parent, }); + model.ResourceAncestors.GetAncestors(child).Select(x => x.Resource).Should().Equal([parent,]); var grandchild = (DeclaredResourceMetadata)model.ResourceMetadata.TryLookup(model.DeclaredResources.Select(x => x.Symbol).Single(r => r.Name == "grandchild").DeclaringSyntax)!; - model.ResourceAncestors.GetAncestors(grandchild).Select(x => x.Resource).Should().Equal(new[] { parent, child, }); // order matters + model.ResourceAncestors.GetAncestors(grandchild).Select(x => x.Resource).Should().Equal([parent, child,]); // order matters } [TestMethod] @@ -452,16 +452,16 @@ public void NestedResources_scopes_isolate_names() model.ResourceAncestors.GetAncestors(parent).Should().BeEmpty(); var child = (DeclaredResourceMetadata)model.ResourceMetadata.TryLookup(model.DeclaredResources.Select(x => x.Symbol).Single(r => r.Name == "child").DeclaringSyntax)!; - model.ResourceAncestors.GetAncestors(child).Select(x => x.Resource).Should().Equal(new[] { parent, }); + model.ResourceAncestors.GetAncestors(child).Select(x => x.Resource).Should().Equal([parent,]); var childGrandChild = (DeclaredResourceMetadata)model.ResourceMetadata.TryLookup(child.Symbol.DeclaringResource.GetBody().Resources.Single())!; - model.ResourceAncestors.GetAncestors(childGrandChild).Select(x => x.Resource).Should().Equal(new[] { parent, child, }); + model.ResourceAncestors.GetAncestors(childGrandChild).Select(x => x.Resource).Should().Equal([parent, child,]); var sibling = (DeclaredResourceMetadata)model.ResourceMetadata.TryLookup(model.DeclaredResources.Select(x => x.Symbol).Single(r => r.Name == "sibling").DeclaringSyntax)!; - model.ResourceAncestors.GetAncestors(child).Select(x => x.Resource).Should().Equal(new[] { parent, }); + model.ResourceAncestors.GetAncestors(child).Select(x => x.Resource).Should().Equal([parent,]); var siblingGrandChild = (DeclaredResourceMetadata)model.ResourceMetadata.TryLookup(sibling.Symbol.DeclaringResource.GetBody().Resources.Single())!; - model.ResourceAncestors.GetAncestors(siblingGrandChild).Select(x => x.Resource).Should().Equal(new[] { parent, sibling, }); + model.ResourceAncestors.GetAncestors(siblingGrandChild).Select(x => x.Resource).Should().Equal([parent, sibling,]); } [TestMethod] // Should turn into positive test when support is added. diff --git a/src/Bicep.Core.IntegrationTests/Scenarios/NullabilityTests.cs b/src/Bicep.Core.IntegrationTests/Scenarios/NullabilityTests.cs index 8149380f9f9..054a490432c 100644 --- a/src/Bicep.Core.IntegrationTests/Scenarios/NullabilityTests.cs +++ b/src/Bicep.Core.IntegrationTests/Scenarios/NullabilityTests.cs @@ -37,13 +37,13 @@ public void Unexpectedly_nullable_types_raise_fixable_warning(string templateWit private static IEnumerable GetTemplatesWithSingleUnexpectedlyNullableValue() { - static object[] Case(string templateWithNullablyTypedValue, string templateWithNonNullAssertion, TypeSymbol expectedType, TypeSymbol actualType) => new object[] - { + static object[] Case(string templateWithNullablyTypedValue, string templateWithNonNullAssertion, TypeSymbol expectedType, TypeSymbol actualType) => + [ templateWithNullablyTypedValue, templateWithNonNullAssertion, expectedType, actualType, - }; + ]; return new[] { diff --git a/src/Bicep.Core.IntegrationTests/Semantics/ExpressionCollectorVisitor.cs b/src/Bicep.Core.IntegrationTests/Semantics/ExpressionCollectorVisitor.cs index 5710c74760d..27641c7d792 100644 --- a/src/Bicep.Core.IntegrationTests/Semantics/ExpressionCollectorVisitor.cs +++ b/src/Bicep.Core.IntegrationTests/Semantics/ExpressionCollectorVisitor.cs @@ -34,7 +34,7 @@ public static ImmutableArray Build(Expression expression) var visitor = new ExpressionCollectorVisitor(); visitor.Visit(expression); - return visitor.expressionList.ToImmutableArray(); + return [.. visitor.expressionList]; } public static string GetExpressionLoggingString( diff --git a/src/Bicep.Core.IntegrationTests/Semantics/NamespaceTests.cs b/src/Bicep.Core.IntegrationTests/Semantics/NamespaceTests.cs index d78f53855c1..2010a7bf570 100644 --- a/src/Bicep.Core.IntegrationTests/Semantics/NamespaceTests.cs +++ b/src/Bicep.Core.IntegrationTests/Semantics/NamespaceTests.cs @@ -52,7 +52,7 @@ public void FunctionsShouldHaveExpectedSignatures(INamespaceSymbol @namespace) private static IEnumerable GetNamespaces() { // local function - static object[] CreateRow(INamespaceSymbol @namespace) => new object[] { @namespace }; + static object[] CreateRow(INamespaceSymbol @namespace) => [@namespace]; var (_, _, compilation) = CompilationHelper.Compile(TestTypeHelper.CreateEmptyResourceTypeLoader(), ("main.bicep", string.Empty)); diff --git a/src/Bicep.Core.IntegrationTests/TypeSystem/TypeValidationTests.cs b/src/Bicep.Core.IntegrationTests/TypeSystem/TypeValidationTests.cs index 5c9c0afa66c..30249405812 100644 --- a/src/Bicep.Core.IntegrationTests/TypeSystem/TypeValidationTests.cs +++ b/src/Bicep.Core.IntegrationTests/TypeSystem/TypeValidationTests.cs @@ -380,7 +380,7 @@ public void Json_function_can_obtain_types_for_string_literal_json_args() var invalidPropAccess = objectJson.invalidProp "; - var model = GetSemanticModelForTest(program, Enumerable.Empty()); + var model = GetSemanticModelForTest(program, []); GetTypeForNamedSymbol(model, "objectJson").Name.Should().Be("object"); GetTypeForNamedSymbol(model, "propAccess").Name.Should().Be("'validValue'"); @@ -405,7 +405,7 @@ public void Json_function_returns_error_for_unparseable_json() var invalidJson = json('{""prop"": ""value') "; - var model = GetSemanticModelForTest(program, Enumerable.Empty()); + var model = GetSemanticModelForTest(program, []); GetTypeForNamedSymbol(model, "invalidJson").Name.Should().Be("error"); @@ -435,7 +435,7 @@ public void Items_function_builds_type_definition_from_source_type() var singleItemValue = itemsOutput[0].value "; - var model = GetSemanticModelForTest(program, Enumerable.Empty()); + var model = GetSemanticModelForTest(program, []); GetTypeForNamedSymbol(model, "itemsOutput").Name.Should().Be("object[]"); GetTypeForNamedSymbol(model, "singleItemKey").Name.Should().Be("'123' | 'DEF' | 'abc' | 'arr'"); @@ -451,7 +451,7 @@ public void Items_function_permits_any_and_returns_generic_type() var singleItemValue = itemsOutput[0].value "; - var model = GetSemanticModelForTest(program, Enumerable.Empty()); + var model = GetSemanticModelForTest(program, []); GetTypeForNamedSymbol(model, "itemsOutput").Name.Should().Be("object[]"); GetTypeForNamedSymbol(model, "singleItemKey").Name.Should().Be("string"); diff --git a/src/Bicep.Core.Samples/DataSetsExtensions.cs b/src/Bicep.Core.Samples/DataSetsExtensions.cs index fed911e0ed5..3d94605d196 100644 --- a/src/Bicep.Core.Samples/DataSetsExtensions.cs +++ b/src/Bicep.Core.Samples/DataSetsExtensions.cs @@ -22,7 +22,7 @@ public static class DataSetsExtensions { public static IEnumerable ToDynamicTestData(this IEnumerable source) => source.Select(ToDynamicTestData); - public static object[] ToDynamicTestData(this DataSet ds) => new object[] { ds }; + public static object[] ToDynamicTestData(this DataSet ds) => [ds]; public static bool HasCrLfNewlines(this DataSet dataSet) => dataSet.Name.EndsWith("_CRLF", StringComparison.Ordinal); @@ -70,7 +70,7 @@ public static IContainerRegistryClientFactory CreateMockRegistryClients(Immutabl clients.Add((targetReference.Registry, targetReference.Repository)); } - return RegistryHelper.CreateMockRegistryClients(clients.Concat(additionalClients).ToArray()).factoryMock; + return RegistryHelper.CreateMockRegistryClients([.. clients, .. additionalClients]).factoryMock; } public static ITemplateSpecRepositoryFactory CreateEmptyTemplateSpecRepositoryFactory() diff --git a/src/Bicep.Core.UnitTests/ApiVersion/ApiVersionProviderTests.cs b/src/Bicep.Core.UnitTests/ApiVersion/ApiVersionProviderTests.cs index 418fd7335b1..28d29d751c7 100644 --- a/src/Bicep.Core.UnitTests/ApiVersion/ApiVersionProviderTests.cs +++ b/src/Bicep.Core.UnitTests/ApiVersion/ApiVersionProviderTests.cs @@ -83,6 +83,6 @@ private ApiVersionProvider CreateDefaultApiVersionProvider(IEnumerable new( new FeatureProvider( IConfigurationManager.GetBuiltInConfiguration()), - resourceTypeReferences ?? Enumerable.Empty()); + resourceTypeReferences ?? []); } } diff --git a/src/Bicep.Core.UnitTests/Configuration/BicepConfigSchemaTests.cs b/src/Bicep.Core.UnitTests/Configuration/BicepConfigSchemaTests.cs index f0a0b31fee8..5a2e0433454 100644 --- a/src/Bicep.Core.UnitTests/Configuration/BicepConfigSchemaTests.cs +++ b/src/Bicep.Core.UnitTests/Configuration/BicepConfigSchemaTests.cs @@ -50,9 +50,9 @@ public IEnumerable GetData(MethodInfo methodInfo) private const string HelpFileName = "experimental-features.md"; // TODO: Remove these when they're fixed - private readonly string[] GrandfatheredFeaturesNeedingHelpOrDescription = { + private readonly string[] GrandfatheredFeaturesNeedingHelpOrDescription = [ "providerRegistry", - }; + ]; private static string GetBicepConfigSchemaContents() { @@ -101,7 +101,7 @@ private static (string Id, JObject Schema)[] AllRuleSchemas => private static IEnumerable GetRuleCustomConfigurationProperties(JObject ruleConfigSchema) { var properties = ruleConfigSchema.SelectToken("allOf[0].properties")?.OfType(); - return properties ?? Enumerable.Empty(); + return properties ?? []; } private IImmutableDictionary GetExperimentalFeaturesFromSchema() diff --git a/src/Bicep.Core.UnitTests/Configuration/RootConfigurationTests.cs b/src/Bicep.Core.UnitTests/Configuration/RootConfigurationTests.cs index 9e60ad343c9..2549ce083b0 100644 --- a/src/Bicep.Core.UnitTests/Configuration/RootConfigurationTests.cs +++ b/src/Bicep.Core.UnitTests/Configuration/RootConfigurationTests.cs @@ -37,11 +37,11 @@ private static IEnumerable GetTestData() return new[] { new object[] { "~", homeDirectory }, - new object[] { "~/", $"{homeDirectory}/" }, - new object[] { "~\\", $"{homeDirectory}\\" }, - new object[] { "~/foo/bar", $"{homeDirectory}/foo/bar" }, - new object[] { "~\\foo\\bar", $"{homeDirectory}\\foo\\bar" }, - new object[] { "~\\foo/bar", $"{homeDirectory}\\foo/bar" }, + ["~/", $"{homeDirectory}/"], + ["~\\", $"{homeDirectory}\\"], + ["~/foo/bar", $"{homeDirectory}/foo/bar"], + ["~\\foo\\bar", $"{homeDirectory}\\foo\\bar"], + ["~\\foo/bar", $"{homeDirectory}\\foo/bar"], }; } } diff --git a/src/Bicep.Core.UnitTests/Diagnostics/ErrorBuilderTests.cs b/src/Bicep.Core.UnitTests/Diagnostics/ErrorBuilderTests.cs index 9688fd9de59..8f86d422f44 100644 --- a/src/Bicep.Core.UnitTests/Diagnostics/ErrorBuilderTests.cs +++ b/src/Bicep.Core.UnitTests/Diagnostics/ErrorBuilderTests.cs @@ -130,7 +130,7 @@ private static object CreateMockParameter(ParameterInfo parameter, int index) if (parameter.ParameterType == typeof(Symbol)) { // just using this one as it's easy to construct - return ErrorType.Create(Enumerable.Empty()); + return ErrorType.Create([]); } if (parameter.ParameterType == typeof(int) || parameter.ParameterType == typeof(int?)) diff --git a/src/Bicep.Core.UnitTests/Diagnostics/LinterRuleTests/ArtifactsParametersRuleTests.cs b/src/Bicep.Core.UnitTests/Diagnostics/LinterRuleTests/ArtifactsParametersRuleTests.cs index d8ebc678786..3e265956257 100644 --- a/src/Bicep.Core.UnitTests/Diagnostics/LinterRuleTests/ArtifactsParametersRuleTests.cs +++ b/src/Bicep.Core.UnitTests/Diagnostics/LinterRuleTests/ArtifactsParametersRuleTests.cs @@ -31,10 +31,9 @@ public void MissingUnderscoreInParamNames_ArtifactsLocation_TreatAsNonArtifactsP @secure() param _artifactsLocationSasToken string = '' ", - new string[] - { + [ "If an '_artifactsLocationSasToken' parameter is provided, an '_artifactsLocation' parameter must also be provided.", - } + ] ); } [TestMethod] @@ -49,10 +48,9 @@ public void MissingUnderscoreInParamNames_SasToken_TreatAsNonArtifactsParameter( param artifactsLocationSasToken string = 'something' " , - new string[] - { + [ "If an '_artifactsLocation' parameter is provided, an '_artifactsLocationSasToken' parameter must also be provided.", - } + ] ); } [TestMethod] @@ -65,9 +63,7 @@ public void ArmTtk_DeploymentFunction_Pass() @secure() param _artifactsLocationSasToken string = '' ", - new string[] - { - } + [] ); } @@ -82,9 +78,7 @@ public void ArmTtk_RawRepoPath_Pass() @secure() param _artifactsLocationSasToken string = '' ", - new string[] - { - } + [] ); } @@ -97,9 +91,7 @@ param _artifactsLoc string @secure() param _artifactsLocSasToken string ", - new string[] - { - } + [] ); } @@ -118,12 +110,7 @@ param _artifactsLocation string @secure() param _artifactsLocationSasToken string ", - new string[] - { - // In the ARM TTK for a main template, this would have failed. For Bicep, we accept this for all templates, and instead check that explicit - // values for these parameters are passed in when a template with artifacts parameters is used as a module. - // as modules - } + [] ); } @@ -142,13 +129,12 @@ The _artifactsLocation parameter in "mainTemplate.json" must have a defaultValue @secure() param _artifactsLocationSasToken string ", - new string[] - { + [ // In the ARM TTK for a main template, this would have failed because the default value for _artifactsLocation is "missing". // For Bicep, we don't care if it's missing, but we don't accept an empty string. "If the '_artifactsLocation' parameter has a default value, it must be a raw URL or an expression like 'deployment().properties.templateLink.uri'." - } + ] ); } @@ -162,12 +148,7 @@ public void ArmTtk_MissingDefaults_SasToken_Pass() @secure() param _artifactsLocationSasToken string = '' ", - new string[] - { - // In the ARM TTK for a main template, this would have failed. For Bicep, we accept this for all templates, and instead check that explicit - // values for these parameters are passed in when a template with artifacts parameters is used as a module. - // as modules - } + [] ); } @@ -183,13 +164,12 @@ public void ArmTtk_MissingSas_Fail() @" param _artifactsLocation string = deployment().properties.templateLink.uri ", - new string[] - { + [ // In the ARM TTK for a main template, this would have failed for this reason: // The _artifactsLocationSasToken in "mainTemplate.json" has an incorrect defaultValue, must be an empty string // For Bicep we don't care about that, but still both parameters must be present if either of them are. "If an '_artifactsLocation' parameter is provided, an '_artifactsLocationSasToken' parameter must also be provided." - } + ] ); } @@ -200,13 +180,12 @@ public void ArmTtk_MissingLocation_Fail() @" param _artifactsLocationSasToken string ", - new string[] - { + [ // In the ARM TTK for a main template, this would have failed for this reason: // The _artifactsLocationSasToken in "mainTemplate.json" has an incorrect defaultValue, must be an empty string // For Bicep we don't care about that, but still both parameters must be present if either of them are. "If an '_artifactsLocationSasToken' parameter is provided, an '_artifactsLocation' parameter must also be provided." - } + ] ); } @@ -231,11 +210,10 @@ public void ArmTtk_WrongDefaults_Fail() @secure() param _artifactsLocationSasToken string = 'hard coded token' //this shouldn't be a default (use a param if needed) ", - new string[] - { + [ $"If the '_artifactsLocation' parameter has a default value, it must be a raw URL or an expression like 'deployment().properties.templateLink.uri'.", $"If the '_artifactsLocationSasToken' parameter has a default value, it must be an empty string.", - }); + ]); } [TestMethod] @@ -247,9 +225,7 @@ param _artifactsLocation string @secure() param _artifactsLocationSasToken string ", - new string[] - { - }); + []); } [TestMethod] public void WrongDefaults3_Fail() @@ -260,11 +236,10 @@ public void WrongDefaults3_Fail() @secure() param _artifactsLocationSasToken string = deployment().properties ", - new string[] - { + [ "If the '_artifactsLocation' parameter has a default value, it must be a raw URL or an expression like 'deployment().properties.templateLink.uri'.", "If the '_artifactsLocationSasToken' parameter has a default value, it must be an empty string.", - }, + ], OnCompileErrors.Ignore); } @@ -283,12 +258,11 @@ The _artifactsLocation parameter in "mainTemplate.json" must have a defaultValue param _artifactsLocation array //wrong type param _artifactsLocationSasToken int //wrong type ", - new string[] - { + [ "Artifacts parameter '_artifactsLocation' must be of type 'string'", "Artifacts parameter '_artifactsLocationSasToken' must be of type 'string'", "Artifacts parameter '_artifactsLocationSasToken' must use the @secure() attribute", - } + ] ); } @@ -307,10 +281,9 @@ The _artifactsLocation parameter in "mainTemplate.json" must have a defaultValue param _artifactsLocation string // okay param _artifactsLocationSasToken string // should be secure ", - new string[] - { + [ "Artifacts parameter '_artifactsLocationSasToken' must use the @secure() attribute" - } + ] ); } @@ -323,11 +296,10 @@ public void ArmTtk_WrongType_InterpolatedString_Pass() @secure() param _artifactsLocationSasToken string = '${'a'}${'b'}' ", - new string[] - { + [ "If the '_artifactsLocation' parameter has a default value, it must be a raw URL or an expression like 'deployment().properties.templateLink.uri'.", "If the '_artifactsLocationSasToken' parameter has a default value, it must be an empty string." - } + ] ); } @@ -340,11 +312,10 @@ public void ArmTtk_WrongType_StringExpression_TypesOkay() @secure() param _artifactsLocationSasToken string = resourceGroup().location ", - new string[] - { + [ "If the '_artifactsLocation' parameter has a default value, it must be a raw URL or an expression like 'deployment().properties.templateLink.uri'.", "If the '_artifactsLocationSasToken' parameter has a default value, it must be an empty string.", - } + ] ); } @@ -360,11 +331,10 @@ public void ArmTtk_WrongType_StringVariable_TypesOkay() @secure() param _artifactsLocationSasToken string = emptyString ", - new string[] - { + [ "If the '_artifactsLocation' parameter has a default value, it must be a raw URL or an expression like 'deployment().properties.templateLink.uri'.", "If the '_artifactsLocationSasToken' parameter has a default value, it must be an empty string.", - } + ] ); } @@ -377,11 +347,10 @@ public void CaseInsensitive() @secure() param _artifactsLocationSASToken string = 'bad default' ", - new string[] - { + [ "If the '_artifactsLocation' parameter has a default value, it must be a raw URL or an expression like 'deployment().properties.templateLink.uri'.", "If the '_artifactsLocationSasToken' parameter has a default value, it must be an empty string.", - } + ] ); } @@ -394,9 +363,7 @@ param _artifactsLocation @secure() param _artifactsLocationSASToken ", - new string[] - { - }, + [], OnCompileErrors.Ignore ); } @@ -421,7 +388,7 @@ param adminUsername string public void ReferencingModulesWithArtifactsParameters_Pass() { var result = CompilationHelper.Compile( - new (string fileName, string fileContents)[] { + [ ("createVM.bicep", CreateVMBicepContents), ("main.bicep", @" module creatingVM 'createVM.bicep' = { @@ -433,7 +400,7 @@ public void ReferencingModulesWithArtifactsParameters_Pass() adminUsername: 'adminUsername' } } - ")}); + ")]); result.Diagnostics.Should().NotHaveAnyDiagnostics(); } @@ -442,7 +409,7 @@ public void ReferencingModulesWithArtifactsParameters_Pass() public void ReferencingModulesWithArtifactsParameters_Fail() { var result = CompilationHelper.Compile( - new (string fileName, string fileContents)[] { + [ ("createVM.bicep", CreateVMBicepContents), ("main.bicep", @" module creatingVM 'createVM.bicep' = { @@ -452,7 +419,7 @@ public void ReferencingModulesWithArtifactsParameters_Fail() adminUsername: 'adminUsername' } } - ")}); + ")]); result.Diagnostics.Should().ContainDiagnostic("artifacts-parameters", DiagnosticLevel.Warning, "Parameter '_artifactsLocationSasToken' of module 'creatingVM' should be assigned an explicit value."); result.Diagnostics.Should().ContainDiagnostic("artifacts-parameters", DiagnosticLevel.Warning, "Parameter '_artifactsLocation' of module 'creatingVM' should be assigned an explicit value."); diff --git a/src/Bicep.Core.UnitTests/Diagnostics/LinterRuleTests/NoLocationExprOutsideParamsRuleTests.cs b/src/Bicep.Core.UnitTests/Diagnostics/LinterRuleTests/NoLocationExprOutsideParamsRuleTests.cs index ef333acd693..f850936d631 100644 --- a/src/Bicep.Core.UnitTests/Diagnostics/LinterRuleTests/NoLocationExprOutsideParamsRuleTests.cs +++ b/src/Bicep.Core.UnitTests/Diagnostics/LinterRuleTests/NoLocationExprOutsideParamsRuleTests.cs @@ -34,12 +34,12 @@ private static CompilationResult Compile(string fileContents) protected void ExpectPass(string bicepText, Options? options = null) { - AssertLinterRuleDiagnostics(NoLocationExprOutsideParamsRule.Code, bicepText, new string[] { }, options); + AssertLinterRuleDiagnostics(NoLocationExprOutsideParamsRule.Code, bicepText, [], options); } protected void ExpectFail(string bicepText, string expectedMessage) { - AssertLinterRuleDiagnostics(NoLocationExprOutsideParamsRule.Code, bicepText, new string[] { expectedMessage }); + AssertLinterRuleDiagnostics(NoLocationExprOutsideParamsRule.Code, bicepText, [expectedMessage]); } protected void ExpectFailWithFix(string bicepText, string expectedMessage, ExpectedCodeFix expectedFix) diff --git a/src/Bicep.Core.UnitTests/Diagnostics/LinterRuleTests/NoUnnecessaryDependsOnRuleTests.cs b/src/Bicep.Core.UnitTests/Diagnostics/LinterRuleTests/NoUnnecessaryDependsOnRuleTests.cs index 588562bab8a..f98ab2e0b56 100644 --- a/src/Bicep.Core.UnitTests/Diagnostics/LinterRuleTests/NoUnnecessaryDependsOnRuleTests.cs +++ b/src/Bicep.Core.UnitTests/Diagnostics/LinterRuleTests/NoUnnecessaryDependsOnRuleTests.cs @@ -60,7 +60,7 @@ public void If_No_Simple_UnnecessaryDependsOn_ShouldPass() } ", OnCompileErrors.IncludeErrors, - System.Array.Empty() + [] ); } @@ -94,8 +94,8 @@ public void DependsOn_Property_NotAtTopLevelOfResource_ShouldNotBeIgnoredForDepe } ", OnCompileErrors.IncludeErrors, - new string[] { - "Remove unnecessary dependsOn entry 'appServicePlan'."} + [ + "Remove unnecessary dependsOn entry 'appServicePlan'."] ); } @@ -126,9 +126,9 @@ public void If_SimpleUnnecessaryDependsOn_ShouldFail() } ", OnCompileErrors.IncludeErrors, - new string[] { + [ "Remove unnecessary dependsOn entry 'appServicePlan'." - } + ] ); } @@ -157,9 +157,9 @@ public void If_SimpleUnnecessaryDependsOn_InModule_ShouldFail() } ", OnCompileErrors.Ignore, - new string[] { + [ "Remove unnecessary dependsOn entry 'storageaccount'." - } + ] ); } @@ -189,9 +189,9 @@ public void If_Indirect_UnnecessaryDependsOn_ShouldFail() } ", OnCompileErrors.IncludeErrors, - new string[] { + [ "Remove unnecessary dependsOn entry 'appServicePlan'." - }); + ]); } [TestMethod] @@ -223,10 +223,10 @@ public void If_Explicit_DependsOn_ToAncestor_FromNestedChild_ShouldFail() } ", OnCompileErrors.IncludeErrors, - new string[] { + [ "" + "Remove unnecessary dependsOn entry 'vnet'." - }); + ]); } [TestMethod] @@ -258,9 +258,9 @@ public void If_Explicit_DependsOn_ToAncestor_FromTopLevelChild_ShouldFail() } ", OnCompileErrors.IncludeErrors, - new string[] { + [ "Remove unnecessary dependsOn entry 'vnet'." - } + ] ); } @@ -293,10 +293,10 @@ public void If_DuplicateEntries_ShouldFailForEach() } ", OnCompileErrors.IncludeErrors, - new string[] { + [ "Remove unnecessary dependsOn entry 'vn'.", - "Remove unnecessary dependsOn entry 'vn'." - } + "Remove unnecessary dependsOn entry 'vn'." + ] ); } @@ -338,12 +338,12 @@ public void If_Explicit_DependsOn_ToParent_FromGrandChild_UsingColonNotation_Sho } ", OnCompileErrors.IncludeErrors, - new string[] { + [ "Remove unnecessary dependsOn entry 'grandparent'.", "Remove unnecessary dependsOn entry 'parent'.", "Remove unnecessary dependsOn entry 'parent'.", "Remove unnecessary dependsOn entry 'grandchild'.", - }); + ]); } [TestMethod] @@ -363,9 +363,9 @@ public void If_UnnecessaryReferenceToParent_FromLoop_ToNonLoopedParent_Should_Fa }] ", OnCompileErrors.IncludeErrors, - new string[] { + [ "Remove unnecessary dependsOn entry 'vn'." - } + ] ); } @@ -386,7 +386,7 @@ public void If_ReferencesResourceByIndex_Simple_Should_IgnoreAndPass() }] ", OnCompileErrors.IncludeErrors, - System.Array.Empty() + [] ); } @@ -427,7 +427,7 @@ param storageAccounts array } ", OnCompileErrors.IncludeErrors, - System.Array.Empty() + [] ); } @@ -448,7 +448,7 @@ public void If_ReferencesResourceCollection_Should_IgnoreAndPass() }] ", OnCompileErrors.IncludeErrors, - System.Array.Empty() + [] ); } @@ -489,7 +489,7 @@ public void TolerantOfSyntaxErrors_1() } ", OnCompileErrors.Ignore, - System.Array.Empty() + [] ); } @@ -516,7 +516,7 @@ public void TolerantOfSyntaxErrors_2() } ", OnCompileErrors.Ignore, - System.Array.Empty() + [] ); } @@ -557,7 +557,7 @@ public void Test_Issue1986_loops() }] ", OnCompileErrors.Ignore, - System.Array.Empty() + [] ); } diff --git a/src/Bicep.Core.UnitTests/Diagnostics/LinterRuleTests/PreferInterpolationRuleTests.cs b/src/Bicep.Core.UnitTests/Diagnostics/LinterRuleTests/PreferInterpolationRuleTests.cs index 48220833ca6..eba5a0bebb0 100644 --- a/src/Bicep.Core.UnitTests/Diagnostics/LinterRuleTests/PreferInterpolationRuleTests.cs +++ b/src/Bicep.Core.UnitTests/Diagnostics/LinterRuleTests/PreferInterpolationRuleTests.cs @@ -26,7 +26,7 @@ private void ExpectPass(string text, OnCompileErrors onCompileErrors = OnCompile private void ExpectDiagnosticWithFix(string text, string expectedFix, Options? options = null) { - ExpectDiagnosticWithFix(text, new string[] { expectedFix }, options); + ExpectDiagnosticWithFix(text, [expectedFix], options); } private void ExpectDiagnosticWithFix(string text, string[] expectedFixes, Options? options = null) diff --git a/src/Bicep.Core.UnitTests/Diagnostics/LinterRuleTests/PreferUnquotedPropertyNamesRuleTests.cs b/src/Bicep.Core.UnitTests/Diagnostics/LinterRuleTests/PreferUnquotedPropertyNamesRuleTests.cs index 2ce8fc8e790..6e054f8172a 100644 --- a/src/Bicep.Core.UnitTests/Diagnostics/LinterRuleTests/PreferUnquotedPropertyNamesRuleTests.cs +++ b/src/Bicep.Core.UnitTests/Diagnostics/LinterRuleTests/PreferUnquotedPropertyNamesRuleTests.cs @@ -14,7 +14,7 @@ public class PreferUnquotedPropertyNamesRuleTests : LinterRuleTestsBase { private void ExpectPass(string text) { - AssertLinterRuleDiagnostics(PreferUnquotedPropertyNamesRule.Code, text, Array.Empty()); + AssertLinterRuleDiagnostics(PreferUnquotedPropertyNamesRule.Code, text, []); } private void ExpectDiagnosticWithFix(string text, string expectedFix) diff --git a/src/Bicep.Core.UnitTests/Diagnostics/LinterRuleTests/SecureParamsInNestedDeploymentsRuleTests.cs b/src/Bicep.Core.UnitTests/Diagnostics/LinterRuleTests/SecureParamsInNestedDeploymentsRuleTests.cs index 031e4eaaa3d..896765e7d21 100644 --- a/src/Bicep.Core.UnitTests/Diagnostics/LinterRuleTests/SecureParamsInNestedDeploymentsRuleTests.cs +++ b/src/Bicep.Core.UnitTests/Diagnostics/LinterRuleTests/SecureParamsInNestedDeploymentsRuleTests.cs @@ -54,9 +54,7 @@ param stgAccountName string } } }", - new string[] - { - }); + []); } [TestMethod] @@ -94,9 +92,7 @@ param stgAccountName string } } }", - new string[] - { - }); + []); } [TestMethod] @@ -133,9 +129,7 @@ param stgAccountName string } } }", - new string[] - { - }); + []); } [TestMethod] @@ -170,9 +164,7 @@ param stgAccountName string } } }", - new string[] - { - }); + []); } [TestMethod] @@ -215,10 +207,9 @@ param stgAccountName2 string } } ", - new[] - { + [ "[5] 'nested' is an outer scoped nested deployment that accesses secure string parameters ('stgAccountName2'), which could expose their values in deployment history. Either set the deployment's properties.expressionEvaluationOptions.scope to 'inner' or use a Bicep module instead." - }); + ]); } [TestMethod] @@ -256,10 +247,9 @@ param stgAccountName2 string } } ", - new[] - { + [ "[5] 'nested' is an outer scoped nested deployment that accesses secure string parameters ('stgAccountName2'), which could expose their values in deployment history. Either set the deployment's properties.expressionEvaluationOptions.scope to 'inner' or use a Bicep module instead." - }); + ]); } @@ -302,10 +292,9 @@ param stgAccountName string } } }", - new[] - { + [ "[6] 'nested' is an outer scoped nested deployment that accesses secure string parameters ('stgAccountName'), which could expose their values in deployment history. Either set the deployment's properties.expressionEvaluationOptions.scope to 'inner' or use a Bicep module instead." - }); + ]); } [TestMethod] @@ -341,11 +330,10 @@ param stgAccountName string } } }", - new string[] - { + [ "[6] The specified \"resource\" declaration is missing the following required properties: \"properties\". If this is an inaccuracy in the documentation, please report it to the Bicep Team.", "[8] The property \"propertiesWhoopsMisspelled\" is not allowed on objects of type \"Microsoft.Resources/deployments\". Permissible properties include \"asserts\", \"dependsOn\", \"location\", \"properties\", \"resourceGroup\", \"scope\", \"subscriptionId\", \"tags\". If this is an inaccuracy in the documentation, please report it to the Bicep Team.", - }); + ]); } [TestMethod] @@ -368,9 +356,7 @@ param abc string } } }", - new string[] - { - }); + []); } [TestMethod] @@ -409,10 +395,9 @@ param stgAccountName string } } ", - new[] - { + [ "[5] 'nested' is an outer scoped nested deployment that accesses secure string parameters ('stgAccountName'), which could expose their values in deployment history. Either set the deployment's properties.expressionEvaluationOptions.scope to 'inner' or use a Bicep module instead.", - }); + ]); } [TestMethod] @@ -448,10 +433,9 @@ param stgAccountName string } } }", - new string[] - { + [ "[6] Resource type \"Microsoft.Resources/notDeployments@2021-04-01\" does not have types available. Bicep is unable to validate resource properties prior to deployment, but this will not block the resource from being deployed." - }); + ]); } [TestMethod] @@ -491,9 +475,7 @@ param stgAccountName2 string } } ", - new string[] - { - }); + []); } [TestMethod] @@ -535,10 +517,9 @@ param stgAccountName3 object } } ", - new string[] - { + [ "[12] 'nested' is an outer scoped nested deployment that accesses secure string parameters ('stgAccountName', 'stgAccountName2'), which could expose their values in deployment history. Either set the deployment's properties.expressionEvaluationOptions.scope to 'inner' or use a Bicep module instead.", - }); + ]); } [TestMethod] @@ -579,10 +560,9 @@ public void ListKeys_Fail() } } ", - new string[] - { + [ "[6] 'nested' is an outer scoped nested deployment that calls a list* function (\"listKeys('someResourceId', '2020-01-01')\"), which could expose sensitive values in deployment history. Either set the deployment's properties.expressionEvaluationOptions.scope to 'inner' or use a Bicep module instead.", - }); + ]); } [TestMethod] @@ -623,10 +603,9 @@ public void AzListKeys_Fail() } } ", - new string[] - { + [ "[6] 'nested' is an outer scoped nested deployment that calls a list* function (\"az.listKeys('someResourceId', '2020-01-01')\"), which could expose sensitive values in deployment history. Either set the deployment's properties.expressionEvaluationOptions.scope to 'inner' or use a Bicep module instead.", - }); + ]); } [TestMethod] @@ -663,10 +642,9 @@ public void FooListKeys_Ignore() } } ", - new string[] - { + [ "[21] The name \"foo\" does not exist in the current context.", - }); + ]); } [TestMethod] @@ -702,10 +680,9 @@ param stgAccountName string } } }", - new[] - { + [ "[6] 'nested' is an outer scoped nested deployment that accesses secure string parameters ('stgAccountName'), which could expose their values in deployment history. Either set the deployment's properties.expressionEvaluationOptions.scope to 'inner' or use a Bicep module instead.", - }); + ]); } [TestMethod] @@ -742,10 +719,9 @@ public void ListKeys_InLoop_Fail() } }] ", - new string[] - { + [ "[2] 'nested' is an outer scoped nested deployment that calls a list* function (\"listKeys('someResourceId', '2020-01-01')\"), which could expose sensitive values in deployment history. Either set the deployment's properties.expressionEvaluationOptions.scope to 'inner' or use a Bicep module instead.", - }); + ]); } } } diff --git a/src/Bicep.Core.UnitTests/Diagnostics/LinterRuleTests/UseParentPropertyRuleTests.cs b/src/Bicep.Core.UnitTests/Diagnostics/LinterRuleTests/UseParentPropertyRuleTests.cs index 5fe64fdd454..6eb991d924a 100644 --- a/src/Bicep.Core.UnitTests/Diagnostics/LinterRuleTests/UseParentPropertyRuleTests.cs +++ b/src/Bicep.Core.UnitTests/Diagnostics/LinterRuleTests/UseParentPropertyRuleTests.cs @@ -13,7 +13,7 @@ private void AssertCodeFix(string inputFile, string resultFile) => AssertCodeFix(UseParentPropertyRule.Code, "Use parent property", inputFile, resultFile); private void AssertNoDiagnostics(string inputFile) - => AssertLinterRuleDiagnostics(UseParentPropertyRule.Code, inputFile, new string[] { }, new Options(OnCompileErrors.Ignore, IncludePosition.None)); + => AssertLinterRuleDiagnostics(UseParentPropertyRule.Code, inputFile, [], new Options(OnCompileErrors.Ignore, IncludePosition.None)); [TestMethod] public void Codefix_handles_parent_name_expression() => AssertCodeFix(@" diff --git a/src/Bicep.Core.UnitTests/Diagnostics/LinterRuleTests/UseProtectedSettingsForCommandToExecuteSecretsRuleTests.cs b/src/Bicep.Core.UnitTests/Diagnostics/LinterRuleTests/UseProtectedSettingsForCommandToExecuteSecretsRuleTests.cs index 44dcd774469..208d942d8f7 100644 --- a/src/Bicep.Core.UnitTests/Diagnostics/LinterRuleTests/UseProtectedSettingsForCommandToExecuteSecretsRuleTests.cs +++ b/src/Bicep.Core.UnitTests/Diagnostics/LinterRuleTests/UseProtectedSettingsForCommandToExecuteSecretsRuleTests.cs @@ -46,12 +46,12 @@ param fileUris string } } ", - new string[] { + [ // TTK error message: // [-] CommandToExecute Must Use ProtectedSettings For Secrets (62 ms) // CommandToExecute references parameter 'arguments' of type 'securestring', but is not in .protectedSettings "[23] Use protectedSettings for commandToExecute secrets. Found possible secret: secure value 'arguments'" - } + ] ); } @@ -87,9 +87,9 @@ param fileUris string } } ", - new string[] { + [ "[23] Use protectedSettings for commandToExecute secrets. Found possible secret: secure value 'arguments'" - } + ] ); } @@ -186,9 +186,9 @@ param adminPasswordOrKey string } } ", - new string[] { + [ "[84] Use protectedSettings for commandToExecute secrets. Found possible secret: secure value 'adminPasswordOrKey'" - } + ] ); } @@ -219,9 +219,9 @@ param commandToExecute string } } ", - new string[] { + [ "[17] Use protectedSettings for commandToExecute secrets. Found possible secret: secure value 'commandToExecute'" - } + ] ); } @@ -252,7 +252,7 @@ param commandToExecute string } } ", - new string[] { } + [] ); } @@ -287,7 +287,7 @@ param fileUris string } } ", - new string[] { } + [] ); } @@ -322,7 +322,7 @@ param fileUris string } } ", - new string[] { } + [] ); } @@ -358,7 +358,7 @@ param fileUris string } } ", - new string[] { } + [] ); } @@ -387,9 +387,9 @@ param siteFQDN string } } ", - new string[] { + [ "[18] Use protectedSettings for commandToExecute secrets. Found possible secret: function 'listKeys'" - } + ] ); } @@ -419,9 +419,9 @@ param fileUris string } } ", - new string[] { + [ "[19] Use protectedSettings for commandToExecute secrets. Found possible secret: function 'listKeys'" - } + ] ); } diff --git a/src/Bicep.Core.UnitTests/Diagnostics/LinterRuleTests/UseRecentApiVersionRuleTests.cs b/src/Bicep.Core.UnitTests/Diagnostics/LinterRuleTests/UseRecentApiVersionRuleTests.cs index 1f9e0fde290..c52c3ab9700 100644 --- a/src/Bicep.Core.UnitTests/Diagnostics/LinterRuleTests/UseRecentApiVersionRuleTests.cs +++ b/src/Bicep.Core.UnitTests/Diagnostics/LinterRuleTests/UseRecentApiVersionRuleTests.cs @@ -144,7 +144,7 @@ private static void TestGetAcceptableApiVersions(string fullyQualifiedResourceTy VerifyAllTypesAndDatesAreFake(resourceTypes); VerifyAllTypesAndDatesAreFake(expectedApiVersions); - var apiVersionProvider = new ApiVersionProvider(BicepTestConstants.Features, Enumerable.Empty()); + var apiVersionProvider = new ApiVersionProvider(BicepTestConstants.Features, []); apiVersionProvider.InjectTypeReferences(scope, FakeResourceTypes.GetFakeResourceTypeReferences(resourceTypes)); var (_, allowedVersions) = UseRecentApiVersionRule.GetAcceptableApiVersions(apiVersionProvider, AzureResourceApiVersion.Parse(today).Date, maxAgeInDays, scope, fullyQualifiedResourceType); var allowedVersionsStrings = allowedVersions.Select(v => v.ToString()).ToArray(); @@ -916,7 +916,7 @@ private static void Test( { string[] gaVersions = gaVersionDates.Select(d => "Whoever.whatever/whichever@" + CreateApiVersion(d)).ToArray(); string[] previewVersions = previewVersionDates.Select(d => "Whoever.whatever/whichever@" + CreateApiVersion(d) + "-preview").ToArray(); - var apiVersionProvider = new ApiVersionProvider(BicepTestConstants.Features, Enumerable.Empty()); + var apiVersionProvider = new ApiVersionProvider(BicepTestConstants.Features, []); apiVersionProvider.InjectTypeReferences(ResourceScope.ResourceGroup, FakeResourceTypes.GetFakeResourceTypeReferences(gaVersions.Concat(previewVersions))); var result = UseRecentApiVersionRule.AnalyzeApiVersion( @@ -942,7 +942,7 @@ private static void Test( (string.Join(", ", result.AcceptableVersions.Select(v => v.ToString()))).Should().Be(expectedFix.Value.acceptableVersions); result.Fixes.Should().HaveCount(1); // Right now we only create one fix result.Fixes[0].Replacements.Should().SatisfyRespectively(r => r.Span.Should().Be(new TextSpan(17, 47))); - result.Fixes[0].Replacements.Select(r => r.Text).Should().BeEquivalentTo(new string[] { expectedFix.Value.replacement }); + result.Fixes[0].Replacements.Select(r => r.Text).Should().BeEquivalentTo([expectedFix.Value.replacement]); } } @@ -1131,7 +1131,7 @@ public void WithRecentPreviewVersion_WhenRecentGAVersionIsSameAsPreviewVersion_S DateOnly recentGAVersionDate = currentVersionDate; string recentGAVersion = CreateApiVersion(recentGAVersionDate); - Test(currentVersionDate, "-preview", new DateOnly[] { recentGAVersionDate }, new DateOnly[] { currentVersionDate }, + Test(currentVersionDate, "-preview", [recentGAVersionDate], [currentVersionDate], ( $"Use more recent API version for 'Whoever.whatever/whichever'. '{currentVersion}' is a preview version and there is a non-preview version available with the same date.", acceptableVersions: recentGAVersion, @@ -1190,7 +1190,7 @@ public void ArmTtk_ApiVersionIsNotAnExpression_Error() ResourceScope.ResourceGroup, FakeResourceTypes.ResourceScopeTypes, "2422-07-04", - new string[] { "[2] The resource type is not valid. Specify a valid resource type of format \"@\"." }); + ["[2] The resource type is not valid. Specify a valid resource type of format \"@\"."]); } [TestMethod] @@ -1239,12 +1239,12 @@ param location string ResourceScope.ResourceGroup, FakeResourceTypes.ResourceScopeTypes, "2422-07-04", - new string[] { + [ "[4] Use more recent API version for 'fake.ServiceBus/namespaces'. '2418-01-01-preview' is 1645 days old, should be no more than 730 days old, or the most recent. Acceptable versions: 2421-06-01-preview, 2421-01-01-preview, 2417-04-01", "[18] Use more recent API version for 'fake.ServiceBus/namespaces/queues/authorizationRules'. '2415-08-01' is 2529 days old, should be no more than 730 days old, or the most recent. Acceptable versions: 2421-06-01-preview, 2421-01-01-preview, 2417-04-01", "[29] Use more recent API version for 'fake.ServiceBus/namespaces/queues/authorizationRules'. '2418-01-01-preview' is 1645 days old, should be no more than 730 days old, or the most recent. Acceptable versions: 2421-06-01-preview, 2421-01-01-preview, 2417-04-01", "[35] Could not find apiVersion 4017-04-01 for fake.ServiceBus/namespaces/queues/authorizationRules. Acceptable versions: 2421-06-01-preview, 2421-01-01-preview, 2417-04-01", - }); + ]); } [TestMethod] @@ -1284,13 +1284,13 @@ param location string ResourceScope.ResourceGroup, FakeResourceTypes.ResourceScopeTypes, "2422-07-04", - new[] { + [ "[5] Use more recent API version for 'fake.ServiceBus/namespaces'. '2418-01-01-preview' is 1645 days old, should be no more than 730 days old, or the most recent. Acceptable versions: 2421-06-01-preview, 2421-01-01-preview, 2417-04-01", "[9] Use more recent API version for 'fake.ServiceBus/namespaces/queues'. '2415-08-01' is 2529 days old, should be no more than 730 days old, or the most recent. Acceptable versions: 2421-06-01-preview, 2421-01-01-preview, 2417-04-01", "[13] Use more recent API version for 'fake.ServiceBus/namespaces/queues/authorizationRules'. '2418-01-01-preview' is 1645 days old, should be no more than 730 days old, or the most recent. Acceptable versions: 2421-06-01-preview, 2421-01-01-preview, 2417-04-01", "[20] Use more recent API version for 'fake.ServiceBus/namespaces/queues/authorizationRules'. '2415-08-01' is 2529 days old, should be no more than 730 days old, or the most recent. Acceptable versions: 2421-06-01-preview, 2421-01-01-preview, 2417-04-01", "[25] Use more recent API version for 'fake.ServiceBus/namespaces/queues/authorizationRules'. '2415-08-01' is 2529 days old, should be no more than 730 days old, or the most recent. Acceptable versions: 2421-06-01-preview, 2421-01-01-preview, 2417-04-01", - }); + ]); } [TestMethod] @@ -1315,9 +1315,9 @@ public void ArmTtk_NotAString_Error() ResourceScope.ResourceGroup, FakeResourceTypes.ResourceScopeTypes, "2422-07-04", - new string[] { + [ "[2] The resource type is not valid. Specify a valid resource type of format \"@\"." - }); + ]); } [TestMethod] @@ -1340,15 +1340,14 @@ public void ArmTtk_PreviewWhenNonPreviewIsAvailable_WithSameDateAsStable_Fail() CompileAndTestWithFakeDateAndTypes( bicep, ResourceScope.ResourceGroup, - new string[] - { + [ "Fake.DBforMySQL/servers@2417-12-01", - "Fake.DBforMySQL/servers@2417-12-01-preview", - }, + "Fake.DBforMySQL/servers@2417-12-01-preview", + ], fakeToday: "2422-07-04", - new[] { + [ "[2] Use more recent API version for 'fake.DBforMySQL/servers'. '2417-12-01-preview' is 1676 days old, should be no more than 730 days old, or the most recent. Acceptable versions: 2417-12-01", - }); + ]); } [TestMethod] @@ -1371,15 +1370,14 @@ public void ArmTtk_PreviewWhenNonPreviewIsAvailable_WithLaterDateThanStable_Fail CompileAndTestWithFakeDateAndTypes( bicep, ResourceScope.ResourceGroup, - new string[] - { + [ "Fake.DBforMySQL/servers@2417-12-02", - "Fake.DBforMySQL/servers@2417-12-01-preview", - }, + "Fake.DBforMySQL/servers@2417-12-01-preview", + ], fakeToday: "2422-07-04", - new[] { + [ "[2] Use more recent API version for 'fake.DBforMySQL/servers'. '2417-12-01-preview' is 1676 days old, should be no more than 730 days old, or the most recent. Acceptable versions: 2417-12-02", - }); + ]); } [TestMethod] @@ -1402,15 +1400,14 @@ public void ArmTtk_PreviewWhenNonPreviewIsAvailable_WithEarlierDateThanStable_Pa CompileAndTestWithFakeDateAndTypes( bicep, ResourceScope.ResourceGroup, - new string[] - { + [ "Fake.DBforMySQL/servers@2417-11-30", "Fake.DBforMySQL/servers@2417-12-01-preview", - }, + ], fakeToday: "2422-07-04", - new[] { + [ "[2] Use more recent API version for 'fake.DBforMySQL/servers'. '2417-12-01-preview' is 1676 days old, should be no more than 730 days old, or the most recent. Acceptable versions: 2417-11-30", - }); + ]); } [TestMethod] @@ -1427,13 +1424,12 @@ public void ArmTtk_OnlyPreviewAvailable_EvenIfOld_Pass() CompileAndTestWithFakeDateAndTypes( bicep, ResourceScope.ResourceGroup, - new string[] - { + [ "Fake.DevTestLab/schedules@2417-06-01-preview", - "Fake.DevTestLab/schedules@2417-08-01-preview", - }, + "Fake.DevTestLab/schedules@2417-08-01-preview", + ], fakeToday: "2422-07-04", - new string[] { }); + []); } [TestMethod] @@ -1448,15 +1444,14 @@ public void NewerPreviewAvailable_Fail() CompileAndTestWithFakeDateAndTypes( bicep, ResourceScope.ResourceGroup, - new string[] - { + [ "Fake.MachineLearningCompute/operationalizationClusters@2417-06-01-preview", - "Fake.MachineLearningCompute/operationalizationClusters@2417-08-01-preview", - }, + "Fake.MachineLearningCompute/operationalizationClusters@2417-08-01-preview", + ], fakeToday: "2422-07-04", - new[] { + [ "[2] Use more recent API version for 'Fake.MachineLearningCompute/operationalizationClusters'. '2417-06-01-preview' is 1859 days old, should be no more than 730 days old, or the most recent. Acceptable versions: 2417-08-01-preview", - }); + ]); } [TestMethod] @@ -1504,9 +1499,9 @@ param builtInRoleType string ResourceScope.Subscription, FakeResourceTypes.SubscriptionScopeTypes, fakeToday: "2422-07-04", - new String[] { + [ "[21] Use more recent API version for 'fake.Authorization/roleAssignments'. '2420-04-01-preview' is 824 days old, should be no more than 730 days old, or the most recent. Acceptable versions: 2420-10-01-preview, 2420-08-01-preview, 2417-09-01" - }); + ]); } [TestMethod] @@ -1524,7 +1519,7 @@ public void ExtensionResources_Lock_Pass() ResourceScope.ResourceGroup, FakeResourceTypes.ResourceScopeTypes, "2422-07-04", - new string[] { }); + []); } [TestMethod] @@ -1561,7 +1556,7 @@ param builtInRoleType string ResourceScope.Subscription, FakeResourceTypes.SubscriptionScopeTypes, "2422-07-04", - new string[] { } + [] ); } @@ -1599,9 +1594,9 @@ param builtInRoleType string ResourceScope.Subscription, FakeResourceTypes.SubscriptionScopeTypes, "2422-07-04", - new[] { + [ "[21] Use more recent API version for 'fake.Authorization/roleAssignments'. '2417-10-01-preview' is 1737 days old, should be no more than 730 days old, or the most recent. Acceptable versions: 2420-10-01-preview, 2420-08-01-preview, 2417-09-01", - } + ] ); } @@ -1654,10 +1649,10 @@ param builtInRoleType string ResourceScope.ResourceGroup, FakeResourceTypes.ResourceScopeTypes, "2422-07-04", - new[] { + [ "[24] Use more recent API version for 'fake.Storage/storageAccounts'. '2420-08-01-preview' is a preview version and there is a more recent non-preview version available. Acceptable versions: 2421-06-01, 2421-04-01, 2421-02-01, 2421-01-01", "[35] Use more recent API version for 'fake.Authorization/roleAssignments'. '2420-04-01-preview' is 824 days old, should be no more than 730 days old, or the most recent. Acceptable versions: 2420-10-01-preview, 2420-08-01-preview, 2415-07-01", - }); + ]); } [TestMethod] @@ -1680,9 +1675,9 @@ public void ExtensionResources_ScopeProperty_ExistingResource_PartiallyPass() ResourceScope.ResourceGroup, FakeResourceTypes.ResourceScopeTypes, "2422-07-04", - new[] { + [ "[6] Use more recent API version for 'fake.Authorization/locks'. '2416-09-01' is 2132 days old, should be no more than 730 days old, or the most recent. Acceptable versions: 2420-05-01", - }); + ]); } [TestMethod] @@ -1701,9 +1696,9 @@ param resourceGroupLocation string ResourceScope.Subscription, FakeResourceTypes.SubscriptionScopeTypes, "2422-07-04", - new[] { + [ "[7] Use more recent API version for 'fake.Resources/resourceGroups'. '2419-05-10' is 1151 days old, should be no more than 730 days old, or the most recent. Acceptable versions: 2421-05-01, 2421-04-01, 2421-01-01, 2420-10-01, 2420-08-01" - }); + ]); } [TestMethod] @@ -1722,7 +1717,7 @@ param resourceGroupLocation string ResourceScope.Subscription, FakeResourceTypes.SubscriptionScopeTypes, "2422-07-04", - new string[] { }); + []); } [TestMethod] @@ -1739,9 +1734,9 @@ public void ResourceTypeNotFound_Error() ResourceScope.ResourceGroup, FakeResourceTypes.ResourceScopeTypes, "2422-07-04", - new string[] { + [ "[2] Could not find resource type \"DontKnowWho.MachineLearningCompute/operationalizationClusters\".", - }); + ]); } [TestMethod] @@ -1758,9 +1753,9 @@ public void ApiVersionNotFound_Error() ResourceScope.ResourceGroup, FakeResourceTypes.ResourceScopeTypes, "2422-07-04", - new string[] { + [ "[2] Could not find apiVersion 2417-06-01-beta for Fake.MachineLearningCompute/operationalizationClusters. Acceptable versions: 2417-08-01-preview" - }); + ]); } [TestMethod] @@ -1779,13 +1774,13 @@ param resourceGroupLocation string ResourceScope.Subscription, FakeResourceTypes.SubscriptionScopeTypes, "2422-07-04", - new[] { + [ new DiagnosticAndFixes( "Use more recent API version for 'fake.Resources/resourceGroups'. '2419-05-10' is 1151 days old, should be no more than 730 days old, or the most recent. Acceptable versions: 2421-05-01, 2421-04-01, 2421-01-01, 2420-10-01, 2420-08-01", "Replace with 2421-05-01", "resource newRG 'fake.Resources/resourceGroups@2421-05-01'" ) - }); + ]); } [TestMethod] @@ -1805,13 +1800,13 @@ param resourceGroupLocation string ResourceScope.Subscription, FakeResourceTypes.SubscriptionScopeTypes, "2422-07-04", - new[] { + [ new DiagnosticAndFixes( "Use more recent API version for 'fake.Resources/resourceGroups'. '2419-05-10' is 1151 days old, should be no more than 459 days old, or the most recent. Acceptable versions: 2421-05-01, 2421-04-01", "Replace with 2421-05-01", "resource newRG 'fake.Resources/resourceGroups@2421-05-01'" ) - }, + ], maxAgeInDays: 459 ); @@ -1830,13 +1825,13 @@ param resourceGroupLocation string ResourceScope.Subscription, FakeResourceTypes.SubscriptionScopeTypes, "2422-07-04", - new[] { + [ new DiagnosticAndFixes( "Use more recent API version for 'fake.Resources/resourceGroups'. '2419-05-10' is 1151 days old, should be no more than 458 days old, or the most recent. Acceptable versions: 2421-05-01", "Replace with 2421-05-01", "resource newRG 'fake.Resources/resourceGroups@2421-05-01'" ) - }, + ], maxAgeInDays: 458 ); } @@ -1858,8 +1853,7 @@ param resourceGroupLocation string ResourceScope.Subscription, FakeResourceTypes.SubscriptionScopeTypes, "2422-07-04", - new string[] { - }, + [], maxAgeInDays: 459 ); } diff --git a/src/Bicep.Core.UnitTests/Diagnostics/LinterRuleTests/UseRecentApiVersionRule_InReferenceFunctions_Tests.cs b/src/Bicep.Core.UnitTests/Diagnostics/LinterRuleTests/UseRecentApiVersionRule_InReferenceFunctions_Tests.cs index c44f2617bdf..69d0df4c565 100644 --- a/src/Bicep.Core.UnitTests/Diagnostics/LinterRuleTests/UseRecentApiVersionRule_InReferenceFunctions_Tests.cs +++ b/src/Bicep.Core.UnitTests/Diagnostics/LinterRuleTests/UseRecentApiVersionRule_InReferenceFunctions_Tests.cs @@ -28,7 +28,7 @@ static InReferenceFunctions() // Note: The compiler does not know about these fake types, only the linter. apiVersionProvider = new ApiVersionProvider( BicepTestConstants.Features, - Enumerable.Empty()); + []); apiVersionProvider.InjectTypeReferences( ResourceScope.ResourceGroup, FakeResourceTypes.GetFakeResourceTypeReferences(FakeResourceTypes.ResourceScopeTypes)); diff --git a/src/Bicep.Core.UnitTests/Diagnostics/LinterRuleTests/UseResourceIdFunctionsRuleTests.cs b/src/Bicep.Core.UnitTests/Diagnostics/LinterRuleTests/UseResourceIdFunctionsRuleTests.cs index 77ccbfb5933..b616d398d5d 100644 --- a/src/Bicep.Core.UnitTests/Diagnostics/LinterRuleTests/UseResourceIdFunctionsRuleTests.cs +++ b/src/Bicep.Core.UnitTests/Diagnostics/LinterRuleTests/UseResourceIdFunctionsRuleTests.cs @@ -2084,10 +2084,7 @@ param subnetAddressPrefix string " ) }), - expectedMessages: new string[] - { - // pass - }); + expectedMessages: []); } [TestMethod] @@ -2117,10 +2114,7 @@ param parTopLevelManagementGroupParentId string } } ", - expectedMessages: new string[] - { - // pass - }); + expectedMessages: []); } } } diff --git a/src/Bicep.Core.UnitTests/Diagnostics/LinterRuleTests/UseResourceSymbolReferenceRuleTests.cs b/src/Bicep.Core.UnitTests/Diagnostics/LinterRuleTests/UseResourceSymbolReferenceRuleTests.cs index c0f2d6784c5..57e04704ee7 100644 --- a/src/Bicep.Core.UnitTests/Diagnostics/LinterRuleTests/UseResourceSymbolReferenceRuleTests.cs +++ b/src/Bicep.Core.UnitTests/Diagnostics/LinterRuleTests/UseResourceSymbolReferenceRuleTests.cs @@ -13,7 +13,7 @@ private void AssertCodeFix(string inputFile, string resultFile) => AssertCodeFix(UseResourceSymbolReferenceRule.Code, "Use direct resource reference", inputFile, resultFile); private void AssertNoDiagnostics(string inputFile) - => AssertLinterRuleDiagnostics(UseParentPropertyRule.Code, inputFile, new string[] { }, new Options(OnCompileErrors.Ignore, IncludePosition.None)); + => AssertLinterRuleDiagnostics(UseParentPropertyRule.Code, inputFile, [], new Options(OnCompileErrors.Ignore, IncludePosition.None)); [TestMethod] public void Codefix_handles_list_functions_with_reference_based_id_and_apiversion() => AssertCodeFix(@" diff --git a/src/Bicep.Core.UnitTests/FileSystem/PathHelperTests.cs b/src/Bicep.Core.UnitTests/FileSystem/PathHelperTests.cs index 423ddb00e39..35f9c8937cf 100644 --- a/src/Bicep.Core.UnitTests/FileSystem/PathHelperTests.cs +++ b/src/Bicep.Core.UnitTests/FileSystem/PathHelperTests.cs @@ -227,7 +227,7 @@ private static IEnumerable GetDecompileOutputPathData() #endif } - private static object[] CreateRow(string input, string expectedOutput) => new object[] { input, expectedOutput }; + private static object[] CreateRow(string input, string expectedOutput) => [input, expectedOutput]; } } diff --git a/src/Bicep.Core.UnitTests/IServiceCollectionExtensions.cs b/src/Bicep.Core.UnitTests/IServiceCollectionExtensions.cs index 22e3540aa64..b3e10cc75e4 100644 --- a/src/Bicep.Core.UnitTests/IServiceCollectionExtensions.cs +++ b/src/Bicep.Core.UnitTests/IServiceCollectionExtensions.cs @@ -120,7 +120,7 @@ public static IServiceCollection WithDeploymentHelper(this IServiceCollection se => Register(services, deploymentHelper); public static IServiceCollection WithEmptyAzResources(this IServiceCollection services) - => services.WithAzResources(Enumerable.Empty()); + => services.WithAzResources([]); public static IServiceCollection AddSingletonIfNonNull(this IServiceCollection services, TService? instance) where TService : class diff --git a/src/Bicep.Core.UnitTests/Mock/FakeResourceTypes.cs b/src/Bicep.Core.UnitTests/Mock/FakeResourceTypes.cs index fb7cc507b4e..315306bd241 100644 --- a/src/Bicep.Core.UnitTests/Mock/FakeResourceTypes.cs +++ b/src/Bicep.Core.UnitTests/Mock/FakeResourceTypes.cs @@ -6346,7 +6346,7 @@ public static Mock GetAzResourceTypeLoaderWithInjectedTypes ResourceScope.Tenant | ResourceScope.ManagementGroup | ResourceScope.Subscription | ResourceScope.ResourceGroup | ResourceScope.Resource, ResourceScope.None, ResourceFlags.None, - new ObjectType(tr.FormatName(), TypeSymbolValidationFlags.Default, Enumerable.Empty(), LanguageConstants.Any))); + new ObjectType(tr.FormatName(), TypeSymbolValidationFlags.Default, [], LanguageConstants.Any))); typesLoader.Setup(m => m.GetAvailableTypes()).Returns(fakeResourceTypeReferences); return typesLoader; diff --git a/src/Bicep.Core.UnitTests/Modules/ArtifactAddressComponentsTests.cs b/src/Bicep.Core.UnitTests/Modules/ArtifactAddressComponentsTests.cs index bd8c8ccddbc..08c11273576 100644 --- a/src/Bicep.Core.UnitTests/Modules/ArtifactAddressComponentsTests.cs +++ b/src/Bicep.Core.UnitTests/Modules/ArtifactAddressComponentsTests.cs @@ -124,7 +124,7 @@ private static ArtifactAddressComponents Parse(string package) public static IEnumerable GetValidCases() { static object[] CreateRow(string value, string expectedRegistry, string expectedRepository, string? expectedTag, string? expectedDigest) => - new object[] { new ValidCase(value, expectedRegistry, expectedRepository, expectedTag, expectedDigest) }; + [new ValidCase(value, expectedRegistry, expectedRepository, expectedTag, expectedDigest)]; yield return CreateRow("a/b:C", "a", "b", "C", null); yield return CreateRow("localhost/hello:V1", "localhost", "hello", "V1", null); diff --git a/src/Bicep.Core.UnitTests/Parsing/LexerTests.cs b/src/Bicep.Core.UnitTests/Parsing/LexerTests.cs index f29903e3cd4..6b5189d3ff2 100644 --- a/src/Bicep.Core.UnitTests/Parsing/LexerTests.cs +++ b/src/Bicep.Core.UnitTests/Parsing/LexerTests.cs @@ -30,7 +30,7 @@ public class LexerTests [DataRow(@"'\u{D801}\u{DC37}'", "\uD801\uDC37")] public void TryGetStringValue_ValidStringLiteralToken_ShouldCalculateValueCorrectly(string literalText, string expectedValue) { - var token = new FreeformToken(TokenType.StringComplete, new TextSpan(0, literalText.Length), literalText, Enumerable.Empty(), Enumerable.Empty()); + var token = new FreeformToken(TokenType.StringComplete, new TextSpan(0, literalText.Length), literalText, [], []); var actual = Lexer.TryGetStringValue(token); @@ -40,7 +40,7 @@ public void TryGetStringValue_ValidStringLiteralToken_ShouldCalculateValueCorrec [TestMethod] public void TryGetStringValue_WrongTokenType_ShouldReturnNull() { - var token = new FreeformToken(TokenType.Integer, new TextSpan(0, 2), "12", Enumerable.Empty(), Enumerable.Empty()); + var token = new FreeformToken(TokenType.Integer, new TextSpan(0, 2), "12", [], []); Lexer.TryGetStringValue(token).Should().BeNull(); } @@ -68,7 +68,7 @@ public void TryGetStringValue_WrongTokenType_ShouldReturnNull() [DataRow(@"'prefix\u{FFFFFFFFsufffix'")] public void GetStringValue_InvalidStringLiteralToken_ShouldReturnNull(string literalText) { - var token = new FreeformToken(TokenType.StringComplete, new TextSpan(0, literalText.Length), literalText, Enumerable.Empty(), Enumerable.Empty()); + var token = new FreeformToken(TokenType.StringComplete, new TextSpan(0, literalText.Length), literalText, [], []); Lexer.TryGetStringValue(token).Should().BeNull(); } diff --git a/src/Bicep.Core.UnitTests/Registry/ArtifactDispatcherTests.cs b/src/Bicep.Core.UnitTests/Registry/ArtifactDispatcherTests.cs index 403cdde44c2..86546067f06 100644 --- a/src/Bicep.Core.UnitTests/Registry/ArtifactDispatcherTests.cs +++ b/src/Bicep.Core.UnitTests/Registry/ArtifactDispatcherTests.cs @@ -244,7 +244,7 @@ private static IEnumerable GetConfigurationData() private static IModuleDispatcher CreateDispatcher(IConfigurationManager configurationManager, params IArtifactRegistry[] registries) { var provider = StrictMock.Of(); - provider.Setup(m => m.Registries(It.IsAny())).Returns(registries.ToImmutableArray()); + provider.Setup(m => m.Registries(It.IsAny())).Returns([.. registries]); return new ModuleDispatcher(provider.Object, configurationManager); } diff --git a/src/Bicep.Core.UnitTests/Registry/CachedModules.cs b/src/Bicep.Core.UnitTests/Registry/CachedModules.cs index dd7b389235a..8f66d16e5dc 100644 --- a/src/Bicep.Core.UnitTests/Registry/CachedModules.cs +++ b/src/Bicep.Core.UnitTests/Registry/CachedModules.cs @@ -22,7 +22,7 @@ public static ImmutableArray GetCachedRegistryModules(IFileSystem var cacheDir = fileSystem.DirectoryInfo.New(cacheRootDirectory); if (!cacheDir.Exists) { - return ImmutableArray.Empty; + return []; } // we create the "br" folder with same casing on all file systems @@ -42,7 +42,7 @@ public static ImmutableArray GetCachedRegistryModules(IFileSystem UnobfuscateFolderName(moduleDirectory.Parent!.Name), UnobfuscateFolderName(moduleDirectory.Name))) .ToImmutableArray() - ?? ImmutableArray.Empty; + ?? []; } private static string UnobfuscateFolderName(string folderName) diff --git a/src/Bicep.Core.UnitTests/Registry/DescriptorFactoryTests.cs b/src/Bicep.Core.UnitTests/Registry/DescriptorFactoryTests.cs index 2e7ac501abb..057c1c05616 100644 --- a/src/Bicep.Core.UnitTests/Registry/DescriptorFactoryTests.cs +++ b/src/Bicep.Core.UnitTests/Registry/DescriptorFactoryTests.cs @@ -13,7 +13,7 @@ public class OciDescriptorTests [TestMethod] public void UnknownAlgorithmShouldThrow() { - Action fail = () => OciDescriptor.ComputeDigest("fake", BinaryData.FromBytes(Array.Empty())); + Action fail = () => OciDescriptor.ComputeDigest("fake", BinaryData.FromBytes([])); fail.Should().Throw().WithMessage("Unknown hash algorithm 'fake'."); } diff --git a/src/Bicep.Core.UnitTests/Registry/TokenCredentialFactoryTests.cs b/src/Bicep.Core.UnitTests/Registry/TokenCredentialFactoryTests.cs index bb5fc13c79b..c054b0fe64f 100644 --- a/src/Bicep.Core.UnitTests/Registry/TokenCredentialFactoryTests.cs +++ b/src/Bicep.Core.UnitTests/Registry/TokenCredentialFactoryTests.cs @@ -41,7 +41,7 @@ public void ShouldCreateExpectedSingleManagedIdentityCredential(CredentialOption public void EmptyListOfCredentialTypesShouldThrow() { var f = new TokenCredentialFactory(); - FluentActions.Invoking(() => f.CreateChain(Enumerable.Empty(), null, exampleAuthorityUri)).Should().Throw(); + FluentActions.Invoking(() => f.CreateChain([], null, exampleAuthorityUri)).Should().Throw(); } [TestMethod] @@ -67,7 +67,7 @@ private static IEnumerable CreateManagedIdentityOptionsData() yield return CreateTestsCase(new ManagedIdentity(ManagedIdentityType.SystemAssigned, Guid.Empty.ToString(), null)); yield return CreateTestsCase(new ManagedIdentity(ManagedIdentityType.SystemAssigned, null, $"/subscriptions/{Guid.Empty}/providers/resourceGroups/myRG/providers/Microsoft.Storage/storageAccounts/mySA")); - static object[] CreateTestsCase(ManagedIdentity? managedIdentity) => new object[] { new CredentialOptions(managedIdentity) }; + static object[] CreateTestsCase(ManagedIdentity? managedIdentity) => [new CredentialOptions(managedIdentity)]; } private static void AssertCredentialTypes(TokenCredential credential, params Type[] expectedTypes) diff --git a/src/Bicep.Core.UnitTests/Semantics/ArmTemplateSemanticModelTests.cs b/src/Bicep.Core.UnitTests/Semantics/ArmTemplateSemanticModelTests.cs index 09ae4fa12a0..93979ef71f0 100644 --- a/src/Bicep.Core.UnitTests/Semantics/ArmTemplateSemanticModelTests.cs +++ b/src/Bicep.Core.UnitTests/Semantics/ArmTemplateSemanticModelTests.cs @@ -430,7 +430,7 @@ public void Model_creates_tagged_union_types_from_nullable_modifier() var taggedUnionType = parameterType.Should().BeOfType().Subject; taggedUnionType.DiscriminatorKey.Should().Be("type"); - taggedUnionType.UnionMembersByKey.Keys.Order().Should().Equal(new[] { "'a'", "'b'" }); + taggedUnionType.UnionMembersByKey.Keys.Order().Should().Equal(["'a'", "'b'"]); taggedUnionType.UnionMembersByKey["'a'"].Properties["value"].TypeReference.Type.Should().Be(LanguageConstants.String); taggedUnionType.UnionMembersByKey["'b'"].Properties["value"].TypeReference.Type.Should().Be(LanguageConstants.Int); } diff --git a/src/Bicep.Core.UnitTests/Semantics/ObjectDeserializationTests.cs b/src/Bicep.Core.UnitTests/Semantics/ObjectDeserializationTests.cs index e100d876025..2f46272d4ef 100644 --- a/src/Bicep.Core.UnitTests/Semantics/ObjectDeserializationTests.cs +++ b/src/Bicep.Core.UnitTests/Semantics/ObjectDeserializationTests.cs @@ -94,7 +94,7 @@ public void JSON_file_content_gets_deserialized_into_JSON() private static void CompareSimpleJSON(string json) { var arguments = new FunctionArgumentSyntax[4]; - new YamlObjectParser().TryExtractFromObject(json, null, new IPositionable[] { arguments[0] }, out var errorDiagnostic, out JToken? jToken); + new YamlObjectParser().TryExtractFromObject(json, null, [arguments[0]], out var errorDiagnostic, out JToken? jToken); var correctList = new List { 1, 2 }; var correctObject = new Dictionary { { "nestedInt", 1 }, }; @@ -132,7 +132,7 @@ public void Unparseable_YAML() - 2"; var span = new TextSpan(0, 10 - 0); - new YamlObjectParser().TryExtractFromObject(invalidYml, null, new IPositionable[] { span }, out var errorDiagnostic, out JToken? jToken); + new YamlObjectParser().TryExtractFromObject(invalidYml, null, [span], out var errorDiagnostic, out JToken? jToken); Assert.AreEqual(errorDiagnostic!.Code, "BCP340"); } @@ -155,7 +155,7 @@ public void Unparseable_JSON() - 2"; var span = new TextSpan(0, 10 - 0); - new JsonObjectParser().TryExtractFromObject(invalidJson, null, new IPositionable[] { span }, out var errorDiagnostic, out JToken? jToken); + new JsonObjectParser().TryExtractFromObject(invalidJson, null, [span], out var errorDiagnostic, out JToken? jToken); Assert.AreEqual(errorDiagnostic!.Code, "BCP186"); } @@ -164,7 +164,7 @@ public void Complex_JSON_gets_deserialized_into_JSON() { var json = COMPLEX_JSON; var arguments = new FunctionArgumentSyntax[4]; - new YamlObjectParser().TryExtractFromObject(json, null, new IPositionable[] { arguments[0] }, out var errorDiagnostic, out JToken? jToken); + new YamlObjectParser().TryExtractFromObject(json, null, [arguments[0]], out var errorDiagnostic, out JToken? jToken); var expectedValue = "```bicep\ndateTimeFromEpoch([epochTime: int]): string\n\n```\nConverts an epoch time integer value to an [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) dateTime string.\n"; Assert.AreEqual(expectedValue, jToken!["documentation"]!["value"]); } @@ -187,7 +187,7 @@ public void Simple_YAML_file_content_gets_deserialized_into_JSON() zip: 99970"; var arguments = new FunctionArgumentSyntax[4]; - new YamlObjectParser().TryExtractFromObject(yml, null, new IPositionable[] { arguments[0] }, out var errorDiagnostic, out JToken? jToken); + new YamlObjectParser().TryExtractFromObject(yml, null, [arguments[0]], out var errorDiagnostic, out JToken? jToken); Assert.AreEqual("George Washington", jToken!["name"]); Assert.AreEqual("400", jToken["addresses"]!["home"]!["street"]!["house_number"]); diff --git a/src/Bicep.Core.UnitTests/SourceCode/SourceCodeDocumentLinkHelperTests.cs b/src/Bicep.Core.UnitTests/SourceCode/SourceCodeDocumentLinkHelperTests.cs index 0a446e585c1..fc88961e82a 100644 --- a/src/Bicep.Core.UnitTests/SourceCode/SourceCodeDocumentLinkHelperTests.cs +++ b/src/Bicep.Core.UnitTests/SourceCode/SourceCodeDocumentLinkHelperTests.cs @@ -22,7 +22,7 @@ private Uri GetUri(string relativePath) public void Single() { var result = CompilationHelper.Compile( - new (string fileName, string fileContents)[] { + [ ("createVM.bicep", ""), ("main.bicep", """ // A comment @@ -35,7 +35,7 @@ public void Single() adminUsername: 'adminUsername' } } - """)}); + """)]); var links = SourceCodeDocumentLinkHelper.GetAllModuleDocumentLinks(result.Compilation.SourceFileGrouping); @@ -55,13 +55,13 @@ public void Single() public void StartingWithDotDot() { var result = CompilationHelper.Compile( - new (string fileName, string fileContents)[] { + [ ("createVM.bicep", ""), ("main.bicep", """ // A comment module creatingVM '../createVM.bicep' = { // '../createVM.bicep' = [1:18]-[1:37] } - """)}); + """)]); var links = SourceCodeDocumentLinkHelper.GetAllModuleDocumentLinks(result.Compilation.SourceFileGrouping); @@ -81,7 +81,7 @@ public void StartingWithDotDot() public void Multiple() { var result = CompilationHelper.Compile( - new (string fileName, string fileContents)[] { + [ ("createVM.bicep", """ module main '../../whatever.bicep' = { } @@ -111,7 +111,7 @@ public void Multiple() } } """), - }); + ]); var links = SourceCodeDocumentLinkHelper.GetAllModuleDocumentLinks(result.Compilation.SourceFileGrouping); @@ -139,7 +139,7 @@ public void Multiple() public void IsButsAndArrays() { var result = CompilationHelper.Compile( - new (string fileName, string fileContents)[] { + [ ("main.bicep", """ module keyVault_accessPolicies 'access-policy/main.bicep' = if (!empty(accessPolicies)) { name: '${uniqueString(deployment().name, location)}-KeyVault-AccessPolicies' @@ -182,7 +182,7 @@ public void IsButsAndArrays() } }] """), - }); + ]); var links = SourceCodeDocumentLinkHelper.GetAllModuleDocumentLinks(result.Compilation.SourceFileGrouping); diff --git a/src/Bicep.Core.UnitTests/SourceCode/SourceCodePathHelperTests.cs b/src/Bicep.Core.UnitTests/SourceCode/SourceCodePathHelperTests.cs index b9cb97a5c9e..18a16fd7e6e 100644 --- a/src/Bicep.Core.UnitTests/SourceCode/SourceCodePathHelperTests.cs +++ b/src/Bicep.Core.UnitTests/SourceCode/SourceCodePathHelperTests.cs @@ -56,18 +56,18 @@ public void ShortenTest(string input, string expected) public void GetUniquePathRoots_ShouldVerifyNormalized() { var cacheRoot = RootC("Users/username/.bicep"); - ((Action)(() => SourceCodePathHelper.MapPathsToDistinctRoots(cacheRoot, new[] { RootC("a.txt"), RootC("b.txt"), RootC("folder/c.txt") }))).Should().NotThrow(); - ((Action)(() => SourceCodePathHelper.MapPathsToDistinctRoots(cacheRoot, new[] { RootC("a.txt"), RootD("b.txt"), RootC("folder\\c.txt") }))).Should().Throw().WithMessage("*normalized*"); + ((Action)(() => SourceCodePathHelper.MapPathsToDistinctRoots(cacheRoot, [RootC("a.txt"), RootC("b.txt"), RootC("folder/c.txt")]))).Should().NotThrow(); + ((Action)(() => SourceCodePathHelper.MapPathsToDistinctRoots(cacheRoot, [RootC("a.txt"), RootD("b.txt"), RootC("folder\\c.txt")]))).Should().Throw().WithMessage("*normalized*"); } [TestMethod] public void GetUniquePathRoots_ShouldThrowIfNotFullyQualified() { var cacheRoot = RootC("Users/username/.bicep"); - ((Action)(() => SourceCodePathHelper.MapPathsToDistinctRoots(cacheRoot, new[] { RootC("a.txt"), RootC("dir/b.txt"), RootC("c.txt") }))).Should().NotThrow(); - ((Action)(() => SourceCodePathHelper.MapPathsToDistinctRoots(cacheRoot, new[] { RootC("a.txt"), RootC("dir/b.txt"), "" }))).Should().Throw().WithMessage("*qualified*"); - ((Action)(() => SourceCodePathHelper.MapPathsToDistinctRoots(cacheRoot, new[] { RootC("a.txt"), RootC("dir/b.txt"), "/" }))).Should().Throw().WithMessage("*qualified*"); - ((Action)(() => SourceCodePathHelper.MapPathsToDistinctRoots(cacheRoot, new[] { RootC("a.txt"), RootC("dir/b.txt"), "c.txt" }))).Should().Throw().WithMessage("*qualified*"); + ((Action)(() => SourceCodePathHelper.MapPathsToDistinctRoots(cacheRoot, [RootC("a.txt"), RootC("dir/b.txt"), RootC("c.txt")]))).Should().NotThrow(); + ((Action)(() => SourceCodePathHelper.MapPathsToDistinctRoots(cacheRoot, [RootC("a.txt"), RootC("dir/b.txt"), ""]))).Should().Throw().WithMessage("*qualified*"); + ((Action)(() => SourceCodePathHelper.MapPathsToDistinctRoots(cacheRoot, [RootC("a.txt"), RootC("dir/b.txt"), "/"]))).Should().Throw().WithMessage("*qualified*"); + ((Action)(() => SourceCodePathHelper.MapPathsToDistinctRoots(cacheRoot, [RootC("a.txt"), RootC("dir/b.txt"), "c.txt"]))).Should().Throw().WithMessage("*qualified*"); } [TestMethod] @@ -94,72 +94,57 @@ public static String GetGetUniquePathRootsDisplayName(MethodInfo _, object[] obj public static IEnumerable GetGetUniquePathRootsTestcases() { - object[] data(string[] paths, string[] expectedRoots) => new object[] { (paths, expectedRoots) }; + object[] data(string[] paths, string[] expectedRoots) => [(paths, expectedRoots)]; yield return data( - new string[] - { - }, - new string[] - { - }); + [], + []); yield return data( - new string[] - { + [ RootC("a.txt") - }, - new string[] - { + ], + [ RootC("") - }); + ]); yield return data( - new string[] - { + [ RootC("a.txt"), RootC("b.txt") - }, - new string[] - { + ], + [ RootC("") - }); + ]); yield return data( - new string[] - { + [ RootC("folder/a.txt") - }, - new string[] - { + ], + [ RootC("folder") - }); + ]); yield return data( - new string[] - { + [ RootC("a.txt"), RootC("folder/a.txt"), - }, - new string[] - { + ], + [ RootC("") - }); + ]); yield return data( - new string[] - { + [ RootC("folder/a.txt"), RootC("a.txt"), - }, - new string[] - { + ], + [ RootC("") - }); + ]); yield return data( - new string[] - { + [ RootC("folder/a.txt"), RootC("a.txt"), RootC("folder/b.txt"), @@ -170,17 +155,15 @@ public static IEnumerable GetGetUniquePathRootsTestcases() RootD("folder/sub1/sub2/b.txt"), RootD("folder/sub1/sub2/c.txt"), RootD("folder2/sub1/sub2/b.txt"), - }, - new string[] - { + ], + [ RootC(""), RootD("folder/sub1"), RootD("folder2/sub1/sub2"), - }); + ]); yield return data( - new string[] - { + [ RootC("folder/a.txt"), RootC("folder2/abc/def/ghi/a.txt"), RootC("folder/b.txt"), @@ -192,71 +175,62 @@ public static IEnumerable GetGetUniquePathRootsTestcases() RootD("folder/sub1/sub2/b.txt"), RootD("folder/sub1/sub2/c.txt"), RootD("folder2/sub1/sub2/b.txt"), - }, - new string[] - { + ], + [ RootC("folder"), RootC("folder2/abc"), RootD("folder/sub1"), RootD("folder2/sub1/sub2"), - }); + ]); yield return data( - new string[] - { + [ RootC("users/username/repos/deployment/src/main.bicep"), RootC("users/username/repos/deployment/src/modules/module1.bicep"), RootC("users/username/repos/deployment/src/modules/module2.bicep"), RootC("users/username/repos/deployment/shared/shared1.bicep"), RootD("bicepcacheroot/br/example.azurecr.io/test$provider$http/1.2.3$/main.json"), - }, - new string[] - { + ], + [ RootC("users/username/repos/deployment/src"), RootC("users/username/repos/deployment/shared"), RootD("bicepcacheroot/br/example.azurecr.io/test$provider$http/1.2.3$"), - }); + ]); yield return data( - new string[] - { + [ RootC("a.txt"), RootC("Users/username/.bicep/br/mcr.microsoft.com/bicep$compute$virtual-machine/1.0.1$/main.json"), - }, - new string[] - { + ], + [ RootC(""), RootC("Users/username/.bicep"), - }); + ]); yield return data( - new string[] - { + [ RootC("deployment/a.txt"), RootC("deployment/b.txt"), RootC("Users/username/.bicep/br/mcr.microsoft.com/bicep$compute$virtual-machine/1.0.1$/main.json"), RootC("Users/username/.bicep/br/mcr.microsoft.com/bicep$compute$virtual-machine/1.0.2$/main.json"), RootC("Users/username/.bicep/br/mcr.microsoft.com/bicep$compute$virtual-machine/1.0.3$/main.json"), - }, - new string[] - { + ], + [ RootC("deployment"), RootC("Users/username/.bicep"), - }); + ]); yield return data( - new string[] - { + [ RootC("deployment/a.txt"), RootC("deployment/b.txt"), RootC("Users/username/.bicep/br/mcr.microsoft.com/bicep$storage$account/1.0.1$/main.json"), RootC("Users/username/.bicep/br/mcr.microsoft.com/bicep$compute$virtual-machine/1.0.1$/main.json"), - }, - new string[] - { + ], + [ RootC("deployment"), RootC("Users/username/.bicep"), - }); + ]); #if WINDOWS_BUILD @@ -280,29 +254,25 @@ public static IEnumerable GetGetUniquePathRootsTestcases() #if !WINDOWS_BUILD yield return data( - new string[] - { + [ $"/a.txt", $"/b.txt", $"/c/b.txt", - }, - new string[] - { + ], + [ $"/" - }); + ]); yield return data( - new string[] - { + [ "/a/a.txt", "/a/b.txt", "/c/b.txt", - }, - new string[] - { + ], + [ $"/a", "/c", - }); + ]); #endif } diff --git a/src/Bicep.Core.UnitTests/Syntax/SeparatedSyntaxListTests.cs b/src/Bicep.Core.UnitTests/Syntax/SeparatedSyntaxListTests.cs index 7a5215faf9c..7ccb1e6447f 100644 --- a/src/Bicep.Core.UnitTests/Syntax/SeparatedSyntaxListTests.cs +++ b/src/Bicep.Core.UnitTests/Syntax/SeparatedSyntaxListTests.cs @@ -15,7 +15,7 @@ public class SeparatedSyntaxListTests public void EmptyListMustHaveZeroLengthSpan() { // ReSharper disable once ObjectCreationAsStatement - Action wrongSpan = () => new SeparatedSyntaxList(Enumerable.Empty(), Enumerable.Empty(), new TextSpan(53, 1)); + Action wrongSpan = () => new SeparatedSyntaxList([], Enumerable.Empty(), new TextSpan(53, 1)); wrongSpan.Should().Throw().WithMessage("The specified span was '[53:54]' but expected a zero-length span."); } @@ -28,7 +28,7 @@ public void EmptyListMustHaveZeroSeparators(int separatorCount) var separators = Enumerable.Repeat(TestSyntaxFactory.CreateToken(TokenType.Colon), separatorCount); // ReSharper disable once ObjectCreationAsStatement - Action wrongSeparators = () => new SeparatedSyntaxList(Enumerable.Empty(), separators, new TextSpan(53, 1)); + Action wrongSeparators = () => new SeparatedSyntaxList([], separators, new TextSpan(53, 1)); wrongSeparators.Should().Throw().WithMessage("With zero elements, the number of separators must also be zero."); } diff --git a/src/Bicep.Core.UnitTests/Syntax/SyntaxCollectorVisitor.cs b/src/Bicep.Core.UnitTests/Syntax/SyntaxCollectorVisitor.cs index 20afe68552b..145fed64981 100644 --- a/src/Bicep.Core.UnitTests/Syntax/SyntaxCollectorVisitor.cs +++ b/src/Bicep.Core.UnitTests/Syntax/SyntaxCollectorVisitor.cs @@ -33,7 +33,7 @@ public static ImmutableArray Build(SyntaxBase syntax) var visitor = new SyntaxCollectorVisitor(); visitor.Visit(syntax); - return visitor.syntaxList.ToImmutableArray(); + return [.. visitor.syntaxList]; } protected override void VisitInternal(SyntaxBase syntax) diff --git a/src/Bicep.Core.UnitTests/Text/SpellCheckerTests.cs b/src/Bicep.Core.UnitTests/Text/SpellCheckerTests.cs index 1000c316e68..643e9f3550f 100644 --- a/src/Bicep.Core.UnitTests/Text/SpellCheckerTests.cs +++ b/src/Bicep.Core.UnitTests/Text/SpellCheckerTests.cs @@ -10,7 +10,7 @@ namespace Bicep.Core.UnitTests.Text public class SpellCheckerTests { [DataTestMethod] - [DataRow(new string[0])] + [DataRow([])] public void GetSpellingSuggestion_NullOrEmptyCandidatesEnumerable_ReturnsNull(string[] candidates) { string? result = SpellChecker.GetSpellingSuggestion("foo", candidates); diff --git a/src/Bicep.Core.UnitTests/TypeSystem/Az/AzResourceTypeProviderTests.cs b/src/Bicep.Core.UnitTests/TypeSystem/Az/AzResourceTypeProviderTests.cs index 73a460ec903..a27da72a42d 100644 --- a/src/Bicep.Core.UnitTests/TypeSystem/Az/AzResourceTypeProviderTests.cs +++ b/src/Bicep.Core.UnitTests/TypeSystem/Az/AzResourceTypeProviderTests.cs @@ -233,8 +233,8 @@ Compilation createCompilation(string program) => Services }); } - private static ImmutableHashSet ExpectedBuiltInTypes { get; } = new[] - { + private static ImmutableHashSet ExpectedBuiltInTypes { get; } = + [ LanguageConstants.Any, LanguageConstants.Null, LanguageConstants.Bool, @@ -243,7 +243,7 @@ Compilation createCompilation(string program) => Services LanguageConstants.Object, LanguageConstants.Array, LanguageConstants.ResourceRef, - }.ToImmutableHashSet(); + ]; private static IEnumerable GetTopLevelProperties(TypeSymbol type) => type switch { @@ -255,7 +255,7 @@ Compilation createCompilation(string program) => Services .AsEnumerable() .Concat(discriminated.UnionMembersByKey.Values.SelectMany(member => GetTopLevelProperties(member))), - _ => Enumerable.Empty() + _ => [] }; private static void VisitAllReachableTypes(TypeSymbol typeSymbol, HashSet visited) diff --git a/src/Bicep.Core.UnitTests/TypeSystem/FunctionResolverTests.cs b/src/Bicep.Core.UnitTests/TypeSystem/FunctionResolverTests.cs index 081cb70ca8c..bb7c204de96 100644 --- a/src/Bicep.Core.UnitTests/TypeSystem/FunctionResolverTests.cs +++ b/src/Bicep.Core.UnitTests/TypeSystem/FunctionResolverTests.cs @@ -37,7 +37,7 @@ public void ExactOrPartialFunctionMatchShouldHaveCorrectReturnType(string displa var mockDiagnosticWriter = Repository.Create(); mockDiagnosticWriter.Setup(writer => writer.Write(It.Is(diag => diag.Code == "BCP234"))); - matches.Single().ResultBuilder(CreateDummySemanticModel(), mockDiagnosticWriter.Object, functionCall, argumentTypes.ToImmutableArray()).Type.Should().Be(expectedReturnType); + matches.Single().ResultBuilder(CreateDummySemanticModel(), mockDiagnosticWriter.Object, functionCall, [.. argumentTypes]).Type.Should().Be(expectedReturnType); } [DataTestMethod] @@ -89,7 +89,7 @@ public void IncorrectArgumentTypeShouldSetArgumentCountMismatches(string display countMismatches.Should().BeEmpty(); typeMismatches.Should().HaveCount(parameterTypeAtIndexOverloads.Count); - typeMismatches = typeMismatches.OrderBy(tm => tm.ArgumentIndex).ToList(); + typeMismatches = [.. typeMismatches.OrderBy(tm => tm.ArgumentIndex)]; for (int i = 0; i < typeMismatches.Count; i++) { @@ -107,8 +107,8 @@ public void IncorrectArgumentTypeShouldSetArgumentCountMismatches(string display public void LengthOfNonLiteralTuplesIsLiteral() { var evaluated = EvaluateFunction("length", - new List { new TupleType("nonLiteralTuple", ImmutableArray.Create(LanguageConstants.Int, LanguageConstants.String, LanguageConstants.Bool), default) }, - new FunctionArgumentSyntax[0]); + new List { new TupleType("nonLiteralTuple", [LanguageConstants.Int, LanguageConstants.String, LanguageConstants.Bool], default) }, + []); evaluated.Type.Should().Be(TypeFactory.CreateIntegerLiteralType(3)); } @@ -124,7 +124,7 @@ public void LiteralTransformationsYieldLiteralReturnType(string displayName, str [DynamicData(nameof(GetInputsThatFlattenToArrayOfAny), DynamicDataSourceType.Method)] public void ShouldFlattenToArrayOfAny(TypeSymbol typeToFlatten) { - EvaluateFunction("flatten", new List { typeToFlatten }, new[] { new FunctionArgumentSyntax(TestSyntaxFactory.CreateArray(Enumerable.Empty())) }) + EvaluateFunction("flatten", new List { typeToFlatten }, [new FunctionArgumentSyntax(TestSyntaxFactory.CreateArray(Enumerable.Empty()))]) .Type.As() .Item.Should().Be(LanguageConstants.Any); } @@ -133,14 +133,14 @@ public void ShouldFlattenToArrayOfAny(TypeSymbol typeToFlatten) [DynamicData(nameof(GetFlattenPositiveTestCases), DynamicDataSourceType.Method)] public void ShouldFlattenTo(TypeSymbol typeToFlatten, TypeSymbol expected) { - TypeValidator.AreTypesAssignable(EvaluateFunction("flatten", new List { typeToFlatten }, new[] { new FunctionArgumentSyntax(TestSyntaxFactory.CreateArray(Enumerable.Empty())) }).Type, expected).Should().BeTrue(); + TypeValidator.AreTypesAssignable(EvaluateFunction("flatten", new List { typeToFlatten }, [new FunctionArgumentSyntax(TestSyntaxFactory.CreateArray(Enumerable.Empty()))]).Type, expected).Should().BeTrue(); } [DataTestMethod] [DynamicData(nameof(GetFlattenNegativeTestCases), DynamicDataSourceType.Method)] public void ShouldNotFlatten(TypeSymbol typeToFlatten, params string[] diagnosticMessages) { - EvaluateFunction("flatten", new List { typeToFlatten }, new[] { new FunctionArgumentSyntax(TestSyntaxFactory.CreateArray(Enumerable.Empty())) }).Type.GetDiagnostics().Cast() + EvaluateFunction("flatten", new List { typeToFlatten }, [new FunctionArgumentSyntax(TestSyntaxFactory.CreateArray(Enumerable.Empty()))]).Type.GetDiagnostics().Cast() .Should().HaveDiagnostics(diagnosticMessages.Select(message => ("BCP309", DiagnosticLevel.Error, message))); } @@ -148,14 +148,14 @@ public void ShouldNotFlatten(TypeSymbol typeToFlatten, params string[] diagnosti [DynamicData(nameof(GetFirstTestCases), DynamicDataSourceType.Method)] public void FirstReturnsCorrectType(TypeSymbol inputArrayType, TypeSymbol expected) { - TypeValidator.AreTypesAssignable(EvaluateFunction("first", new List { inputArrayType }, new[] { new FunctionArgumentSyntax(TestSyntaxFactory.CreateArray(Enumerable.Empty())) }).Type, expected).Should().BeTrue(); + TypeValidator.AreTypesAssignable(EvaluateFunction("first", new List { inputArrayType }, [new FunctionArgumentSyntax(TestSyntaxFactory.CreateArray(Enumerable.Empty()))]).Type, expected).Should().BeTrue(); } [DataTestMethod] [DynamicData(nameof(GetLastTestCases), DynamicDataSourceType.Method)] public void LastReturnsCorrectType(TypeSymbol inputArrayType, TypeSymbol expected) { - TypeValidator.AreTypesAssignable(EvaluateFunction("last", new List { inputArrayType }, new[] { new FunctionArgumentSyntax(TestSyntaxFactory.CreateArray(Enumerable.Empty())) }).Type, expected).Should().BeTrue(); + TypeValidator.AreTypesAssignable(EvaluateFunction("last", new List { inputArrayType }, [new FunctionArgumentSyntax(TestSyntaxFactory.CreateArray(Enumerable.Empty()))]).Type, expected).Should().BeTrue(); } [TestMethod] @@ -163,7 +163,7 @@ public void SplitReturnsNonEmtpyArrayOfStrings() { var returnType = EvaluateFunction("split", new List { LanguageConstants.String, LanguageConstants.String }, - new FunctionArgumentSyntax[] { new(TestSyntaxFactory.CreateVariableAccess("foo")), new(TestSyntaxFactory.CreateVariableAccess("bar")) }) + [new(TestSyntaxFactory.CreateVariableAccess("foo")), new(TestSyntaxFactory.CreateVariableAccess("bar"))]) .Type; var returnedArray = returnType.Should().BeAssignableTo().Subject; @@ -177,7 +177,7 @@ public void ConcatDerivesMinLengthOfReturnType() { var returnType = EvaluateFunction("concat", new List { TypeFactory.CreateArrayType(LanguageConstants.String, minLength: 10), LanguageConstants.Array, TypeFactory.CreateArrayType(LanguageConstants.String, minLength: 11) }, - new FunctionArgumentSyntax[] { new(TestSyntaxFactory.CreateVariableAccess("foo")), new(TestSyntaxFactory.CreateVariableAccess("bar")), new(TestSyntaxFactory.CreateVariableAccess("baz")) }) + [new(TestSyntaxFactory.CreateVariableAccess("foo")), new(TestSyntaxFactory.CreateVariableAccess("bar")), new(TestSyntaxFactory.CreateVariableAccess("baz"))]) .Type; var returnedArray = returnType.Should().BeAssignableTo().Subject; @@ -190,7 +190,7 @@ public void ConcatDerivesMaxLengthOfReturnType() { var returnType = EvaluateFunction("concat", new List { TypeFactory.CreateArrayType(LanguageConstants.String, maxLength: 10), TypeFactory.CreateArrayType(LanguageConstants.String, maxLength: 11) }, - new FunctionArgumentSyntax[] { new(TestSyntaxFactory.CreateVariableAccess("foo")), new(TestSyntaxFactory.CreateVariableAccess("bar")) }) + [new(TestSyntaxFactory.CreateVariableAccess("foo")), new(TestSyntaxFactory.CreateVariableAccess("bar"))]) .Type; var returnedArray = returnType.Should().BeAssignableTo().Subject; @@ -203,7 +203,7 @@ public void ConcatDoesNotDeriveMaxLengthOfReturnTypeIfAnyInputLacksAMaxLength() { var returnType = EvaluateFunction("concat", new List { TypeFactory.CreateArrayType(LanguageConstants.String, maxLength: 10), LanguageConstants.Array, TypeFactory.CreateArrayType(LanguageConstants.String, maxLength: 11) }, - new FunctionArgumentSyntax[] { new(TestSyntaxFactory.CreateVariableAccess("foo")), new(TestSyntaxFactory.CreateVariableAccess("bar")), new(TestSyntaxFactory.CreateVariableAccess("baz")) }) + [new(TestSyntaxFactory.CreateVariableAccess("foo")), new(TestSyntaxFactory.CreateVariableAccess("bar")), new(TestSyntaxFactory.CreateVariableAccess("baz"))]) .Type; var returnedArray = returnType.Should().BeAssignableTo().Subject; @@ -216,11 +216,11 @@ public void ConcatConcatenatesTuples() var returnType = EvaluateFunction("concat", new List { - new TupleType(ImmutableArray.Create(LanguageConstants.String, LanguageConstants.Int), default), - new TupleType(ImmutableArray.Create(LanguageConstants.Bool), default), - new TupleType(ImmutableArray.Create(TypeFactory.CreateStringLiteralType("abc"), TypeFactory.CreateIntegerLiteralType(123)), default), + new TupleType([LanguageConstants.String, LanguageConstants.Int], default), + new TupleType([LanguageConstants.Bool], default), + new TupleType([TypeFactory.CreateStringLiteralType("abc"), TypeFactory.CreateIntegerLiteralType(123)], default), }, - new FunctionArgumentSyntax[] { new(TestSyntaxFactory.CreateVariableAccess("foo")), new(TestSyntaxFactory.CreateVariableAccess("bar")), new(TestSyntaxFactory.CreateVariableAccess("baz")) }) + [new(TestSyntaxFactory.CreateVariableAccess("foo")), new(TestSyntaxFactory.CreateVariableAccess("bar")), new(TestSyntaxFactory.CreateVariableAccess("baz"))]) .Type; var returnedTuple = returnType.Should().BeAssignableTo().Subject; @@ -233,7 +233,7 @@ public void SkipDerivesMinAndMaxLengthOfReturnType() { var returnType = EvaluateFunction("skip", new List { TypeFactory.CreateArrayType(LanguageConstants.String, minLength: 10, maxLength: 20), TypeFactory.CreateIntegerLiteralType(9) }, - new FunctionArgumentSyntax[] { new(TestSyntaxFactory.CreateVariableAccess("foo")), new(TestSyntaxFactory.CreateVariableAccess("bar")) }) + [new(TestSyntaxFactory.CreateVariableAccess("foo")), new(TestSyntaxFactory.CreateVariableAccess("bar"))]) .Type; var returnedArray = returnType.Should().BeAssignableTo().Subject; @@ -249,7 +249,7 @@ public void TakeDerivesMinAndMaxLengthOfReturnType() { var returnType = EvaluateFunction("take", new List { TypeFactory.CreateArrayType(LanguageConstants.String, minLength: 5, maxLength: 20), TypeFactory.CreateIntegerLiteralType(9) }, - new FunctionArgumentSyntax[] { new(TestSyntaxFactory.CreateVariableAccess("foo")), new(TestSyntaxFactory.CreateVariableAccess("bar")) }) + [new(TestSyntaxFactory.CreateVariableAccess("foo")), new(TestSyntaxFactory.CreateVariableAccess("bar"))]) .Type; var returnedArray = returnType.Should().BeAssignableTo().Subject; @@ -265,7 +265,7 @@ public void SplitReturnTypeIncludesNonZeroMinLength() { var returnType = EvaluateFunction("split", new List { LanguageConstants.Any, LanguageConstants.Any }, - new FunctionArgumentSyntax[] { new(TestSyntaxFactory.CreateVariableAccess("foo")), new(TestSyntaxFactory.CreateVariableAccess("bar")) }) + [new(TestSyntaxFactory.CreateVariableAccess("foo")), new(TestSyntaxFactory.CreateVariableAccess("bar"))]) .Type; var returnedArray = returnType.Should().BeAssignableTo().Subject; @@ -286,7 +286,7 @@ public void PadLeftReturnsCorrectType(IList argumentTypes, TypeSymbo private static IEnumerable GetPadLeftTestCases() { static object[] CreateRow(TypeSymbol expectedReturnType, params TypeSymbol[] argumentTypes) - => new object[] { argumentTypes.ToList(), expectedReturnType }; + => [argumentTypes.ToList(), expectedReturnType]; return new[] { @@ -311,7 +311,7 @@ public void ToLowerPreservesFlags() { var returnType = EvaluateFunction("toLower", new List { LanguageConstants.SecureString }, - new FunctionArgumentSyntax[] { new(TestSyntaxFactory.CreateVariableAccess("foo")) }) + [new(TestSyntaxFactory.CreateVariableAccess("foo"))]) .Type; returnType.ValidationFlags.Should().HaveFlag(TypeSymbolValidationFlags.AllowLooseAssignment); @@ -323,7 +323,7 @@ public void ToUpperPreservesFlags() { var returnType = EvaluateFunction("toUpper", new List { LanguageConstants.SecureString }, - new FunctionArgumentSyntax[] { new(TestSyntaxFactory.CreateVariableAccess("foo")) }) + [new(TestSyntaxFactory.CreateVariableAccess("foo"))]) .Type; returnType.ValidationFlags.Should().HaveFlag(TypeSymbolValidationFlags.AllowLooseAssignment); @@ -336,7 +336,7 @@ public void LengthInfersPossibleRangesFromRefinementMetadata(TypeSymbol argument { var returnType = EvaluateFunction("length", new List { argumentType }, - new FunctionArgumentSyntax[] { new(TestSyntaxFactory.CreateVariableAccess("foo")) }); + [new(TestSyntaxFactory.CreateVariableAccess("foo"))]); returnType.Type.Should().Be(expectedReturn); } @@ -344,7 +344,7 @@ public void LengthInfersPossibleRangesFromRefinementMetadata(TypeSymbol argument private static IEnumerable GetLengthTestCases() { static object[] CreateRow(TypeSymbol argumentType, TypeSymbol returnType) - => new object[] { argumentType, returnType }; + => [argumentType, returnType]; return new[] { @@ -406,7 +406,7 @@ static object[] CreateRow(TypeSymbol argumentType, TypeSymbol returnType) CreateRow(TypeFactory.CreateArrayType(1, 10, default), TypeFactory.CreateIntegerType(1, 10)), - CreateRow(new TupleType("tuple", ImmutableArray.Create(LanguageConstants.Object, LanguageConstants.String, LanguageConstants.Int), default), + CreateRow(new TupleType("tuple", [LanguageConstants.Object, LanguageConstants.String, LanguageConstants.Int], default), TypeFactory.CreateIntegerLiteralType(3)), }; } @@ -417,7 +417,7 @@ public void JoinInfersPossibleLengthRangesFromRefinementMetadata(TypeSymbol type { var returnType = EvaluateFunction("join", new List { typeToJoin, delimiterType }, - new FunctionArgumentSyntax[] { new(TestSyntaxFactory.CreateVariableAccess("foo")), new(TestSyntaxFactory.CreateVariableAccess("foo")) }); + [new(TestSyntaxFactory.CreateVariableAccess("foo")), new(TestSyntaxFactory.CreateVariableAccess("foo"))]); returnType.Type.Should().Be(expectedReturn); } @@ -425,7 +425,7 @@ public void JoinInfersPossibleLengthRangesFromRefinementMetadata(TypeSymbol type private static IEnumerable GetJoinTestCases() { static object[] CreateRow(TypeSymbol typeToJoin, TypeSymbol delimiterType, TypeSymbol returnType) - => new object[] { typeToJoin, delimiterType, returnType }; + => [typeToJoin, delimiterType, returnType]; return new[] { @@ -436,16 +436,16 @@ static object[] CreateRow(TypeSymbol typeToJoin, TypeSymbol delimiterType, TypeS CreateRow(new TypedArrayType(TypeFactory.CreateStringType(1, 10), default, 1, 10), LanguageConstants.String, TypeFactory.CreateStringType(1)), - CreateRow(new TupleType("tuple", ImmutableArray.Create(LanguageConstants.Object, LanguageConstants.String, LanguageConstants.Int), default), + CreateRow(new TupleType("tuple", [LanguageConstants.Object, LanguageConstants.String, LanguageConstants.Int], default), TypeFactory.CreateStringLiteralType(", "), TypeFactory.CreateStringType(7)), - CreateRow(new TupleType("tuple", ImmutableArray.Create(TypeFactory.CreateIntegerType(0, 9)), default), + CreateRow(new TupleType("tuple", [TypeFactory.CreateIntegerType(0, 9)], default), TypeFactory.CreateStringLiteralType(", "), TypeFactory.CreateStringType(1, 1)), - CreateRow(new TupleType("tuple", ImmutableArray.Create(TypeFactory.CreateIntegerType(0, 9), TypeFactory.CreateIntegerType(0, 9)), default), + CreateRow(new TupleType("tuple", [TypeFactory.CreateIntegerType(0, 9), TypeFactory.CreateIntegerType(0, 9)], default), TypeFactory.CreateStringLiteralType(", "), TypeFactory.CreateStringType(4, 4)), - CreateRow(new TupleType("tuple", ImmutableArray.Create(TypeFactory.CreateIntegerType(0, 9), TypeFactory.CreateIntegerType(0, 9)), default), + CreateRow(new TupleType("tuple", [TypeFactory.CreateIntegerType(0, 9), TypeFactory.CreateIntegerType(0, 9)], default), TypeFactory.CreateStringType(), TypeFactory.CreateStringType(2)), }; @@ -464,7 +464,7 @@ public void SubstringInfersPossibleLengthRangesFromRefinementMetadata(IList GetSubstringTestCases() { static object[] CreateRow(TypeSymbol expectedReturnType, params TypeSymbol[] argumentTypes) - => new object[] { argumentTypes.ToList(), expectedReturnType }; + => [argumentTypes.ToList(), expectedReturnType]; return new[] { @@ -494,7 +494,7 @@ public void SkipInfersPossibleLengthRangesFromRefinementMetadata(TypeSymbol orig { var returnType = EvaluateFunction("skip", new List { originalValue, numberToSkip }, - new FunctionArgumentSyntax[] { new(TestSyntaxFactory.CreateVariableAccess("foo")), new(TestSyntaxFactory.CreateVariableAccess("bar")) }); + [new(TestSyntaxFactory.CreateVariableAccess("foo")), new(TestSyntaxFactory.CreateVariableAccess("bar"))]); returnType.Type.Should().Be(expectedReturn); } @@ -502,7 +502,7 @@ public void SkipInfersPossibleLengthRangesFromRefinementMetadata(TypeSymbol orig private static IEnumerable GetSkipTestCases() { static object[] CreateRow(TypeSymbol originalValue, TypeSymbol numberToSkip, TypeSymbol expectedReturn) - => new object[] { originalValue, numberToSkip, expectedReturn }; + => [originalValue, numberToSkip, expectedReturn]; return new[] { @@ -537,7 +537,7 @@ public void TakeInfersPossibleLengthRangesFromRefinementMetadata(TypeSymbol orig { var returnType = EvaluateFunction("take", new List { originalValue, numberToTake }, - new FunctionArgumentSyntax[] { new(TestSyntaxFactory.CreateVariableAccess("foo")), new(TestSyntaxFactory.CreateVariableAccess("bar")) }); + [new(TestSyntaxFactory.CreateVariableAccess("foo")), new(TestSyntaxFactory.CreateVariableAccess("bar"))]); returnType.Type.Should().Be(expectedReturn); } @@ -545,7 +545,7 @@ public void TakeInfersPossibleLengthRangesFromRefinementMetadata(TypeSymbol orig private static IEnumerable GetTakeTestCases() { static object[] CreateRow(TypeSymbol originalValue, TypeSymbol numberToTake, TypeSymbol expectedReturn) - => new object[] { originalValue, numberToTake, expectedReturn }; + => [originalValue, numberToTake, expectedReturn]; return new[] { @@ -581,7 +581,7 @@ public void TrimDropsMinLengthButPreservesMaxLengthAndFlags() { var returnType = EvaluateFunction("trim", new List { TypeFactory.CreateStringType(10, 20, TypeSymbolValidationFlags.IsSecure) }, - new FunctionArgumentSyntax[] { new(TestSyntaxFactory.CreateVariableAccess("foo")) }) + [new(TestSyntaxFactory.CreateVariableAccess("foo"))]) .Type; returnType.Should().Be(TypeFactory.CreateStringType(minLength: null, 20, TypeSymbolValidationFlags.IsSecure)); @@ -593,7 +593,7 @@ public void RangeInfersYieldRefinementsFromInputMetadata(TypeSymbol startIndex, { var returnType = EvaluateFunction("range", new List { startIndex, count }, - new FunctionArgumentSyntax[] { new(TestSyntaxFactory.CreateVariableAccess("foo")), new(TestSyntaxFactory.CreateVariableAccess("bar")) }); + [new(TestSyntaxFactory.CreateVariableAccess("foo")), new(TestSyntaxFactory.CreateVariableAccess("bar"))]); returnType.Type.Should().Be(expectedReturn); } @@ -601,7 +601,7 @@ public void RangeInfersYieldRefinementsFromInputMetadata(TypeSymbol startIndex, private static IEnumerable GetRangeTestCases() { static object[] CreateRow(TypeSymbol startIndex, TypeSymbol count, TypeSymbol expectedReturn) - => new object[] { startIndex, count, expectedReturn }; + => [startIndex, count, expectedReturn]; return new[] { @@ -639,18 +639,18 @@ private FunctionResult EvaluateFunction(string functionName, IList a CreateDummySemanticModel(), Repository.Create().Object, SyntaxFactory.CreateFunctionCall(functionName, arguments), - argumentTypes.ToImmutableArray()); + [.. argumentTypes]); } private static IEnumerable GetInputsThatFlattenToArrayOfAny() => new[] { new object[] { LanguageConstants.Any }, - new object[] { LanguageConstants.Array }, - new object[] { TypeHelper.CreateTypeUnion(new TypedArrayType(new TypedArrayType(LanguageConstants.String, default), default), LanguageConstants.Any) }, - new object[] { TypeHelper.CreateTypeUnion(new TypedArrayType(new TypedArrayType(LanguageConstants.String, default), default), LanguageConstants.Array) }, - new object[] { TypeHelper.CreateTypeUnion(new TypedArrayType(new TypedArrayType(LanguageConstants.String, default), default), new TypedArrayType(LanguageConstants.Array, default)) }, - new object[] { new TypedArrayType(TypeHelper.CreateTypeUnion(new TypedArrayType(LanguageConstants.String, default), LanguageConstants.Any), default) }, - new object[] { new TypedArrayType(TypeHelper.CreateTypeUnion(new TypedArrayType(LanguageConstants.String, default), LanguageConstants.Array), default) }, + [LanguageConstants.Array], + [TypeHelper.CreateTypeUnion(new TypedArrayType(new TypedArrayType(LanguageConstants.String, default), default), LanguageConstants.Any)], + [TypeHelper.CreateTypeUnion(new TypedArrayType(new TypedArrayType(LanguageConstants.String, default), default), LanguageConstants.Array)], + [TypeHelper.CreateTypeUnion(new TypedArrayType(new TypedArrayType(LanguageConstants.String, default), default), new TypedArrayType(LanguageConstants.Array, default))], + [new TypedArrayType(TypeHelper.CreateTypeUnion(new TypedArrayType(LanguageConstants.String, default), LanguageConstants.Any), default)], + [new TypedArrayType(TypeHelper.CreateTypeUnion(new TypedArrayType(LanguageConstants.String, default), LanguageConstants.Array), default)], }; private static IEnumerable GetFlattenPositiveTestCases() => new[] @@ -658,37 +658,41 @@ private static IEnumerable GetFlattenPositiveTestCases() => new[] // flatten(string[][]) -> string[] new object[] { new TypedArrayType(new TypedArrayType(LanguageConstants.String, default), default), new TypedArrayType(LanguageConstants.String, default) }, // flatten((string[] | int[])[]) -> (string | int)[] - new object[] - { + [ new TypedArrayType(TypeHelper.CreateTypeUnion(new TypedArrayType(LanguageConstants.String, default), new TypedArrayType(LanguageConstants.Int, default)), default), new TypedArrayType(TypeHelper.CreateTypeUnion(LanguageConstants.String, LanguageConstants.Int), default), - }, + ], // flatten(string[][] | int[][]) -> (string | int)[] - new object[] - { + [ TypeHelper.CreateTypeUnion(new TypedArrayType(new TypedArrayType(LanguageConstants.String, default), default), new TypedArrayType(new TypedArrayType(LanguageConstants.Int, default), default)), new TypedArrayType(TypeHelper.CreateTypeUnion(LanguageConstants.String, LanguageConstants.Int), default), - }, + ], // flatten([[1, 2], [3, 4]]) -> [1, 2, 3, 4] - new object[] - { + [ new TupleType("[[1, 2], [3, 4]]", - ImmutableArray.Create( - new TupleType("[1, 2]", ImmutableArray.Create(TypeFactory.CreateIntegerLiteralType(1), TypeFactory.CreateIntegerLiteralType(2)), default), - new TupleType("[3, 4]", ImmutableArray.Create(TypeFactory.CreateIntegerLiteralType(3), TypeFactory.CreateIntegerLiteralType(4)), default)), + [ + new TupleType("[1, 2]", [TypeFactory.CreateIntegerLiteralType(1), TypeFactory.CreateIntegerLiteralType(2)], default), + new TupleType("[3, 4]", [TypeFactory.CreateIntegerLiteralType(3), TypeFactory.CreateIntegerLiteralType(4)], default), + ], default), - new TupleType("[1, 2, 3, 4]", ImmutableArray.Create(TypeFactory.CreateIntegerLiteralType(1), TypeFactory.CreateIntegerLiteralType(2), TypeFactory.CreateIntegerLiteralType(3), TypeFactory.CreateIntegerLiteralType(4)), default), - }, + new TupleType("[1, 2, 3, 4]", + [ + TypeFactory.CreateIntegerLiteralType(1), + TypeFactory.CreateIntegerLiteralType(2), + TypeFactory.CreateIntegerLiteralType(3), + TypeFactory.CreateIntegerLiteralType(4), + ], default), + ], // flatten([[1, 2], (3 | 4)[]]) -> (1 | 2 | 3 | 4)[] - new object[] - { + [ new TupleType("[[1, 2], (3, 4)[]]", - ImmutableArray.Create( - new TupleType("[1, 2]", ImmutableArray.Create(TypeFactory.CreateIntegerLiteralType(1), TypeFactory.CreateIntegerLiteralType(2)), default), - new TypedArrayType(TypeHelper.CreateTypeUnion(TypeFactory.CreateIntegerLiteralType(3), TypeFactory.CreateIntegerLiteralType(4)), default)), + [ + new TupleType("[1, 2]", [TypeFactory.CreateIntegerLiteralType(1), TypeFactory.CreateIntegerLiteralType(2)], default), + new TypedArrayType(TypeHelper.CreateTypeUnion(TypeFactory.CreateIntegerLiteralType(3), TypeFactory.CreateIntegerLiteralType(4)), default), + ], default), new TypedArrayType(TypeHelper.CreateTypeUnion(TypeFactory.CreateIntegerLiteralType(1), TypeFactory.CreateIntegerLiteralType(2), TypeFactory.CreateIntegerLiteralType(3), TypeFactory.CreateIntegerLiteralType(4)), default), - }, + ], }; private static IEnumerable GetFlattenNegativeTestCases() => new[] @@ -696,18 +700,18 @@ private static IEnumerable GetFlattenNegativeTestCases() => new[] // flatten(string[]) -> new object[] { new TypedArrayType(LanguageConstants.String, default), @"Values of type ""string[]"" cannot be flattened because ""string"" is not an array type." }, // flatten((string[] | string)[]) -> - new object[] { new TypedArrayType(TypeHelper.CreateTypeUnion(new TypedArrayType(LanguageConstants.String, default), LanguageConstants.String), default), @"Values of type ""(string | string[])[]"" cannot be flattened because ""string"" is not an array type." }, + [new TypedArrayType(TypeHelper.CreateTypeUnion(new TypedArrayType(LanguageConstants.String, default), LanguageConstants.String), default), @"Values of type ""(string | string[])[]"" cannot be flattened because ""string"" is not an array type."], // flatten((string[] | string | int)[]) -> - new object[] { + [ new TypedArrayType(TypeHelper.CreateTypeUnion(new TypedArrayType(LanguageConstants.String, default), LanguageConstants.String, LanguageConstants.Int), default), @"Values of type ""(int | string | string[])[]"" cannot be flattened because ""int"" is not an array type.", @"Values of type ""(int | string | string[])[]"" cannot be flattened because ""string"" is not an array type.", - }, + ], // flatten(string[][] | bool[]) -> - new object[] { + [ TypeHelper.CreateTypeUnion(new TypedArrayType(new TypedArrayType(LanguageConstants.String, default), default), new TypedArrayType(LanguageConstants.Bool, default)), @"Values of type ""bool[] | string[][]"" cannot be flattened because ""bool"" is not an array type.", - }, + ], }; private static IEnumerable GetFirstTestCases() => new[] @@ -719,45 +723,39 @@ private static IEnumerable GetFirstTestCases() => new[] TypeHelper.CreateTypeUnion(LanguageConstants.Null, LanguageConstants.CreateResourceScopeReference(ResourceScope.ResourceGroup)) }, // first(string[] {@minLength(1)}) -> string - new object[] - { + [ new TypedArrayType(LanguageConstants.String, default, minLength: 1), LanguageConstants.String, - }, + ], // first(['test', 3]) -> 'test' - new object[] - { + [ new TupleType("['test', 3]", - ImmutableArray.Create( - TypeFactory.CreateStringLiteralType("test"), - TypeFactory.CreateIntegerLiteralType(3) - ), + [TypeFactory.CreateStringLiteralType("test"), TypeFactory.CreateIntegerLiteralType(3) +], default), TypeFactory.CreateStringLiteralType("test") - }, + ], // first([resourceGroup, subscription]) => resourceGroup - new object[] - { + [ new TupleType("[resourceGroup, subscription]", - ImmutableArray.Create( + [ LanguageConstants.CreateResourceScopeReference(ResourceScope.ResourceGroup), LanguageConstants.CreateResourceScopeReference(ResourceScope.Subscription) - ), +, + ], default), LanguageConstants.CreateResourceScopeReference(ResourceScope.ResourceGroup) - }, + ], // first(string) => string {@minLength(0), @maxLength(1)} - new object[] - { + [ LanguageConstants.String, TypeFactory.CreateStringType(0, 1), - }, + ], // first(string {@minLength(> 0)}) => string {@minLength(1), @maxLength(1)} - new object[] - { + [ TypeFactory.CreateStringType(1), TypeFactory.CreateStringType(1, 1), - }, + ], }; private static IEnumerable GetLastTestCases() => new[] @@ -769,45 +767,39 @@ private static IEnumerable GetLastTestCases() => new[] TypeHelper.CreateTypeUnion(LanguageConstants.Null, LanguageConstants.CreateResourceScopeReference(ResourceScope.ResourceGroup)) }, // last(string[] {@minLength(1)}) -> string - new object[] - { + [ new TypedArrayType(LanguageConstants.String, default, minLength: 1), LanguageConstants.String, - }, + ], // last(['test', 3]) -> 3 - new object[] - { + [ new TupleType("['test', 3]", - ImmutableArray.Create( - TypeFactory.CreateStringLiteralType("test"), - TypeFactory.CreateIntegerLiteralType(3) - ), + [TypeFactory.CreateStringLiteralType("test"), TypeFactory.CreateIntegerLiteralType(3) +], default), TypeFactory.CreateIntegerLiteralType(3) - }, + ], // last([resourceGroup, subscription]) => subscription - new object[] - { + [ new TupleType("[resourceGroup, subscription]", - ImmutableArray.Create( + [ LanguageConstants.CreateResourceScopeReference(ResourceScope.ResourceGroup), LanguageConstants.CreateResourceScopeReference(ResourceScope.Subscription) - ), +, + ], default), LanguageConstants.CreateResourceScopeReference(ResourceScope.Subscription) - }, + ], // last(string) => string {@minLength(0), @maxLength(1)} - new object[] - { + [ LanguageConstants.String, TypeFactory.CreateStringType(0, 1), - }, + ], // last(string {@minLength(> 0)}) => string {@minLength(1), @maxLength(1)} - new object[] - { + [ TypeFactory.CreateStringType(1), TypeFactory.CreateStringType(1, 1), - }, + ], }; private static IEnumerable GetLiteralTransformations() @@ -843,7 +835,7 @@ object[] CreateRow(object? returnedLiteral, string functionName, params object[] var argumentTypeLiterals = argumentLiterals.Select(ToTypeLiteral).ToList(); string displayName = $@"{functionName}({string.Join(", ", argumentLiterals.Select(l => $@"""{l}"""))}): ""{returnedLiteral}"""; - return new object[] { displayName, functionName, argumentTypeLiterals, argumentLiteralSyntaxes, ToTypeLiteral(returnedLiteral) }; + return [displayName, functionName, argumentTypeLiterals, argumentLiteralSyntaxes, ToTypeLiteral(returnedLiteral)]; } return new[] @@ -909,7 +901,7 @@ private static IEnumerable GetExactMatchData() object[] CreateRow(string functionName, TypeSymbol expectedReturnType, params TypeSymbol[] argumentTypes) { string displayName = $"{functionName}({argumentTypes.Select(a => a.ToString()).ConcatString(", ")}): {expectedReturnType}"; - return new object[] { displayName, functionName, expectedReturnType, argumentTypes }; + return [displayName, functionName, expectedReturnType, argumentTypes]; } // various concat overloads @@ -943,7 +935,7 @@ private static IEnumerable GetAmbiguousMatchData() object[] CreateRow(string functionName, int argumentCount, params TypeSymbol[] expectedReturnTypes) { string displayName = $"{functionName}({Enumerable.Repeat(LanguageConstants.Any, argumentCount).Select(a => a.ToString()).ConcatString(", ")}): {TypeHelper.CreateTypeUnion(expectedReturnTypes)}"; - return new object[] { displayName, functionName, argumentCount, expectedReturnTypes }; + return [displayName, functionName, argumentCount, expectedReturnTypes]; } yield return CreateRow("concat", 2, LanguageConstants.String, LanguageConstants.Array); @@ -958,7 +950,7 @@ private static IEnumerable GetArgumentCountMismatchData() object[] CreateRow(string functionName, Tuple argumentCountRange, params TypeSymbol[] argumentTypes) { string displayName = $"{functionName}({argumentTypes.Select(a => a.ToString()).ConcatString(", ")})"; - return new object[] { displayName, functionName, argumentCountRange, argumentTypes }; + return [displayName, functionName, argumentCountRange, argumentTypes]; } yield return CreateRow("concat", Tuple.Create(1, (int?)null)); @@ -973,7 +965,7 @@ private static IEnumerable GetArgumentTypeMismatchData() object[] CreateRow(string functionName, List> parameterTypeAtIndexOverloads, params TypeSymbol[] argumentTypes) { string displayName = $"{functionName}({argumentTypes.Select(a => a.ToString()).ConcatString(", ")})"; - return new object[] { displayName, functionName, parameterTypeAtIndexOverloads, argumentTypes }; + return [displayName, functionName, parameterTypeAtIndexOverloads, argumentTypes]; } yield return CreateRow( @@ -1003,7 +995,7 @@ private static IEnumerable GetMismatchData() object[] CreateRow(string functionName, params TypeSymbol[] argumentTypes) { string displayName = $"{functionName}({argumentTypes.Select(a => a.ToString()).ConcatString(", ")})"; - return new object[] { displayName, functionName, argumentTypes }; + return [displayName, functionName, argumentTypes]; } // wrong types diff --git a/src/Bicep.Core.UnitTests/TypeSystem/OperatorTests.cs b/src/Bicep.Core.UnitTests/TypeSystem/OperatorTests.cs index 1a0c445679b..4a52b7122b4 100644 --- a/src/Bicep.Core.UnitTests/TypeSystem/OperatorTests.cs +++ b/src/Bicep.Core.UnitTests/TypeSystem/OperatorTests.cs @@ -82,7 +82,7 @@ public void Unary_operator_resolves_correct_type(UnaryOperationSyntax expression private static IEnumerable GetUnaryTestCases() { static object[] Case(UnaryOperationSyntax expression, TypeSymbol operandType, TypeSymbol expected, params DiagnosticMatcherData[] matcherData) - => new object[] { expression, operandType, expected, matcherData }; + => [expression, operandType, expected, matcherData]; var symbolRef = TestSyntaxFactory.CreateVariableAccess("foo"); @@ -145,7 +145,7 @@ public void Binary_operator_resolves_correct_type(BinaryOperator @operator, Type private static IEnumerable GetBinaryTestCases() { static object[] Case(BinaryOperator @operator, TypeSymbol leftOperandType, TypeSymbol rightOperandType, TypeSymbol expected, params DiagnosticMatcherData[] matcherData) - => new object[] { @operator, leftOperandType, rightOperandType, expected, matcherData }; + => [@operator, leftOperandType, rightOperandType, expected, matcherData]; return new[] { diff --git a/src/Bicep.Core.UnitTests/TypeSystem/ResourceDerivedTypeResolverTests.cs b/src/Bicep.Core.UnitTests/TypeSystem/ResourceDerivedTypeResolverTests.cs index e9b8ea5f09d..cd93bcf8d36 100644 --- a/src/Bicep.Core.UnitTests/TypeSystem/ResourceDerivedTypeResolverTests.cs +++ b/src/Bicep.Core.UnitTests/TypeSystem/ResourceDerivedTypeResolverTests.cs @@ -34,7 +34,7 @@ public void Returns_input_if_no_unbound_types_are_enclosed(TypeSymbol type) private static IEnumerable GetTypesNotInNeedOfBinding() { - static object[] Row(TypeSymbol type) => new object[] { type }; + static object[] Row(TypeSymbol type) => [type]; yield return Row(LanguageConstants.Any); yield return Row(LanguageConstants.Null); @@ -62,7 +62,7 @@ public void Hydrates_array_item_types() var hydrated = TypeFactory.CreateBooleanLiteralType(false); var (sut, unhydratedTypeRef) = SetupResolver(hydrated); - var containsUnresolved = TypeFactory.CreateArrayType(new UnresolvedResourceDerivedType(unhydratedTypeRef, ImmutableArray.Empty, LanguageConstants.Any)); + var containsUnresolved = TypeFactory.CreateArrayType(new UnresolvedResourceDerivedType(unhydratedTypeRef, [], LanguageConstants.Any)); sut.ResolveResourceDerivedTypes(containsUnresolved).Should().BeOfType() .Subject.Item.Should().BeSameAs(hydrated); } @@ -73,7 +73,7 @@ public void Hydrates_tuple_item_types() var hydrated = TypeFactory.CreateBooleanLiteralType(false); var (sut, unhydratedTypeRef) = SetupResolver(hydrated); - var containsUnresolved = new TupleType(ImmutableArray.Create(new UnresolvedResourceDerivedType(unhydratedTypeRef, ImmutableArray.Empty, LanguageConstants.Any)), + var containsUnresolved = new TupleType([new UnresolvedResourceDerivedType(unhydratedTypeRef, [], LanguageConstants.Any)], TypeSymbolValidationFlags.Default); sut.ResolveResourceDerivedTypes(containsUnresolved).Should().BeOfType() .Subject.Items.First().Should().BeSameAs(hydrated); @@ -93,7 +93,7 @@ public void Hydrates_discriminated_object_variant_types() "property", new ITypeReference[] { - new UnresolvedResourceDerivedPartialObjectType(unhydratedTypeRef, ImmutableArray.Empty, "property", "foo"), + new UnresolvedResourceDerivedPartialObjectType(unhydratedTypeRef, [], "property", "foo"), new ObjectType("bar", TypeSymbolValidationFlags.Default, new TypeProperty("property", TypeFactory.CreateStringLiteralType("bar")).AsEnumerable(), @@ -112,7 +112,7 @@ public void Hydrates_object_property_types() var containsUnresolved = new ObjectType("object", TypeSymbolValidationFlags.Default, - new TypeProperty("property", new UnresolvedResourceDerivedType(unhydratedTypeRef, ImmutableArray.Empty, LanguageConstants.Any)).AsEnumerable(), + new TypeProperty("property", new UnresolvedResourceDerivedType(unhydratedTypeRef, [], LanguageConstants.Any)).AsEnumerable(), null); sut.ResolveResourceDerivedTypes(containsUnresolved).Should().BeOfType() @@ -128,7 +128,7 @@ public void Hydrates_object_additinalProperties_types() var containsUnresolved = new ObjectType("object", TypeSymbolValidationFlags.Default, ImmutableArray.Empty, - new UnresolvedResourceDerivedType(unhydratedTypeRef, ImmutableArray.Empty, LanguageConstants.Any)); + new UnresolvedResourceDerivedType(unhydratedTypeRef, [], LanguageConstants.Any)); var hydratedContainer = sut.ResolveResourceDerivedTypes(containsUnresolved).Should().BeOfType().Subject; hydratedContainer.AdditionalPropertiesType.Should().NotBeNull(); @@ -142,7 +142,7 @@ public void Hydrates_union_member_types() var (sut, unhydratedTypeRef) = SetupResolver(hydrated); var containsUnresolved = TypeHelper.CreateTypeUnion(LanguageConstants.String, - new UnresolvedResourceDerivedType(unhydratedTypeRef, ImmutableArray.Empty, LanguageConstants.Any)); + new UnresolvedResourceDerivedType(unhydratedTypeRef, [], LanguageConstants.Any)); sut.ResolveResourceDerivedTypes(containsUnresolved).Should().BeOfType() .Subject.Members.Should().Contain(hydrated); @@ -154,7 +154,7 @@ public void Hydrates_wrapped_types() var hydrated = TypeFactory.CreateBooleanLiteralType(false); var (sut, unhydratedTypeRef) = SetupResolver(hydrated); - var containsUnresolved = new TypeType(new UnresolvedResourceDerivedType(unhydratedTypeRef, ImmutableArray.Empty, LanguageConstants.Any)); + var containsUnresolved = new TypeType(new UnresolvedResourceDerivedType(unhydratedTypeRef, [], LanguageConstants.Any)); sut.ResolveResourceDerivedTypes(containsUnresolved).Should().BeOfType() .Subject.Unwrapped.Should().BeSameAs(hydrated); @@ -168,11 +168,11 @@ public void Hydrates_lambda_types() var containsUnresolved = new LambdaType( [ - TypeFactory.CreateArrayType(new UnresolvedResourceDerivedType(unhydratedTypeRef, ImmutableArray.Empty, LanguageConstants.Any)), - new UnresolvedResourceDerivedType(unhydratedTypeRef, ImmutableArray.Empty, LanguageConstants.Any), + TypeFactory.CreateArrayType(new UnresolvedResourceDerivedType(unhydratedTypeRef, [], LanguageConstants.Any)), + new UnresolvedResourceDerivedType(unhydratedTypeRef, [], LanguageConstants.Any), ], [], - new UnresolvedResourceDerivedType(unhydratedTypeRef, ImmutableArray.Empty, LanguageConstants.Any)); + new UnresolvedResourceDerivedType(unhydratedTypeRef, [], LanguageConstants.Any)); var bound = sut.ResolveResourceDerivedTypes(containsUnresolved).Should().BeOfType().Subject; bound.ArgumentTypes.Should().SatisfyRespectively( @@ -199,7 +199,7 @@ private static (ResourceDerivedTypeResolver sut, ResourceTypeReference unhydrate ResourceScope.None, ResourceFlags.None, hydratedType, - ImmutableHashSet.Empty)); + [])); var resolver = NamespaceResolver.Create([ new("az", stubbedNamespaceType, null), @@ -238,7 +238,7 @@ public void Emits_diagnostic_and_uses_fallback_type_when_resource_not_found() ResourceDerivedTypeResolver sut = new(binderMock.Object); var fallbackType = LanguageConstants.SecureString; - sut.ResolveResourceDerivedTypes(new UnresolvedResourceDerivedType(unhydratedTypeRef, ImmutableArray.Empty, fallbackType)).Should().BeSameAs(fallbackType); + sut.ResolveResourceDerivedTypes(new UnresolvedResourceDerivedType(unhydratedTypeRef, [], fallbackType)).Should().BeSameAs(fallbackType); resourceTypeProviderMock.Verify(x => x.TryGetDefinedType(stubbedNamespaceType, unhydratedTypeRef, ResourceTypeGenerationFlags.None), Times.Once()); resourceTypeProviderMock.Verify(x => x.TryGenerateFallbackType(stubbedNamespaceType, unhydratedTypeRef, ResourceTypeGenerationFlags.None), Times.Once()); @@ -252,31 +252,33 @@ public void Supports_pointers_to_partial_resource_body_types() TypeSymbolValidationFlags.Default, ImmutableArray.Create(new TypeProperty("property", new TupleType( - ImmutableArray.Create(new ObjectType("dictionary", - TypeSymbolValidationFlags.Default, - ImmutableArray.Empty, - TypeFactory.CreateArrayType(new DiscriminatedObjectType("taggedUnion", - TypeSymbolValidationFlags.Default, - "type", - ImmutableArray.Create( - new ObjectType("fooVariant", - TypeSymbolValidationFlags.Default, - ImmutableArray.Create( - new TypeProperty("type", TypeFactory.CreateStringLiteralType("foo")), - new TypeProperty("property", LanguageConstants.Int)), - null), - new ObjectType("barVariant", - TypeSymbolValidationFlags.Default, - ImmutableArray.Create( - new TypeProperty("type", TypeFactory.CreateStringLiteralType("bar")), - new TypeProperty("property", targetType)), - null)))))), + [ + new ObjectType("dictionary", + TypeSymbolValidationFlags.Default, + ImmutableArray.Empty, + TypeFactory.CreateArrayType(new DiscriminatedObjectType("taggedUnion", + TypeSymbolValidationFlags.Default, + "type", + ImmutableArray.Create( + new ObjectType("fooVariant", + TypeSymbolValidationFlags.Default, + ImmutableArray.Create( + new TypeProperty("type", TypeFactory.CreateStringLiteralType("foo")), + new TypeProperty("property", LanguageConstants.Int)), + null), + new ObjectType("barVariant", + TypeSymbolValidationFlags.Default, + ImmutableArray.Create( + new TypeProperty("type", TypeFactory.CreateStringLiteralType("bar")), + new TypeProperty("property", targetType)), + null))))), + ], TypeSymbolValidationFlags.Default))), null); var (sut, unhydratedTypeRef) = SetupResolver(hydrated); UnresolvedResourceDerivedType unresolved = new(unhydratedTypeRef, - ImmutableArray.Create("properties", "property", "prefixItems", "0", "additionalProperties", "items", "discriminator", "mapping", "bar", "properties", "property"), + ["properties", "property", "prefixItems", "0", "additionalProperties", "items", "discriminator", "mapping", "bar", "properties", "property"], LanguageConstants.Any); var bound = sut.ResolveResourceDerivedTypes(unresolved); diff --git a/src/Bicep.Core.UnitTests/TypeSystem/TypeHelperTests.cs b/src/Bicep.Core.UnitTests/TypeSystem/TypeHelperTests.cs index 1a048c5f8eb..46a87426f4a 100644 --- a/src/Bicep.Core.UnitTests/TypeSystem/TypeHelperTests.cs +++ b/src/Bicep.Core.UnitTests/TypeSystem/TypeHelperTests.cs @@ -110,22 +110,22 @@ static object[] Row(TypeSymbol expected, params TypeSymbol[] toCollapse) TypeFactory.CreateArrayType(LanguageConstants.String, minLength: 4, maxLength: 6), TypeFactory.CreateArrayType(LanguageConstants.Int, minLength: 5, maxLength: 99)), // collapse(array{6,7}, [string, int], array{8,9}) -> union(array{6,9}, [string, int]) - Row(TypeHelper.CreateTypeUnion(TypeFactory.CreateArrayType(minLength: 6, maxLength: 9), new TupleType(ImmutableArray.Create(LanguageConstants.String, LanguageConstants.Int), default)), + Row(TypeHelper.CreateTypeUnion(TypeFactory.CreateArrayType(minLength: 6, maxLength: 9), new TupleType([LanguageConstants.String, LanguageConstants.Int], default)), TypeFactory.CreateArrayType(minLength: 6, maxLength: 7), - new TupleType(ImmutableArray.Create(LanguageConstants.String, LanguageConstants.Int), default), + new TupleType([LanguageConstants.String, LanguageConstants.Int], default), TypeFactory.CreateArrayType(minLength: 8, maxLength: 9)), // collapse(string[], [string, string, string]) -> string[] Row(TypeFactory.CreateArrayType(LanguageConstants.String), TypeFactory.CreateArrayType(LanguageConstants.String), - new TupleType(ImmutableArray.Create(LanguageConstants.String, LanguageConstants.String, LanguageConstants.String), default)), + new TupleType([LanguageConstants.String, LanguageConstants.String, LanguageConstants.String], default)), // collapse(string[], [string, int, string]) -> union(string[], [string, int, string]) - Row(TypeHelper.CreateTypeUnion(TypeFactory.CreateArrayType(LanguageConstants.String), new TupleType(ImmutableArray.Create(LanguageConstants.String, LanguageConstants.Int, LanguageConstants.String), default)), + Row(TypeHelper.CreateTypeUnion(TypeFactory.CreateArrayType(LanguageConstants.String), new TupleType([LanguageConstants.String, LanguageConstants.Int, LanguageConstants.String], default)), TypeFactory.CreateArrayType(LanguageConstants.String), - new TupleType(ImmutableArray.Create(LanguageConstants.String, LanguageConstants.Int, LanguageConstants.String), default)), + new TupleType([LanguageConstants.String, LanguageConstants.Int, LanguageConstants.String], default)), // collapse((string | int)[], [string, int, string]) -> (string | int)[] Row(TypeFactory.CreateArrayType(TypeHelper.CreateTypeUnion(LanguageConstants.String, LanguageConstants.Int)), TypeFactory.CreateArrayType(TypeHelper.CreateTypeUnion(LanguageConstants.String, LanguageConstants.Int)), - new TupleType(ImmutableArray.Create(LanguageConstants.String, LanguageConstants.Int, LanguageConstants.String), default)), + new TupleType([LanguageConstants.String, LanguageConstants.Int, LanguageConstants.String], default)), }; } diff --git a/src/Bicep.Core.UnitTests/TypeSystem/TypeValidatorAssignabilityTests.cs b/src/Bicep.Core.UnitTests/TypeSystem/TypeValidatorAssignabilityTests.cs index ba3b4dc5695..fb74170e830 100644 --- a/src/Bicep.Core.UnitTests/TypeSystem/TypeValidatorAssignabilityTests.cs +++ b/src/Bicep.Core.UnitTests/TypeSystem/TypeValidatorAssignabilityTests.cs @@ -249,7 +249,7 @@ private static TypeSymbol Assert_narrowing_diagnostics(TypeSymbol sourceType, Ty private static IEnumerable GetStringDomainNarrowingData() { static object[] Row(TypeSymbol sourceType, TypeSymbol targetType, TypeSymbol expectedType, params (string code, DiagnosticLevel level, string message)[] diagnostics) - => new object[] { sourceType, targetType, expectedType, diagnostics }; + => [sourceType, targetType, expectedType, diagnostics]; return new[] { @@ -339,7 +339,7 @@ public void Integer_domain_narrowing(TypeSymbol sourceType, TypeSymbol targetTyp private static IEnumerable GetIntegerDomainNarrowingData() { static object[] Row(TypeSymbol sourceType, TypeSymbol targetType, TypeSymbol expectedType, params (string code, DiagnosticLevel level, string message)[] diagnostics) - => new object[] { sourceType, targetType, expectedType, diagnostics }; + => [sourceType, targetType, expectedType, diagnostics]; return new[] { @@ -489,7 +489,7 @@ public void InvalidTupleValuesShouldBeRejected() var arrayLiteral = TestSyntaxFactory.CreateArray(new SyntaxBase[] { TestSyntaxFactory.CreateString("foo"), TestSyntaxFactory.CreateInt(5), TestSyntaxFactory.CreateNull() }); var (narrowedType, diagnostics) = NarrowTypeAndCollectDiagnostics(SyntaxHierarchy.Build(arrayLiteral), arrayLiteral, new TupleType( - ImmutableArray.Create(TypeFactory.CreateStringType(maxLength: 2), TypeFactory.CreateIntegerType(minValue: 6)), + [TypeFactory.CreateStringType(maxLength: 2), TypeFactory.CreateIntegerType(minValue: 6)], default)); diagnostics.Should().HaveDiagnostics(new[] @@ -531,7 +531,7 @@ public void Array_domain_narrowing(TypeSymbol sourceType, TypeSymbol targetType, private static IEnumerable GetArrayDomainNarrowingData() { static object[] Row(TypeSymbol sourceType, TypeSymbol targetType, TypeSymbol expectedReturnType, params (string code, DiagnosticLevel level, string message)[] diagnostics) - => new object[] { sourceType, targetType, expectedReturnType, diagnostics }; + => [sourceType, targetType, expectedReturnType, diagnostics]; return new[] { @@ -547,9 +547,9 @@ static object[] Row(TypeSymbol sourceType, TypeSymbol targetType, TypeSymbol exp new TypedArrayType(TypeFactory.CreateIntegerType(1, 10), default)), // A source tuple should narrow its items - Row(new TupleType(ImmutableArray.Create(TypeFactory.CreateIntegerType(1, 10), TypeFactory.CreateStringType(1, 10)), default), - new TupleType(ImmutableArray.Create(TypeFactory.CreateIntegerType(-5, 11), TypeFactory.CreateStringType(maxLength: 20)), default), - new TupleType(ImmutableArray.Create(TypeFactory.CreateIntegerType(1, 10), TypeFactory.CreateStringType(1, 10)), default)), + Row(new TupleType([TypeFactory.CreateIntegerType(1, 10), TypeFactory.CreateStringType(1, 10)], default), + new TupleType([TypeFactory.CreateIntegerType(-5, 11), TypeFactory.CreateStringType(maxLength: 20)], default), + new TupleType([TypeFactory.CreateIntegerType(1, 10), TypeFactory.CreateStringType(1, 10)], default)), // A source type whose domain overlaps but extends below the domain of the target type should narrow and warn Row(TypeFactory.CreateArrayType(1, 10), @@ -746,7 +746,7 @@ public void DiscriminatedObjectType_raises_appropriate_diagnostics_for_matches() // incorrect type specified for the discriminator field var obj = TestSyntaxFactory.CreateObject(new[] { - TestSyntaxFactory.CreateProperty("myDiscriminator", TestSyntaxFactory.CreateObject(Enumerable.Empty())), + TestSyntaxFactory.CreateProperty("myDiscriminator", TestSyntaxFactory.CreateObject([])), TestSyntaxFactory.CreateProperty("fieldB", TestSyntaxFactory.CreateString("someVal")), }); @@ -849,7 +849,7 @@ public void UnionType_narrowing_and_diagnostics_provides_expected_results() { // pick an invalid path (object) - we should get diagnosticWriter - var objectSyntax = TestSyntaxFactory.CreateObject(Enumerable.Empty()); + var objectSyntax = TestSyntaxFactory.CreateObject([]); var hierarchy = SyntaxHierarchy.Build(objectSyntax); var (narrowedType, diagnostics) = NarrowTypeAndCollectDiagnostics(hierarchy, objectSyntax, unionType); @@ -903,7 +903,7 @@ public static string GetDisplayName(MethodInfo method, object[] row) private static IEnumerable GetData() { - static object[] CreateRow(string name, ObjectSyntax @object) => new object[] { name, @object }; + static object[] CreateRow(string name, ObjectSyntax @object) => [name, @object]; // empty object yield return CreateRow("Empty", TestSyntaxFactory.CreateObject(new ObjectPropertySyntax[0])); diff --git a/src/Bicep.Core.UnitTests/TypeSystem/TypeValidatorCompileTimeConstantTests.cs b/src/Bicep.Core.UnitTests/TypeSystem/TypeValidatorCompileTimeConstantTests.cs index 3c873b96009..ff3fdf5687a 100644 --- a/src/Bicep.Core.UnitTests/TypeSystem/TypeValidatorCompileTimeConstantTests.cs +++ b/src/Bicep.Core.UnitTests/TypeSystem/TypeValidatorCompileTimeConstantTests.cs @@ -173,6 +173,6 @@ private static IEnumerable GetNonExpressionData() yield return CreateRow("empty file", new Parser("").Program()); } - private static object[] CreateRow(string name, SyntaxBase expression) => new object[] { name, expression }; + private static object[] CreateRow(string name, SyntaxBase expression) => [name, expression]; } } diff --git a/src/Bicep.Core.UnitTests/TypeSystem/UnionTypeTests.cs b/src/Bicep.Core.UnitTests/TypeSystem/UnionTypeTests.cs index 3eeeeb4903e..f7a692cc2cc 100644 --- a/src/Bicep.Core.UnitTests/TypeSystem/UnionTypeTests.cs +++ b/src/Bicep.Core.UnitTests/TypeSystem/UnionTypeTests.cs @@ -123,7 +123,7 @@ public void UnionsOfUntypedAndTypedArraysShouldProduceUntypedArrayType() LanguageConstants.Array, new TypedArrayType(LanguageConstants.Int, TypeSymbolValidationFlags.Default), LanguageConstants.String, - new ObjectType("myObj", TypeSymbolValidationFlags.Default, Enumerable.Empty(), null)); + new ObjectType("myObj", TypeSymbolValidationFlags.Default, [], null)); actual.Name.Should().Be("array | myObj | string"); } diff --git a/src/Bicep.Core.UnitTests/Utils/BuiltInTestTypes.cs b/src/Bicep.Core.UnitTests/Utils/BuiltInTestTypes.cs index 5e82ac06007..e02c59f0def 100644 --- a/src/Bicep.Core.UnitTests/Utils/BuiltInTestTypes.cs +++ b/src/Bicep.Core.UnitTests/Utils/BuiltInTestTypes.cs @@ -243,7 +243,7 @@ private static ResourceTypeComponents ListFunctionsType() overloads)); } - public static ImmutableArray Types { get; } = new[] { + public static ImmutableArray Types { get; } = [ BasicTestsType(), ReadWriteTestsType(), ReadOnlyTestsType(), @@ -252,7 +252,7 @@ private static ResourceTypeComponents ListFunctionsType() DiscriminatedPropertiesTestsType2(), FallbackPropertyTestsType(), ListFunctionsType(), - }.ToImmutableArray(); + ]; public static INamespaceProvider Create() => new NamespaceProvider( diff --git a/src/Bicep.Core.UnitTests/Utils/CycleDetectorTests.cs b/src/Bicep.Core.UnitTests/Utils/CycleDetectorTests.cs index 5ed1754de7b..dc9cdc24e48 100644 --- a/src/Bicep.Core.UnitTests/Utils/CycleDetectorTests.cs +++ b/src/Bicep.Core.UnitTests/Utils/CycleDetectorTests.cs @@ -43,17 +43,17 @@ public void CycleDetector_should_detect_cycles_correctly() cycles.Keys.Should().BeEquivalentTo(new[] { vertexes[1], vertexes[2], vertexes[3], vertexes[6], vertexes[7], vertexes[8], vertexes[9], vertexes[10] }); - cycles[vertexes[1]].Should().ContainInOrder(new[] { vertexes[1] }); + cycles[vertexes[1]].Should().ContainInOrder([vertexes[1]]); - cycles[vertexes[2]].Should().ContainInOrder(new[] { vertexes[2], vertexes[3] }); - cycles[vertexes[3]].Should().ContainInOrder(new[] { vertexes[3], vertexes[2] }); + cycles[vertexes[2]].Should().ContainInOrder([vertexes[2], vertexes[3]]); + cycles[vertexes[3]].Should().ContainInOrder([vertexes[3], vertexes[2]]); // note that the cycle for each key should be returned in-order, starting with the key - cycles[vertexes[6]].Should().ContainInOrder(new[] { vertexes[6], vertexes[7], vertexes[8], vertexes[9], vertexes[10] }); - cycles[vertexes[7]].Should().ContainInOrder(new[] { vertexes[7], vertexes[8], vertexes[9], vertexes[10], vertexes[6] }); - cycles[vertexes[8]].Should().ContainInOrder(new[] { vertexes[8], vertexes[9], vertexes[10], vertexes[6], vertexes[7] }); - cycles[vertexes[9]].Should().ContainInOrder(new[] { vertexes[9], vertexes[10], vertexes[6], vertexes[7], vertexes[8] }); - cycles[vertexes[10]].Should().ContainInOrder(new[] { vertexes[10], vertexes[6], vertexes[7], vertexes[8], vertexes[9] }); + cycles[vertexes[6]].Should().ContainInOrder([vertexes[6], vertexes[7], vertexes[8], vertexes[9], vertexes[10]]); + cycles[vertexes[7]].Should().ContainInOrder([vertexes[7], vertexes[8], vertexes[9], vertexes[10], vertexes[6]]); + cycles[vertexes[8]].Should().ContainInOrder([vertexes[8], vertexes[9], vertexes[10], vertexes[6], vertexes[7]]); + cycles[vertexes[9]].Should().ContainInOrder([vertexes[9], vertexes[10], vertexes[6], vertexes[7], vertexes[8]]); + cycles[vertexes[10]].Should().ContainInOrder([vertexes[10], vertexes[6], vertexes[7], vertexes[8], vertexes[9]]); } } } diff --git a/src/Bicep.Core.UnitTests/Utils/PrintHelper.cs b/src/Bicep.Core.UnitTests/Utils/PrintHelper.cs index f19d5b41f3d..45de8226d1b 100644 --- a/src/Bicep.Core.UnitTests/Utils/PrintHelper.cs +++ b/src/Bicep.Core.UnitTests/Utils/PrintHelper.cs @@ -45,7 +45,7 @@ private static string[] GetProgramTextLines(BicepSourceFile bicepFile) public static string PrintFullSource(BicepSourceFile bicepFile, int context, bool includeLineNumbers) { - return string.Join("\n", GetProgramTextLines(bicepFile).ToArray()); + return string.Join("\n", [.. GetProgramTextLines(bicepFile)]); } public static string PrintWithAnnotations(BicepSourceFile bicepFile, IEnumerable annotations, int context, bool includeLineNumbers) diff --git a/src/Bicep.Core.UnitTests/Utils/TestTypeHelper.cs b/src/Bicep.Core.UnitTests/Utils/TestTypeHelper.cs index d6223dfb26e..3b59fbc214a 100644 --- a/src/Bicep.Core.UnitTests/Utils/TestTypeHelper.cs +++ b/src/Bicep.Core.UnitTests/Utils/TestTypeHelper.cs @@ -40,7 +40,7 @@ public static IResourceTypeProvider CreateAzResourceTypeProviderWithTypes(IEnume => new AzResourceTypeProvider(new TestResourceTypeLoader(resourceTypes)); public static IResourceTypeLoader CreateEmptyResourceTypeLoader() - => new TestResourceTypeLoader(Enumerable.Empty()); + => new TestResourceTypeLoader([]); public static IResourceTypeLoader CreateResourceTypeLoaderWithTypes(IEnumerable resourceTypes) => new TestResourceTypeLoader(resourceTypes); @@ -57,7 +57,7 @@ public static INamespaceProvider CreateEmptyNamespaceProvider() => new NamespaceProvider( CreateResourceTypeLoaderFactory( CreateAzResourceTypeProviderWithTypes( - Enumerable.Empty()))); + []))); public static ResourceTypeComponents CreateCustomResourceType(string fullyQualifiedType, string apiVersion, TypeSymbolValidationFlags validationFlags, params TypeProperty[] customProperties) => CreateCustomResourceTypeWithTopLevelProperties(fullyQualifiedType, apiVersion, validationFlags, null, customProperties); @@ -97,7 +97,7 @@ params TypeProperty[] customProperties var reference = ResourceTypeReference.Parse($"{fullyQualifiedType}@{apiVersion}"); var resourceProperties = AzResourceTypeProvider.GetCommonResourceProperties(reference) - .Concat(additionalTopLevelProperties ?? Enumerable.Empty()) + .Concat(additionalTopLevelProperties ?? []) .Concat(new TypeProperty("properties", new ObjectType("properties", validationFlags, customProperties, null), TypePropertyFlags.None)); var bodyType = new ObjectType(reference.FormatName(), validationFlags, resourceProperties, null); diff --git a/src/Bicep.Core.UnitTests/Utils/TextByteArray.cs b/src/Bicep.Core.UnitTests/Utils/TextByteArray.cs index 135e29307d1..4f33e8bce3b 100644 --- a/src/Bicep.Core.UnitTests/Utils/TextByteArray.cs +++ b/src/Bicep.Core.UnitTests/Utils/TextByteArray.cs @@ -13,22 +13,22 @@ public class TextByteArray { private readonly ImmutableArray bytes; - public TextByteArray(string text) => bytes = Encoding.UTF8.GetBytes(text).ToImmutableArray(); + public TextByteArray(string text) => bytes = [.. Encoding.UTF8.GetBytes(text)]; - public TextByteArray(byte[] bytes) => this.bytes = bytes.ToImmutableArray(); + public TextByteArray(byte[] bytes) => this.bytes = [.. bytes]; public TextByteArray(ImmutableArray bytes) => this.bytes = bytes; public ImmutableArray Bytes => bytes; - public byte[] ToArray() => bytes.ToArray(); + public byte[] ToArray() => [.. bytes]; // Left as property to make it easier to use in the debugger public string Text => Encoding.UTF8.GetString(bytes.AsSpan()); public Stream ToStream() { - return new MemoryStream(Bytes.ToArray()); + return new MemoryStream([.. Bytes]); } public static Stream TextToStream(string text) diff --git a/src/Bicep.Core.UnitTests/Utils/ThirdPartyTypeHelper.cs b/src/Bicep.Core.UnitTests/Utils/ThirdPartyTypeHelper.cs index 6b62a26653d..d4286c2cbb0 100644 --- a/src/Bicep.Core.UnitTests/Utils/ThirdPartyTypeHelper.cs +++ b/src/Bicep.Core.UnitTests/Utils/ThirdPartyTypeHelper.cs @@ -16,7 +16,7 @@ public static class ThirdPartyTypeHelper { public static IReadOnlyDictionary GetHttpProviderTypes() { - var factory = new TypeFactory(Enumerable.Empty()); + var factory = new TypeFactory([]); var formatType = factory.Create(() => new UnionType([ factory.GetReference(factory.Create(() => new StringLiteralType("raw"))), @@ -74,8 +74,8 @@ public static BinaryData GetHttpProviderTypesTgz() /// public static BinaryData GetTestTypesTgz() { - var factory = new TypeFactory(Enumerable.Empty()); - var rootFactory = new TypeFactory(Enumerable.Empty()); + var factory = new TypeFactory([]); + var rootFactory = new TypeFactory([]); var stringType = factory.Create(() => new StringType()); @@ -124,8 +124,8 @@ public static BinaryData GetTestTypesTgz() public static BinaryData GetTestTypesTgzWithFallbackAndConfiguration() { - var factory = new TypeFactory(Enumerable.Empty()); - var rootFactory = new TypeFactory(Enumerable.Empty()); + var factory = new TypeFactory([]); + var rootFactory = new TypeFactory([]); var stringType = factory.Create(() => new StringType()); var stringTypeRoot = rootFactory.Create(() => new StringType()); @@ -192,7 +192,7 @@ public static BinaryData GetTestTypesTgzWithFallbackAndConfiguration() public static BinaryData GetMockRadiusTypesTgz() { - var factory = new TypeFactory(Enumerable.Empty()); + var factory = new TypeFactory([]); var stringType = factory.Create(() => new StringType()); diff --git a/src/Bicep.Core/Analyzers/Linter/ApiVersions/ApiVersionProvider.cs b/src/Bicep.Core/Analyzers/Linter/ApiVersions/ApiVersionProvider.cs index 7743f39bf02..2f1ea11e3df 100644 --- a/src/Bicep.Core/Analyzers/Linter/ApiVersions/ApiVersionProvider.cs +++ b/src/Bicep.Core/Analyzers/Linter/ApiVersions/ApiVersionProvider.cs @@ -89,7 +89,7 @@ public IEnumerable GetApiVersions(ResourceScope scope, return apiVersions.Select(AzureResourceApiVersion.Parse); } - return Enumerable.Empty(); + return []; } private class ApiVersionCache diff --git a/src/Bicep.Core/Analyzers/Linter/Common/LinterExpressionHelper.cs b/src/Bicep.Core/Analyzers/Linter/Common/LinterExpressionHelper.cs index 9e5e170d71a..3c448894c84 100644 --- a/src/Bicep.Core/Analyzers/Linter/Common/LinterExpressionHelper.cs +++ b/src/Bicep.Core/Analyzers/Linter/Common/LinterExpressionHelper.cs @@ -19,7 +19,7 @@ public static class LinterExpressionHelper // TODO: Refactor more rules to use this public static (string stringValue, StringSyntax stringSyntax, string? pathToValueIfNonTrivial)? TryGetEvaluatedStringLiteral(SemanticModel model, SyntaxBase? expression) { - return TryGetEvaluatedStringLiteral(model, expression, Array.Empty()); + return TryGetEvaluatedStringLiteral(model, expression, []); } private static (string stringValue, StringSyntax stringSyntax, string? pathToValueIfNonTrivial)? TryGetEvaluatedStringLiteral(SemanticModel model, SyntaxBase? expression, DeclaredSymbol[] currentPaths) diff --git a/src/Bicep.Core/Analyzers/Linter/LinterAnalyzer.cs b/src/Bicep.Core/Analyzers/Linter/LinterAnalyzer.cs index 9f4a8906089..ada7538431e 100644 --- a/src/Bicep.Core/Analyzers/Linter/LinterAnalyzer.cs +++ b/src/Bicep.Core/Analyzers/Linter/LinterAnalyzer.cs @@ -46,7 +46,7 @@ private ImmutableArray CreateLinterRules() rules.Add(Activator.CreateInstance(ruleType) as IBicepAnalyzerRule ?? throw new InvalidOperationException($"Failed to create an instance of \"{ruleType.Name}\".")); } - return rules.ToImmutableArray(); + return [.. rules]; } public IEnumerable GetRuleSet() => ruleSet; diff --git a/src/Bicep.Core/Analyzers/Linter/LinterRuleBase.cs b/src/Bicep.Core/Analyzers/Linter/LinterRuleBase.cs index ebb6c83a078..eee9a2433f1 100644 --- a/src/Bicep.Core/Analyzers/Linter/LinterRuleBase.cs +++ b/src/Bicep.Core/Analyzers/Linter/LinterRuleBase.cs @@ -73,7 +73,7 @@ public IEnumerable Analyze(SemanticModel model) { if (GetDiagnosticLevel(model) == DiagnosticLevel.Off) { - return Enumerable.Empty(); + return []; } return AnalyzeInternal(model, GetDiagnosticLevel(model)); @@ -143,7 +143,7 @@ protected virtual AnalyzerDiagnostic CreateDiagnosticForSpan(DiagnosticLevel lev styling: this.DiagnosticStyling); protected virtual AnalyzerFixableDiagnostic CreateFixableDiagnosticForSpan(DiagnosticLevel level, TextSpan span, CodeFix fix, params object[] values) => - CreateFixableDiagnosticForSpan(level, span, new[] { fix }, values); + CreateFixableDiagnosticForSpan(level, span, [fix], values); protected virtual AnalyzerFixableDiagnostic CreateFixableDiagnosticForSpan(DiagnosticLevel level, TextSpan span, CodeFix[] fixes, params object[] values) => new(analyzerName: this.AnalyzerName, diff --git a/src/Bicep.Core/Analyzers/Linter/Rules/LocationRuleBase.cs b/src/Bicep.Core/Analyzers/Linter/Rules/LocationRuleBase.cs index 39e7a560a72..28453c04506 100644 --- a/src/Bicep.Core/Analyzers/Linter/Rules/LocationRuleBase.cs +++ b/src/Bicep.Core/Analyzers/Linter/Rules/LocationRuleBase.cs @@ -169,7 +169,7 @@ protected static ImmutableArray TryGetParameterDefin return bicepFile.ProgramSyntax.Declarations.OfType().ToImmutableArray(); } - return ImmutableArray.Empty; + return []; } /// @@ -187,7 +187,7 @@ private ImmutableArray GetParametersUsedInResourceLocations( GetParametersUsedInResourceLocationsVisitor visitor = new(semanticModel); visitor.Visit(bicepFile.ProgramSyntax); - ImmutableArray parameters = visitor.parameters.ToImmutableArray(); + ImmutableArray parameters = [.. visitor.parameters]; cachedParamsUsedInLocationPropsForFile.Add(bicepFile, parameters); return parameters; } @@ -239,7 +239,7 @@ bool onlyParamsWithDefaultValues } } - return locationParameters.ToImmutableArray(); + return [.. locationParameters]; } /// @@ -276,7 +276,7 @@ bool onlyParamsWithDefaultValues } } - return result.ToImmutableArray(); + return [.. result]; } private class GetParametersUsedInResourceLocationsVisitor : AstVisitor diff --git a/src/Bicep.Core/Analyzers/Linter/Rules/MaxNumberOutputsRule.cs b/src/Bicep.Core/Analyzers/Linter/Rules/MaxNumberOutputsRule.cs index f4a68908581..7754275714b 100644 --- a/src/Bicep.Core/Analyzers/Linter/Rules/MaxNumberOutputsRule.cs +++ b/src/Bicep.Core/Analyzers/Linter/Rules/MaxNumberOutputsRule.cs @@ -30,7 +30,7 @@ override public IEnumerable AnalyzeInternal(SemanticModel model, Di var firstItem = model.Root.OutputDeclarations.First(); return new IDiagnostic[] { CreateDiagnosticForSpan(diagnosticLevel, firstItem.NameSource.Span, MaxNumber) }; } - return Enumerable.Empty(); + return []; } } } diff --git a/src/Bicep.Core/Analyzers/Linter/Rules/MaxNumberParametersRule.cs b/src/Bicep.Core/Analyzers/Linter/Rules/MaxNumberParametersRule.cs index 5400f107134..13e861e2919 100644 --- a/src/Bicep.Core/Analyzers/Linter/Rules/MaxNumberParametersRule.cs +++ b/src/Bicep.Core/Analyzers/Linter/Rules/MaxNumberParametersRule.cs @@ -30,7 +30,7 @@ override public IEnumerable AnalyzeInternal(SemanticModel model, Di var firstItem = model.Root.ParameterDeclarations.First(); return new IDiagnostic[] { CreateDiagnosticForSpan(diagnosticLevel, firstItem.NameSource.Span, MaxNumber) }; } - return Enumerable.Empty(); + return []; } } } diff --git a/src/Bicep.Core/Analyzers/Linter/Rules/MaxNumberResourcesRule.cs b/src/Bicep.Core/Analyzers/Linter/Rules/MaxNumberResourcesRule.cs index f46ea20ce36..9f8525567aa 100644 --- a/src/Bicep.Core/Analyzers/Linter/Rules/MaxNumberResourcesRule.cs +++ b/src/Bicep.Core/Analyzers/Linter/Rules/MaxNumberResourcesRule.cs @@ -30,7 +30,7 @@ override public IEnumerable AnalyzeInternal(SemanticModel model, Di var firstItem = model.DeclaredResources.Where(r => r.Parent is null).First(); return new IDiagnostic[] { CreateDiagnosticForSpan(diagnosticLevel, firstItem.Symbol.NameSource.Span, MaxNumber) }; } - return Enumerable.Empty(); + return []; } } } diff --git a/src/Bicep.Core/Analyzers/Linter/Rules/MaxNumberVariablesRule.cs b/src/Bicep.Core/Analyzers/Linter/Rules/MaxNumberVariablesRule.cs index b62149d79a5..0c517399288 100644 --- a/src/Bicep.Core/Analyzers/Linter/Rules/MaxNumberVariablesRule.cs +++ b/src/Bicep.Core/Analyzers/Linter/Rules/MaxNumberVariablesRule.cs @@ -30,7 +30,7 @@ override public IEnumerable AnalyzeInternal(SemanticModel model, Di var firstItem = model.Root.VariableDeclarations.First(); return new IDiagnostic[] { CreateDiagnosticForSpan(diagnosticLevel, firstItem.NameSource.Span, MaxNumber) }; } - return Enumerable.Empty(); + return []; } } } diff --git a/src/Bicep.Core/Analyzers/Linter/Rules/NoConflictingMetadataRule.cs b/src/Bicep.Core/Analyzers/Linter/Rules/NoConflictingMetadataRule.cs index 9b45821b271..6b0bd064178 100644 --- a/src/Bicep.Core/Analyzers/Linter/Rules/NoConflictingMetadataRule.cs +++ b/src/Bicep.Core/Analyzers/Linter/Rules/NoConflictingMetadataRule.cs @@ -35,10 +35,10 @@ private record MetadataPropertySetByDecorator(string MetadataPropertyName, strin private class Visitor : AstVisitor { - private static readonly ImmutableArray metadataPropertySetByDecorators = ImmutableArray.CreateRange(new MetadataPropertySetByDecorator[] - { + private static readonly ImmutableArray metadataPropertySetByDecorators = + [ new(LanguageConstants.MetadataDescriptionPropertyName, SystemNamespaceType.BuiltInName, LanguageConstants.MetadataDescriptionPropertyName), - }); + ]; private readonly List<(ObjectPropertySyntax, MetadataPropertySetByDecorator)> metadataPropertiesInConflictWithDecorators = new(); private readonly SemanticModel model; diff --git a/src/Bicep.Core/Analyzers/Linter/Rules/NoHardcodedEnvironmentUrlsRule.cs b/src/Bicep.Core/Analyzers/Linter/Rules/NoHardcodedEnvironmentUrlsRule.cs index 18804443cf8..cce71a5a503 100644 --- a/src/Bicep.Core/Analyzers/Linter/Rules/NoHardcodedEnvironmentUrlsRule.cs +++ b/src/Bicep.Core/Analyzers/Linter/Rules/NoHardcodedEnvironmentUrlsRule.cs @@ -33,7 +33,7 @@ public override IEnumerable AnalyzeInternal(SemanticModel model, Di if (model.SourceFile is BicepParamFile) { // The environment() function isn't available for .bicepparam files - return Enumerable.Empty(); + return []; } var disallowedHosts = GetConfigurationValue(model.Configuration.Analyzers, DisallowedHostsKey.ToLowerInvariant(), Array.Empty()).ToImmutableArray(); @@ -47,7 +47,7 @@ public override IEnumerable AnalyzeInternal(SemanticModel model, Di return visitor.DisallowedHostSpans.Select(entry => CreateDiagnosticForSpan(diagnosticLevel, entry.Key, entry.Value)); } - return Enumerable.Empty(); + return []; } public static IEnumerable<(TextSpan RelativeSpan, string Value)> FindHostnameMatches(string hostname, string srcText) diff --git a/src/Bicep.Core/Analyzers/Linter/Rules/NoUnusedExistingResourcesRule.cs b/src/Bicep.Core/Analyzers/Linter/Rules/NoUnusedExistingResourcesRule.cs index f8b4041c33e..74b8f36a8b9 100644 --- a/src/Bicep.Core/Analyzers/Linter/Rules/NoUnusedExistingResourcesRule.cs +++ b/src/Bicep.Core/Analyzers/Linter/Rules/NoUnusedExistingResourcesRule.cs @@ -32,7 +32,7 @@ override public IEnumerable AnalyzeInternal(SemanticModel model, Di .Where(sym => sym.NameSource.IsValid) .Where(sym => sym.DeclaringResource.IsExistingResource()) .Where(sym => !invertedBindings[sym].Any(x => x != sym.DeclaringSyntax)) - .Where(sym => !(sym.DeclaringResource.TryGetBody()?.Resources ?? Enumerable.Empty()).Any()); + .Where(sym => !(sym.DeclaringResource.TryGetBody()?.Resources ?? []).Any()); foreach (var sym in unreferencedResources) { yield return CreateRemoveUnusedDiagnosticForSpan(diagnosticLevel, sym.Name, sym.NameSource.Span, sym.DeclaringSyntax, model.SourceFile.ProgramSyntax); diff --git a/src/Bicep.Core/Analyzers/Linter/Rules/UseProtectedSettingsForCommandToExecuteSecretsRule.cs b/src/Bicep.Core/Analyzers/Linter/Rules/UseProtectedSettingsForCommandToExecuteSecretsRule.cs index 0d58a05177f..555bf5d2f1b 100644 --- a/src/Bicep.Core/Analyzers/Linter/Rules/UseProtectedSettingsForCommandToExecuteSecretsRule.cs +++ b/src/Bicep.Core/Analyzers/Linter/Rules/UseProtectedSettingsForCommandToExecuteSecretsRule.cs @@ -13,12 +13,13 @@ public sealed class ProtectCommandToExecuteSecretsRule : LinterRuleBase { public new const string Code = "protect-commandtoexecute-secrets"; - private static readonly ImmutableArray<(string publisher, string type)> publisherAndNameList = ImmutableArray.Create<(string publisher, string type)>( - // NOTE: This list was obtained by running "az vm extension image list" + private static readonly ImmutableArray<(string publisher, string type)> publisherAndNameList = + [ ("Microsoft.Azure.Extensions", "CustomScript"), ("Microsoft.Compute", "CustomScriptExtension"), ("Microsoft.OSTCExtensions", "CustomScriptForLinux") - ); +, + ]; public static ImmutableArray<(string publisher, string type)> PublisherAndNameList => publisherAndNameList; diff --git a/src/Bicep.Core/Analyzers/Linter/Rules/UseRecentApiVersionRule.cs b/src/Bicep.Core/Analyzers/Linter/Rules/UseRecentApiVersionRule.cs index 5191538095d..fd0d8693b76 100644 --- a/src/Bicep.Core/Analyzers/Linter/Rules/UseRecentApiVersionRule.cs +++ b/src/Bicep.Core/Analyzers/Linter/Rules/UseRecentApiVersionRule.cs @@ -431,7 +431,7 @@ public static (AzureResourceApiVersion[] allApiVersions, AzureResourceApiVersion var recentPreviewVersionsSorted = FilterRecent(previewVersionsSorted, today, maxAgeInDays).ToArray(); // Start with all recent stable versions - List acceptableVersions = recentStableVersionsSorted.ToList(); + List acceptableVersions = [.. recentStableVersionsSorted]; // If no recent stable versions, add the most recent stable version, if any if (!acceptableVersions.Any()) @@ -487,7 +487,7 @@ public static (AzureResourceApiVersion[] allApiVersions, AzureResourceApiVersion private static Failure CreateFailureFromMessage(TextSpan span, string message) { - return new Failure(span, message, Array.Empty(), Array.Empty()); + return new Failure(span, message, [], []); } private static Failure CreateFailureFromApiVersion(TextSpan errorSpan, TextSpan replacementSpan, string message, AzureResourceApiVersion[] acceptableVersionsSorted) diff --git a/src/Bicep.Core/Analyzers/Linter/Rules/UseResourceIdFunctionsRule.cs b/src/Bicep.Core/Analyzers/Linter/Rules/UseResourceIdFunctionsRule.cs index 71704de6c3a..a187d294c88 100644 --- a/src/Bicep.Core/Analyzers/Linter/Rules/UseResourceIdFunctionsRule.cs +++ b/src/Bicep.Core/Analyzers/Linter/Rules/UseResourceIdFunctionsRule.cs @@ -50,61 +50,61 @@ public Exclusion(string? regexResourceType, string? propertyName) // an exact resource type, plus some of them occur in multiple resource types. // Resource type is a regex pattern (case-insensitive), property name is an exact match (case-insensitive) - private static readonly Exclusion[] allowedResourcesAndProperties = new[] { + private static readonly Exclusion[] allowedResourcesAndProperties = [ new Exclusion(null, "appId"), // Example: Microsoft.Insights - new Exclusion(null, "appId"), // Example: Microsoft.Insights - new Exclusion(null, "clientId"), // Example: Microsoft.BotService - common var name - new Exclusion(null, "contentId"), // Example: Microsoft.Sentinel/Solutions/Metadata - new Exclusion(null, "connectorId"), // Example: Microsoft.Sentinel/Solutions/Analytical Rule/Metadata - new Exclusion(null, "DataTypeId"), // Example: Microsoft.OperationalInsights/workspaces/dataSources - new Exclusion(null, "defaultMenuItemId"), // Example: Microsoft.Portal/dashboards - it's a messy resource - new Exclusion(null, "deploymentSpecId"), // Example: Microsoft.NetApp/netAppAccounts/volumeGroups - new Exclusion(null, "detector"), // Example: microsoft.alertsmanagement/smartdetectoralertrules (detector.id is the one we want to skip) - new Exclusion(null, "groupId"), // Example: Microsoft.DataFactory/factories/managedVirtualNetworks/managedPrivateEndpoints - new Exclusion(null, "IllusiveIncidentId"), // Example: Microsoft.Sentinel/Solutions/Analytical Rule/Metadata - new Exclusion(null, "keyId"), // Example: Microsoft.Cdn/profiles urlSigningKeys - new Exclusion(null, "keyVaultId"), // Example: KeyVaultIDs - new Exclusion(null, "keyVaultSecretId"), // Example: Microsoft.Network/applicationGateways sslCertificates - this is actually a uri created with reference() and concat /secrets/secretname - new Exclusion(null, "locations"), // Example: Microsoft.Insights/webtests - new Exclusion(null, "menuId"), // Example: Microsoft.Portal/dashboards - new Exclusion(null, "metadata"), // Multiple resources - new Exclusion(null, "metricId"), // Example: Microsoft.ServiceBus/namespaces - new Exclusion(null, "nodeAgentSkuId"), // Example: Microsoft.Batch/batchAccounts/pools - new Exclusion(null, "objectId"), // Common Property name - new Exclusion(null, "parentId"), // Example: Microsoft.Sentinel/Solutions/Metadata - new Exclusion(null, "policyDefinitionReferenceId"), // Example: Microsft.Authorization/policySetDefinition unique Id used when setting up a PolicyDefinitionReference - new Exclusion(null, "requestedServiceObjectiveId"), // Example: Microsoft.Sql/servers/databases - new Exclusion(null, "resource"), // Example: Microsoft.DocumentDB/databaseAccounts/sqlDatabase and child resources - new Exclusion(null, "ruleId"), // Example: Microsoft.Network/applicationGatewayWebApplicationFirewallPolicies - new Exclusion(null, "schemaId"), // Example: Microsoft.ApiManagement/service/apis/operations - new Exclusion(null, "servicePrincipalClientId"), // Common var name - new Exclusion(null, "sid"), // Example: Microsoft.Sql/servers/administrators/activeDirectory - new Exclusion(null, "StartingDeviceID"), // Example: SQLIaasVMExtension > settings/ServerConfigurationsManagementSettings/SQLStorageUpdateSettings - new Exclusion(null, "subscriptionId"), // Example: Microsoft.Cdn/profiles urlSigningKeys - new Exclusion(null, "storageAccountSubscriptionId"),// Example: Microsoft.Sql/servers/auditingSettings - new Exclusion(null, "SyntheticMonitorId"), // Example: Microsoft.Insights/webtests - new Exclusion(null, "tags"), // Multiple resources - new Exclusion(null, "targetProtectionContainerId"), // Example: Microsoft.RecoveryServices/vaults/replicationFabrics/replicationProtectionContainers/replicationProtectionContainerMappings (yes really) - new Exclusion(null, "targetWorkerSizeId"), // Example: Microsoft.Web/serverFarms (later apiVersions) - new Exclusion(null, "tenantId"), // Common Property name - new Exclusion(null, "timezoneId"), // Example: Microsoft.SQL/managedInstances - new Exclusion(null, "vlanId"), // Example: Unique Id to establish peering when setting up an ExpressRoute circuit - new Exclusion(null, "workerSizeId"), // Example: Microsoft.Web/serverFarms (older apiVersions) - new Exclusion(null, "UniqueFindingId"), // Example: Microsoft.Sentinel/Solutions/Metadata - new Exclusion(null, "principalId"), // Example: Microsoft.DocumentDB/databaseAccounts/sqlRoleAssignments - - // These resource types are completely excluded from the rule - new Exclusion("^microsoft.portal/dashboards$", null), - new Exclusion("^microsoft.logic/workflows$", null), - new Exclusion("^microsoft.ApiManagement/service/backends$", null), - new Exclusion("^Microsoft.Web/sites/config", null), - // Skip for Microsoft.DocumentDb/databaseAccounts/mongodbDatabases/collections - // and for "other collections" on docDB - new Exclusion(@"^Microsoft\.DocumentDb/databaseAccounts/\w{0,}/collections$", null), - - // Specific properties of specific resource types - new Exclusion("^Microsoft.ApiManagement/service/subscriptions$", "ownerId"), // #8382 - }; + new Exclusion(null, "appId"), // Example: Microsoft.Insights + new Exclusion(null, "clientId"), // Example: Microsoft.BotService - common var name + new Exclusion(null, "contentId"), // Example: Microsoft.Sentinel/Solutions/Metadata + new Exclusion(null, "connectorId"), // Example: Microsoft.Sentinel/Solutions/Analytical Rule/Metadata + new Exclusion(null, "DataTypeId"), // Example: Microsoft.OperationalInsights/workspaces/dataSources + new Exclusion(null, "defaultMenuItemId"), // Example: Microsoft.Portal/dashboards - it's a messy resource + new Exclusion(null, "deploymentSpecId"), // Example: Microsoft.NetApp/netAppAccounts/volumeGroups + new Exclusion(null, "detector"), // Example: microsoft.alertsmanagement/smartdetectoralertrules (detector.id is the one we want to skip) + new Exclusion(null, "groupId"), // Example: Microsoft.DataFactory/factories/managedVirtualNetworks/managedPrivateEndpoints + new Exclusion(null, "IllusiveIncidentId"), // Example: Microsoft.Sentinel/Solutions/Analytical Rule/Metadata + new Exclusion(null, "keyId"), // Example: Microsoft.Cdn/profiles urlSigningKeys + new Exclusion(null, "keyVaultId"), // Example: KeyVaultIDs + new Exclusion(null, "keyVaultSecretId"), // Example: Microsoft.Network/applicationGateways sslCertificates - this is actually a uri created with reference() and concat /secrets/secretname + new Exclusion(null, "locations"), // Example: Microsoft.Insights/webtests + new Exclusion(null, "menuId"), // Example: Microsoft.Portal/dashboards + new Exclusion(null, "metadata"), // Multiple resources + new Exclusion(null, "metricId"), // Example: Microsoft.ServiceBus/namespaces + new Exclusion(null, "nodeAgentSkuId"), // Example: Microsoft.Batch/batchAccounts/pools + new Exclusion(null, "objectId"), // Common Property name + new Exclusion(null, "parentId"), // Example: Microsoft.Sentinel/Solutions/Metadata + new Exclusion(null, "policyDefinitionReferenceId"), // Example: Microsft.Authorization/policySetDefinition unique Id used when setting up a PolicyDefinitionReference + new Exclusion(null, "requestedServiceObjectiveId"), // Example: Microsoft.Sql/servers/databases + new Exclusion(null, "resource"), // Example: Microsoft.DocumentDB/databaseAccounts/sqlDatabase and child resources + new Exclusion(null, "ruleId"), // Example: Microsoft.Network/applicationGatewayWebApplicationFirewallPolicies + new Exclusion(null, "schemaId"), // Example: Microsoft.ApiManagement/service/apis/operations + new Exclusion(null, "servicePrincipalClientId"), // Common var name + new Exclusion(null, "sid"), // Example: Microsoft.Sql/servers/administrators/activeDirectory + new Exclusion(null, "StartingDeviceID"), // Example: SQLIaasVMExtension > settings/ServerConfigurationsManagementSettings/SQLStorageUpdateSettings + new Exclusion(null, "subscriptionId"), // Example: Microsoft.Cdn/profiles urlSigningKeys + new Exclusion(null, "storageAccountSubscriptionId"),// Example: Microsoft.Sql/servers/auditingSettings + new Exclusion(null, "SyntheticMonitorId"), // Example: Microsoft.Insights/webtests + new Exclusion(null, "tags"), // Multiple resources + new Exclusion(null, "targetProtectionContainerId"), // Example: Microsoft.RecoveryServices/vaults/replicationFabrics/replicationProtectionContainers/replicationProtectionContainerMappings (yes really) + new Exclusion(null, "targetWorkerSizeId"), // Example: Microsoft.Web/serverFarms (later apiVersions) + new Exclusion(null, "tenantId"), // Common Property name + new Exclusion(null, "timezoneId"), // Example: Microsoft.SQL/managedInstances + new Exclusion(null, "vlanId"), // Example: Unique Id to establish peering when setting up an ExpressRoute circuit + new Exclusion(null, "workerSizeId"), // Example: Microsoft.Web/serverFarms (older apiVersions) + new Exclusion(null, "UniqueFindingId"), // Example: Microsoft.Sentinel/Solutions/Metadata + new Exclusion(null, "principalId"), // Example: Microsoft.DocumentDB/databaseAccounts/sqlRoleAssignments + + // These resource types are completely excluded from the rule + new Exclusion("^microsoft.portal/dashboards$", null), + new Exclusion("^microsoft.logic/workflows$", null), + new Exclusion("^microsoft.ApiManagement/service/backends$", null), + new Exclusion("^Microsoft.Web/sites/config", null), + // Skip for Microsoft.DocumentDb/databaseAccounts/mongodbDatabases/collections + // and for "other collections" on docDB + new Exclusion(@"^Microsoft\.DocumentDb/databaseAccounts/\w{0,}/collections$", null), + + // Specific properties of specific resource types + new Exclusion("^Microsoft.ApiManagement/service/subscriptions$", "ownerId"), // #8382 + ]; internal record Failure( ObjectPropertySyntax Property, @@ -131,7 +131,7 @@ public override IEnumerable AnalyzeInternal(SemanticModel model, Di } string[] excludedPropertiesForThisResource = exclusionsMatchingResourceType.Select(excl => excl.propertyName!).ToArray(); // propertyName can't be null in this list - var visitor = new IdPropertyVisitor(model, excludedPropertiesForThisResource.ToArray()); + var visitor = new IdPropertyVisitor(model, [.. excludedPropertiesForThisResource]); properties.Accept(visitor); foreach (Failure failure in visitor.Failures) @@ -139,7 +139,7 @@ public override IEnumerable AnalyzeInternal(SemanticModel model, Di var propertyName = failure.Property.Key.ToString(); var paths = failure.PathToExpression.Any() ? (new string[] { propertyName }).Concat(failure.PathToExpression.Select(s => s.Name)) : - Enumerable.Empty(); + []; var path = string.Join(" -> ", paths); yield return CreateDiagnosticForSpan( diagnosticLevel, @@ -155,7 +155,7 @@ public override string FormatMessage(params object[] values) { var propertyName = (string)values[0]; var path = (string)values[1]; - var allowedList = string.Join(", ", allowedFunctions.OrderByAscendingInsensitively(k => k).ToArray()); + var allowedList = string.Join(", ", [.. allowedFunctions.OrderByAscendingInsensitively(k => k)]); var mainMessage = string.Format(CoreResources.UseResourceIdFunctionsRule_MessageFormat, propertyName, allowedList); var pathMessage = string.IsNullOrWhiteSpace(path) ? null : string.Format(CoreResources.UseResourceIdFunctionsRule_NonConformingExprPath, path); return pathMessage is null ? mainMessage : $"{mainMessage} {pathMessage}"; @@ -238,7 +238,7 @@ private static ResourceIdStatus IsResourceIdProperty(ObjectPropertySyntax Proper var type = model.GetTypeInfo(propertySyntax.Value); if (type.IsString() || type.IsNullableString()) { - return AnalyzeIdPropertyValue(model, propertySyntax, propertySyntax.Value, Array.Empty()); + return AnalyzeIdPropertyValue(model, propertySyntax, propertySyntax.Value, []); } return null; diff --git a/src/Bicep.Core/Analyzers/Linter/Rules/UseResourceSymbolReferenceRule.cs b/src/Bicep.Core/Analyzers/Linter/Rules/UseResourceSymbolReferenceRule.cs index fa7a14ba221..895e648e6dc 100644 --- a/src/Bicep.Core/Analyzers/Linter/Rules/UseResourceSymbolReferenceRule.cs +++ b/src/Bicep.Core/Analyzers/Linter/Rules/UseResourceSymbolReferenceRule.cs @@ -180,7 +180,7 @@ functionCall.Arguments[2].Expression is StringSyntax fullString && var newArgs = functionCall.Arguments.Length == 2 ? new SyntaxBase[] { } : - new SyntaxBase[] { functionCall.Arguments[1].Expression, functionCall.Arguments[2].Expression }; + [functionCall.Arguments[1].Expression, functionCall.Arguments[2].Expression]; var newFunctionCall = SyntaxFactory.CreateInstanceFunctionCall( SyntaxFactory.CreateIdentifier(resource.Symbol.Name), diff --git a/src/Bicep.Core/Analyzers/Linter/Rules/UseStableVMImageRule.cs b/src/Bicep.Core/Analyzers/Linter/Rules/UseStableVMImageRule.cs index 5b34a9585df..9748c4d2f16 100644 --- a/src/Bicep.Core/Analyzers/Linter/Rules/UseStableVMImageRule.cs +++ b/src/Bicep.Core/Analyzers/Linter/Rules/UseStableVMImageRule.cs @@ -16,7 +16,7 @@ public sealed class UseStableVMImageRule : LinterRuleBase { public new const string Code = "use-stable-vm-image"; - private readonly ImmutableHashSet imageReferenceProperties = ImmutableHashSet.Create("offer", "sku", "version"); + private readonly ImmutableHashSet imageReferenceProperties = ["offer", "sku", "version"]; public UseStableVMImageRule() : base( code: Code, diff --git a/src/Bicep.Core/CodeAction/Fixes/DecoratorCodeFixProvider.cs b/src/Bicep.Core/CodeAction/Fixes/DecoratorCodeFixProvider.cs index 9dbb215118a..f3057f85f70 100644 --- a/src/Bicep.Core/CodeAction/Fixes/DecoratorCodeFixProvider.cs +++ b/src/Bicep.Core/CodeAction/Fixes/DecoratorCodeFixProvider.cs @@ -87,12 +87,12 @@ private SyntaxBase[] GetEmptyParams() switch (decorator.Overload.FixedParameters[0].Type) { case ArrayType: - return new[] { SyntaxFactory.CreateArray(Enumerable.Empty()) }; + return new[] { SyntaxFactory.CreateArray([]) }; case StringType: return new[] { SyntaxFactory.CreateStringLiteral(String.Empty) }; } } - return Array.Empty(); + return []; } } diff --git a/src/Bicep.Core/Collections/Trees/IntervalTreeNode.cs b/src/Bicep.Core/Collections/Trees/IntervalTreeNode.cs index c839487723a..9650ebca782 100644 --- a/src/Bicep.Core/Collections/Trees/IntervalTreeNode.cs +++ b/src/Bicep.Core/Collections/Trees/IntervalTreeNode.cs @@ -7,7 +7,7 @@ public class IntervalTreeNode { public readonly static IntervalTreeNode Nil = new(-1, -1, new List()); - private readonly IntervalTreeNode[] children = new[] { Nil, Nil }; + private readonly IntervalTreeNode[] children = [Nil, Nil]; public IntervalTreeNode(int start, int end, TData data) : this(start, end, new List() { data }) diff --git a/src/Bicep.Core/Configuration/CloudConfiguration.cs b/src/Bicep.Core/Configuration/CloudConfiguration.cs index eccdd203acf..3b2f10990c9 100644 --- a/src/Bicep.Core/Configuration/CloudConfiguration.cs +++ b/src/Bicep.Core/Configuration/CloudConfiguration.cs @@ -16,7 +16,7 @@ public record Cloud public ImmutableSortedDictionary Profiles { get; init; } = ImmutableSortedDictionary.Empty; - public ImmutableArray CredentialPrecedence { get; init; } = ImmutableArray.Empty; + public ImmutableArray CredentialPrecedence { get; init; } = []; public CredentialOptions? CredentialOptions { get; init; } } diff --git a/src/Bicep.Core/DataFlow/LocalSymbolDependencyVisitor.cs b/src/Bicep.Core/DataFlow/LocalSymbolDependencyVisitor.cs index 2301b85431f..acf59527f2e 100644 --- a/src/Bicep.Core/DataFlow/LocalSymbolDependencyVisitor.cs +++ b/src/Bicep.Core/DataFlow/LocalSymbolDependencyVisitor.cs @@ -23,7 +23,7 @@ public static ImmutableHashSet GetLocalSymbolDependencies(S var visitor = new LocalSymbolDependencyVisitor(semanticModel); visitor.Visit(syntax); - return visitor.SymbolDependencies.ToImmutableHashSet(); + return [.. visitor.SymbolDependencies]; } public override void VisitVariableAccessSyntax(VariableAccessSyntax syntax) diff --git a/src/Bicep.Core/Diagnostics/EmptyDiagnosticLookup.cs b/src/Bicep.Core/Diagnostics/EmptyDiagnosticLookup.cs index e10b98d4867..9fb2662c5ef 100644 --- a/src/Bicep.Core/Diagnostics/EmptyDiagnosticLookup.cs +++ b/src/Bicep.Core/Diagnostics/EmptyDiagnosticLookup.cs @@ -12,7 +12,7 @@ public sealed class EmptyDiagnosticLookup : IDiagnosticLookup private EmptyDiagnosticLookup() { } - public IEnumerable this[IPositionable positionable] => Enumerable.Empty(); + public IEnumerable this[IPositionable positionable] => []; public bool Contains(IPositionable positionable) => false; diff --git a/src/Bicep.Core/Emit/CompileTimeImports/ArmDeclarationToExpressionConverter.cs b/src/Bicep.Core/Emit/CompileTimeImports/ArmDeclarationToExpressionConverter.cs index 0de8306d920..325a5677000 100644 --- a/src/Bicep.Core/Emit/CompileTimeImports/ArmDeclarationToExpressionConverter.cs +++ b/src/Bicep.Core/Emit/CompileTimeImports/ArmDeclarationToExpressionConverter.cs @@ -414,8 +414,11 @@ private Expression ConvertToVariableValue(string originalName) this.activeCopyLoopName = originalName; var expression = new ForLoopExpression(sourceSyntax, - new FunctionCallExpression(sourceSyntax, "range", ImmutableArray.Create(ExpressionFactory.CreateIntegerLiteral(0, sourceSyntax), - ConvertToExpression(ExpressionsEngine.ParseLanguageExpressionsRecursive(copyDeclaration.CountToken), copyDeclaration.CountToken))), + new FunctionCallExpression(sourceSyntax, "range", + [ + ExpressionFactory.CreateIntegerLiteral(0, sourceSyntax), + ConvertToExpression(ExpressionsEngine.ParseLanguageExpressionsRecursive(copyDeclaration.CountToken), copyDeclaration.CountToken), + ]), ConvertToExpression(ExpressionsEngine.ParseLanguageExpressionsRecursive(copyDeclaration.ValueItemToken), copyDeclaration.ValueItemToken), null, null); @@ -459,7 +462,7 @@ ObjectPropertyExpression convertObjectProperty(JProperty property) // there's no Bicep expression that corresponds to .Float, so use a `json('')` function expression JTokenType.Float => new FunctionCallExpression(sourceSyntax, "json", - ImmutableArray.Create(ExpressionFactory.CreateStringLiteral(toConvert.ToString()))), + [ExpressionFactory.CreateStringLiteral(toConvert.ToString())]), JTokenType.Boolean => ExpressionFactory.CreateBooleanLiteral(toConvert.ToObject(), sourceSyntax), JTokenType.Null => new NullLiteralExpression(sourceSyntax), // everything else (.String, .Date, .Uri, etc.) is some specialization of string @@ -511,7 +514,7 @@ private Expression ConvertToExpression(FunctionExpression func) StringLiteralExpression constantVariableName => new SynthesizedVariableReferenceExpression(sourceSyntax, armIdentifierToSymbolNameMapping[new(ArmSymbolType.Variable, constantVariableName.Value)]), // if the argument to variables() was itself a runtime-evaluated expression, just treat this as a function call - Expression otherwise => new FunctionCallExpression(sourceSyntax, VariablesFunctionName, ImmutableArray.Create(otherwise)), + Expression otherwise => new FunctionCallExpression(sourceSyntax, VariablesFunctionName, [otherwise]), }, CopyIndexFunctionName when variablesEvaluator.TryEvaluate(func.Parameters[0]) is JValue { Value: string copyIndexName } && StringComparer.OrdinalIgnoreCase.Equals(activeCopyLoopName, copyIndexName) => func.Parameters.Skip(1).FirstOrDefault() switch diff --git a/src/Bicep.Core/Emit/ExpressionConverter.cs b/src/Bicep.Core/Emit/ExpressionConverter.cs index a93a8a51387..2f74c97511d 100644 --- a/src/Bicep.Core/Emit/ExpressionConverter.cs +++ b/src/Bicep.Core/Emit/ExpressionConverter.cs @@ -148,7 +148,7 @@ public LanguageExpression ConvertExpression(Expression expression) return ConvertAccessChain(exp); case AccessExpression exp: - return ConvertAccessExpression(exp, Enumerable.Empty()); + return ConvertAccessExpression(exp, []); case ResourceReferenceExpression exp: return GetReferenceExpression(exp.Metadata, exp.IndexContext, true); @@ -274,17 +274,15 @@ private LanguageExpression ConvertAccessExpression(AccessExpression expression, // creates an expression like: `last(split(, '/'))` LanguageExpression NameFromIdExpression(LanguageExpression idExpression) => new FunctionExpression("last", - new LanguageExpression[] - { + [ new FunctionExpression("split", - new LanguageExpression[] - { + [ idExpression, new JTokenExpression("/"), - }, - Array.Empty()), - }, - Array.Empty()); + ], + []), + ], + []); // The cases for a parameter resource are much simpler and can be handled up front. These do not // support symbolic names they are somewhat different from the declared resource case since we just have an @@ -342,19 +340,17 @@ private LanguageExpression ConvertAccessExpression(AccessExpression expression, // retrieve the value of that output), but this inefficiency is unavoidable since passing `null` to `split` will cause the deployment to fail return ( new FunctionExpression("if", - new LanguageExpression[] - { + [ new FunctionExpression("contains", - new LanguageExpression[] - { + [ AppendProperties(GetModuleReferenceExpression(output.Module, null, true), new JTokenExpression("outputs")), new JTokenExpression(output.OutputName), - }, - Array.Empty()), + ], + []), NameFromIdExpression(GetFullyQualifiedResourceId(output)), - new FunctionExpression("null", Array.Empty(), Array.Empty()), - }, - Array.Empty()), + new FunctionExpression("null", [], []), + ], + []), Enumerable.Empty(), true); case "name": @@ -509,8 +505,8 @@ public LanguageExpression GetFullyQualifiedResourceId(ResourceMetadata resource) { return new FunctionExpression( "parameters", - new LanguageExpression[] { new JTokenExpression(parameter.Symbol.Name), }, - new LanguageExpression[] { }); + [new JTokenExpression(parameter.Symbol.Name),], + []); } else if (resource is ModuleOutputResourceMetadata output) { @@ -577,8 +573,8 @@ public FunctionExpression GetReferenceExpression(ResourceMetadata resource, Inde { ParameterResourceMetadata parameter => new FunctionExpression( "parameters", - new LanguageExpression[] { new JTokenExpression(parameter.Symbol.Name), }, - Array.Empty()), + [new JTokenExpression(parameter.Symbol.Name),], + []), ModuleOutputResourceMetadata output => AppendProperties( GetModuleReferenceExpression(output.Module, null, true), @@ -881,13 +877,13 @@ private static FunctionExpression CreateFunction(string name, params LanguageExp => CreateFunction(name, parameters as IEnumerable); private static FunctionExpression CreateFunction(string name, IEnumerable parameters) - => new(name, parameters.ToArray(), Array.Empty()); + => new(name, parameters.ToArray(), []); private static FunctionExpression AppendProperties(FunctionExpression function, params LanguageExpression[] properties) => AppendProperties(function, properties as IEnumerable); private static FunctionExpression AppendProperties(FunctionExpression function, IEnumerable properties) - => new(function.Function, function.Parameters, function.Properties.Concat(properties).ToArray()); + => new(function.Function, function.Parameters, [.. function.Properties, .. properties]); private static (string namespaceName, string functionName) GetFunctionName(string potentiallyQualifiedName) => potentiallyQualifiedName.IndexOf('.') switch { diff --git a/src/Bicep.Core/Emit/ExpressionEmitter.cs b/src/Bicep.Core/Emit/ExpressionEmitter.cs index 2b92e875924..a2aada930ea 100644 --- a/src/Bicep.Core/Emit/ExpressionEmitter.cs +++ b/src/Bicep.Core/Emit/ExpressionEmitter.cs @@ -217,7 +217,7 @@ static bool CanEmitAsInputDirectly(Expression input) // construct the length ARM expression from the Bicep array expression // type check has already ensured that the array expression is an array - this.EmitProperty("count", new FunctionCallExpression(forExpression.SourceSyntax, "length", new[] { forExpression }.ToImmutableArray())); + this.EmitProperty("count", new FunctionCallExpression(forExpression.SourceSyntax, "length", [forExpression])); if (batchSize.HasValue) { @@ -261,7 +261,7 @@ static bool CanEmitAsInputDirectly(Expression input) { // it's an invocation of the copyIndex function with 1 argument with a literal value // replace the argument with the correct value - function.Parameters = new LanguageExpression[] { new JTokenExpression("value") }; + function.Parameters = [new JTokenExpression("value")]; } } }; diff --git a/src/Bicep.Core/Emit/InlineDependencyVisitor.cs b/src/Bicep.Core/Emit/InlineDependencyVisitor.cs index 3fc47f899ad..ca537e4f064 100644 --- a/src/Bicep.Core/Emit/InlineDependencyVisitor.cs +++ b/src/Bicep.Core/Emit/InlineDependencyVisitor.cs @@ -39,7 +39,7 @@ private InlineDependencyVisitor(SemanticModel model, VariableDeclarationSyntax? if (targetVariable is not null) { // the functionality - this.currentStack = ImmutableStack.Create(); + this.currentStack = []; this.capturedSequence = null; } } @@ -68,7 +68,7 @@ public static ImmutableHashSet GetVariablesToInline(SemanticMode /// The variable access chain that leads to inlining or empty if not available. public static bool ShouldInlineVariable(SemanticModel model, VariableDeclarationSyntax variable, out ImmutableArray variableAccessChain) { - variableAccessChain = ImmutableArray.Empty; + variableAccessChain = []; if (model.GetSymbolInfo(variable) is not VariableSymbol variableSymbol) { // we have errors - assume this is not meant to be inlined @@ -83,7 +83,7 @@ public static bool ShouldInlineVariable(SemanticModel model, VariableDeclaration return false; } - variableAccessChain = visitor.capturedSequence?.Reverse().ToImmutableArray() ?? ImmutableArray.Empty; + variableAccessChain = visitor.capturedSequence?.Reverse().ToImmutableArray() ?? []; return true; } diff --git a/src/Bicep.Core/Emit/PlaceholderParametersBicepParamWriter.cs b/src/Bicep.Core/Emit/PlaceholderParametersBicepParamWriter.cs index 9a215927a72..bcb6da85d40 100644 --- a/src/Bicep.Core/Emit/PlaceholderParametersBicepParamWriter.cs +++ b/src/Bicep.Core/Emit/PlaceholderParametersBicepParamWriter.cs @@ -91,9 +91,9 @@ private SyntaxBase GetValueForParameter(ParameterDeclarationSyntax syntax) case "bool": return SyntaxFactory.CreateBooleanLiteral(false); case "array": - return SyntaxFactory.CreateArray(Enumerable.Empty()); + return SyntaxFactory.CreateArray([]); case "object": - return SyntaxFactory.CreateObject(Enumerable.Empty()); + return SyntaxFactory.CreateObject([]); case "string": default: return SyntaxFactory.CreateStringLiteral((allowedDecoratorFirstItem as StringSyntax)?.SegmentValues.First() ?? ""); diff --git a/src/Bicep.Core/Emit/PositionTrackingJsonTextWriter.cs b/src/Bicep.Core/Emit/PositionTrackingJsonTextWriter.cs index 1632f335dbc..ab7cfb278c1 100644 --- a/src/Bicep.Core/Emit/PositionTrackingJsonTextWriter.cs +++ b/src/Bicep.Core/Emit/PositionTrackingJsonTextWriter.cs @@ -288,7 +288,7 @@ private void AddRawMapping(BicepSourceFile bicepFile, TextSpan bicepPosition, Te return new SourceMap( entrypointFileName, - sourceMapFileEntries.ToImmutableArray()); + [.. sourceMapFileEntries]); } } } diff --git a/src/Bicep.Core/Emit/ResourceDependencyVisitor.cs b/src/Bicep.Core/Emit/ResourceDependencyVisitor.cs index a136efc2557..c6a11e1c5e2 100644 --- a/src/Bicep.Core/Emit/ResourceDependencyVisitor.cs +++ b/src/Bicep.Core/Emit/ResourceDependencyVisitor.cs @@ -145,7 +145,7 @@ private IEnumerable GetResourceDependencies(DeclaredSymbol d if (!resourceDependencies.TryGetValue(declaredSymbol, out dependencies)) { - return Enumerable.Empty(); + return []; } } diff --git a/src/Bicep.Core/Emit/ScopeHelper.cs b/src/Bicep.Core/Emit/ScopeHelper.cs index d25c58bfe7e..85751dd6f54 100644 --- a/src/Bicep.Core/Emit/ScopeHelper.cs +++ b/src/Bicep.Core/Emit/ScopeHelper.cs @@ -199,7 +199,7 @@ public static LanguageExpression FormatFullyQualifiedResourceId(EmitterContext c arguments.Add(new JTokenExpression(fullyQualifiedType)); arguments.AddRange(nameSegments); - return new FunctionExpression("subscriptionResourceId", arguments.ToArray(), Array.Empty()); + return new FunctionExpression("subscriptionResourceId", [.. arguments], []); case ResourceScope.ResourceGroup: // We avoid using the 'resourceId' function at all here, because its behavior differs depending on the scope that it is called FROM. LanguageExpression scope; @@ -211,7 +211,7 @@ public static LanguageExpression FormatFullyQualifiedResourceId(EmitterContext c } else { - var subscriptionId = new FunctionExpression("subscription", Array.Empty(), new LanguageExpression[] { new JTokenExpression("subscriptionId") }); + var subscriptionId = new FunctionExpression("subscription", [], [new JTokenExpression("subscriptionId")]); var resourceGroup = converter.ConvertExpression(scopeData.ResourceGroupProperty); scope = ExpressionConverter.GenerateResourceGroupScope(subscriptionId, resourceGroup); } diff --git a/src/Bicep.Core/Emit/TemplateEmitter.cs b/src/Bicep.Core/Emit/TemplateEmitter.cs index 8080a93cdbe..9fd7ca032be 100644 --- a/src/Bicep.Core/Emit/TemplateEmitter.cs +++ b/src/Bicep.Core/Emit/TemplateEmitter.cs @@ -124,7 +124,7 @@ private EmitResult EmitOrFail(Func write) var diagnostics = model switch { SemanticModel x => x.GetAllDiagnostics(), - _ => ImmutableArray.Empty, + _ => [], }; if (diagnostics.Any(d => d.Level == DiagnosticLevel.Error)) diff --git a/src/Bicep.Core/Emit/TemplateWriter.cs b/src/Bicep.Core/Emit/TemplateWriter.cs index 7c93bb23a9f..b445b5b3315 100644 --- a/src/Bicep.Core/Emit/TemplateWriter.cs +++ b/src/Bicep.Core/Emit/TemplateWriter.cs @@ -462,7 +462,7 @@ ImmutableArray SegmentsForVariant(string discriminatorValue) private record ResourceDerivedTypeResolution(ResourceTypeReference RootResourceTypeReference, ImmutableArray PointerSegments, TypeSymbol DerivedType) : ITypeReferenceExpressionResolution { internal ResourceDerivedTypeResolution(ResourceDerivedTypeExpression expression) - : this(expression.RootResourceType.TypeReference, ImmutableArray.Empty, expression.RootResourceType.Body.Type) { } + : this(expression.RootResourceType.TypeReference, [], expression.RootResourceType.Body.Type) { } public ObjectExpression GetTypePropertiesForResolvedReferenceExpression(SyntaxBase? sourceSyntax) => ExpressionFactory.CreateObject(new[] @@ -495,7 +495,7 @@ public ObjectExpression GetTypePropertiesForResolvedReferenceExpression(SyntaxBa } private ResolvedInternalReference ForNamedRoot(string rootName) - => new(ImmutableArray.Create(TypeDefinitionsProperty, rootName), declaredTypesByName[rootName].Value); + => new([TypeDefinitionsProperty, rootName], declaredTypesByName[rootName].Value); private ITypeReferenceExpressionResolution ResolveTypeReferenceExpression(TypeExpression expression) { @@ -1308,7 +1308,7 @@ private void EmitModule(PositionTrackingJsonTextWriter jsonWriter, DeclaredModul // the deployment() object at resource group scope does not contain a property named 'location', so we have to use resourceGroup().location emitter.EmitProperty("location", new PropertyAccessExpression( null, - new FunctionCallExpression(null, "resourceGroup", ImmutableArray.Empty), + new FunctionCallExpression(null, "resourceGroup", []), "location", AccessExpressionFlags.None)); } @@ -1317,7 +1317,7 @@ private void EmitModule(PositionTrackingJsonTextWriter jsonWriter, DeclaredModul // at all other scopes we can just use deployment().location emitter.EmitProperty("location", new PropertyAccessExpression( null, - new FunctionCallExpression(null, "deployment", ImmutableArray.Empty), + new FunctionCallExpression(null, "deployment", []), "location", AccessExpressionFlags.None)); } diff --git a/src/Bicep.Core/Extensions/JsonNodeExtensions.cs b/src/Bicep.Core/Extensions/JsonNodeExtensions.cs index fddd6aa5a5a..9868804ec49 100644 --- a/src/Bicep.Core/Extensions/JsonNodeExtensions.cs +++ b/src/Bicep.Core/Extensions/JsonNodeExtensions.cs @@ -23,7 +23,7 @@ public static IEnumerable Select(this JsonNode node, string jsonPathQu return result.Matches.Select(x => x.Value).OfType(); } - return Enumerable.Empty(); + return []; } } diff --git a/src/Bicep.Core/FileSystem/FileResolver.cs b/src/Bicep.Core/FileSystem/FileResolver.cs index 8e09298a2ea..89dee893a20 100644 --- a/src/Bicep.Core/FileSystem/FileResolver.cs +++ b/src/Bicep.Core/FileSystem/FileResolver.cs @@ -120,7 +120,7 @@ public IEnumerable GetDirectories(Uri fileUri, string pattern) { if (!fileUri.IsFile) { - return Enumerable.Empty(); + return []; } return fileSystem.Directory.GetDirectories(fileUri.LocalPath, pattern).Select(s => new Uri(s + "/")); } @@ -129,7 +129,7 @@ public IEnumerable GetFiles(Uri fileUri, string pattern) { if (!fileUri.IsFile) { - return Enumerable.Empty(); + return []; } return fileSystem.Directory.GetFiles(fileUri.LocalPath, pattern).Select(s => new Uri(s)); } diff --git a/src/Bicep.Core/Intermediate/ExpressionBuilder.cs b/src/Bicep.Core/Intermediate/ExpressionBuilder.cs index f71af1988f9..257b661f890 100644 --- a/src/Bicep.Core/Intermediate/ExpressionBuilder.cs +++ b/src/Bicep.Core/Intermediate/ExpressionBuilder.cs @@ -22,23 +22,23 @@ namespace Bicep.Core.Intermediate; public class ExpressionBuilder { - private static readonly ImmutableHashSet NonAzResourcePropertiesToOmit = new[] { + private static readonly ImmutableHashSet NonAzResourcePropertiesToOmit = [ LanguageConstants.ResourceDependsOnPropertyName, - }.ToImmutableHashSet(); + ]; - private static readonly ImmutableHashSet AzResourcePropertiesToOmit = new[] { + private static readonly ImmutableHashSet AzResourcePropertiesToOmit = [ AzResourceTypeProvider.ResourceNamePropertyName, LanguageConstants.ResourceScopePropertyName, LanguageConstants.ResourceParentPropertyName, LanguageConstants.ResourceDependsOnPropertyName, - }.ToImmutableHashSet(); + ]; - private static readonly ImmutableHashSet ModulePropertiesToOmit = new[] { + private static readonly ImmutableHashSet ModulePropertiesToOmit = [ AzResourceTypeProvider.ResourceNamePropertyName, LanguageConstants.ModuleParamsPropertyName, LanguageConstants.ResourceScopePropertyName, LanguageConstants.ResourceDependsOnPropertyName, - }.ToImmutableHashSet(); + ]; private static readonly int MaxCopyIndexStringLength = LanguageConstants.MaxResourceCopyIndexValue.ToString().Length; @@ -289,7 +289,7 @@ UnionTypeSyntax unionTypeSyntax when Context.SemanticModel.GetTypeInfo(unionType UnionType unionType => new UnionTypeExpression(syntax, unionType, ImmutableArray.CreateRange(unionTypeSyntax.Members.Select(m => ConvertTypeWithoutLowering(m.Value)))), // If a union type expression's members all refer to the same literal value, the type of the expression will be a single literal rather than a union TypeSymbol otherwise => new UnionTypeExpression(syntax, - new UnionType(string.Empty, ImmutableArray.Create(otherwise)), + new UnionType(string.Empty, [otherwise]), ImmutableArray.CreateRange(unionTypeSyntax.Members.Select(m => ConvertTypeWithoutLowering(m.Value)))), }, ParenthesizedTypeSyntax parenthesizedExpression => ConvertTypeWithoutLowering(parenthesizedExpression.Expression), @@ -749,7 +749,7 @@ void completePreviousChunk() { if (currentChunk.Count > 0) { - chunks.Add(new ArrayExpression(array, currentChunk.ToImmutableArray())); + chunks.Add(new ArrayExpression(array, [.. currentChunk])); currentChunk.Clear(); } } @@ -774,7 +774,7 @@ void completePreviousChunk() 0 => new ArrayExpression(array, []), // preserve [ ...[ bar ] ] rather than converting it to [ foo: bar ] 1 when !hasSpread => chunks[0], - _ => new FunctionCallExpression(array, "flatten", [new ArrayExpression(array, chunks.ToImmutableArray())]), + _ => new FunctionCallExpression(array, "flatten", [new ArrayExpression(array, [.. chunks])]), }; } @@ -787,7 +787,7 @@ void completePreviousChunk() { if (currentChunk.Count > 0) { - chunks.Add(new ObjectExpression(@object, currentChunk.ToImmutableArray())); + chunks.Add(new ObjectExpression(@object, [.. currentChunk])); currentChunk.Clear(); } } @@ -812,7 +812,7 @@ void completePreviousChunk() 0 => new ObjectExpression(@object, []), // preserve { ...{ foo: bar } } rather than converting it to { foo: bar } 1 when !hasSpread => chunks[0], - _ => new FunctionCallExpression(@object, "shallowMerge", [new ArrayExpression(@object, chunks.ToImmutableArray())]), + _ => new FunctionCallExpression(@object, "shallowMerge", [new ArrayExpression(@object, [.. chunks])]), }; } @@ -861,13 +861,13 @@ private Expression ConvertFunctionDirect(FunctionCallSyntaxBase functionCall) return new FunctionCallExpression( method, "invokeResourceMethod", - new Expression[] { + [ nameExpression, new StringLiteralExpression(method.Name, method.Name.IdentifierName), new ArrayExpression( method, method.Arguments.Select(a => ConvertWithoutLowering(a.Expression)).ToImmutableArray()), - }.ToImmutableArray()); + ]); } var indexContext = resource switch @@ -972,12 +972,12 @@ private Expression ConvertArrayAccess(ArrayAccessSyntax arrayAccess) { if (convertedBase is AccessExpression baseAccess) { - return new AccessChainExpression(arrayAccess, baseAccess, ImmutableArray.Create(convertedIndex)); + return new AccessChainExpression(arrayAccess, baseAccess, [convertedIndex]); } if (convertedBase is AccessChainExpression accessChain) { - return new AccessChainExpression(arrayAccess, accessChain.FirstLink, accessChain.AdditionalProperties.Append(convertedIndex).ToImmutableArray()); + return new AccessChainExpression(arrayAccess, accessChain.FirstLink, [.. accessChain.AdditionalProperties, convertedIndex]); } } @@ -1067,12 +1067,12 @@ moduleCollectionOutputs.BaseExpression is ArrayAccessSyntax moduleArrayAccess && if (convertedBase is AccessExpression baseAccess) { - return new AccessChainExpression(propertyAccess, baseAccess, ImmutableArray.Create(nextLink)); + return new AccessChainExpression(propertyAccess, baseAccess, [nextLink]); } if (convertedBase is AccessChainExpression accessChain) { - return new AccessChainExpression(propertyAccess, accessChain.FirstLink, accessChain.AdditionalProperties.Append(nextLink).ToImmutableArray()); + return new AccessChainExpression(propertyAccess, accessChain.FirstLink, [.. accessChain.AdditionalProperties, nextLink]); } } @@ -1520,7 +1520,7 @@ private void EmitResourceOrModuleScopeProperties(ScopeData scopeData, Expression else if (Context.SemanticModel.TargetScope == ResourceScope.ResourceGroup) { // TODO: It's very suspicious that this doesn't reference scopeData.IndexExpression - expressionEmitter.EmitProperty("subscriptionId", new FunctionExpression("subscription", Array.Empty(), new LanguageExpression[] { new JTokenExpression("subscriptionId") })); + expressionEmitter.EmitProperty("subscriptionId", new FunctionExpression("subscription", [], [new JTokenExpression("subscriptionId")])); } return; case ResourceScope.ResourceGroup: diff --git a/src/Bicep.Core/Intermediate/ExpressionExtensions.cs b/src/Bicep.Core/Intermediate/ExpressionExtensions.cs index 0490c949439..123fac32c89 100644 --- a/src/Bicep.Core/Intermediate/ExpressionExtensions.cs +++ b/src/Bicep.Core/Intermediate/ExpressionExtensions.cs @@ -19,7 +19,7 @@ public static bool HasKeyText(this ObjectPropertyExpression property, string key public static ObjectExpression MergeProperty(this ObjectExpression? expression, string propertyName, Expression propertyValue) { - expression ??= new ObjectExpression(null, ImmutableArray.Empty); + expression ??= new ObjectExpression(null, []); var properties = expression.Properties.ToList(); int matchingIndex = 0; @@ -54,7 +54,7 @@ public static ObjectExpression MergeProperty(this ObjectExpression? expression, propertyValue)); } - return new ObjectExpression(expression.SourceSyntax, properties.ToImmutableArray()); + return new ObjectExpression(expression.SourceSyntax, [.. properties]); } public static ObjectExpression DeepMerge(this ObjectExpression sourceObject, ObjectExpression targetObject) diff --git a/src/Bicep.Core/LanguageConstants.cs b/src/Bicep.Core/LanguageConstants.cs index 7cddbec6c74..5a342102e44 100644 --- a/src/Bicep.Core/LanguageConstants.cs +++ b/src/Bicep.Core/LanguageConstants.cs @@ -194,7 +194,7 @@ public static class LanguageConstants public const string AnyFunction = "any"; public static readonly TypeSymbol Any = new AnyType(); - public static readonly TypeSymbol Never = new UnionType("never", ImmutableArray.Empty); + public static readonly TypeSymbol Never = new UnionType("never", []); public static readonly TypeSymbol ResourceRef = CreateResourceScopeReference(ResourceScope.Module | ResourceScope.Resource); @@ -212,8 +212,8 @@ public static class LanguageConstants public static readonly TypeSymbol LooseString = TypeFactory.CreateStringType(validationFlags: TypeSymbolValidationFlags.AllowLooseAssignment); // SecureString should be regarded as equal to the 'string' type, but with different validation behavior public static readonly TypeSymbol SecureString = TypeFactory.CreateStringType(validationFlags: TypeSymbolValidationFlags.AllowLooseAssignment | TypeSymbolValidationFlags.IsSecure); - public static readonly TypeSymbol Object = new ObjectType(ObjectType, TypeSymbolValidationFlags.Default, Enumerable.Empty(), LanguageConstants.Any); - public static readonly TypeSymbol SecureObject = new ObjectType(ObjectType, TypeSymbolValidationFlags.Default | TypeSymbolValidationFlags.IsSecure, Enumerable.Empty(), LanguageConstants.Any); + public static readonly TypeSymbol Object = new ObjectType(ObjectType, TypeSymbolValidationFlags.Default, [], LanguageConstants.Any); + public static readonly TypeSymbol SecureObject = new ObjectType(ObjectType, TypeSymbolValidationFlags.Default | TypeSymbolValidationFlags.IsSecure, [], LanguageConstants.Any); public static readonly TypeSymbol Int = TypeFactory.CreateIntegerType(); // LooseInt should be regarded as equal to the 'int' type, but with different validation behavior public static readonly TypeSymbol LooseInt = TypeFactory.CreateIntegerType(validationFlags: TypeSymbolValidationFlags.AllowLooseAssignment); @@ -251,7 +251,7 @@ public static class LanguageConstants public static readonly ImmutableHashSet ReservedTypeNames = ImmutableHashSet.Create(IdentifierComparer, ResourceKeyword); - public static readonly ImmutableArray DiscriminatorPreferenceOrder = ImmutableArray.Create("type", "kind"); + public static readonly ImmutableArray DiscriminatorPreferenceOrder = ["type", "kind"]; private static IEnumerable CreateParameterModifierMetadataProperties() { diff --git a/src/Bicep.Core/Modules/LocalModuleReference.cs b/src/Bicep.Core/Modules/LocalModuleReference.cs index ae34b3639d4..664fdeeb61c 100644 --- a/src/Bicep.Core/Modules/LocalModuleReference.cs +++ b/src/Bicep.Core/Modules/LocalModuleReference.cs @@ -92,8 +92,8 @@ public static ResultWithDiagnostic Validate(string pathName) return new(true); } - private static readonly ImmutableHashSet forbiddenPathChars = "<>:\"\\|?*".ToImmutableHashSet(); - private static readonly ImmutableHashSet forbiddenPathTerminatorChars = " .".ToImmutableHashSet(); + private static readonly ImmutableHashSet forbiddenPathChars = [.. "<>:\"\\|?*"]; + private static readonly ImmutableHashSet forbiddenPathTerminatorChars = [.. " ."]; private static bool IsInvalidPathControlCharacter(char pathChar) { diff --git a/src/Bicep.Core/Parsing/BaseParser.cs b/src/Bicep.Core/Parsing/BaseParser.cs index 244f1e46f85..b4da42773cb 100644 --- a/src/Bicep.Core/Parsing/BaseParser.cs +++ b/src/Bicep.Core/Parsing/BaseParser.cs @@ -154,7 +154,7 @@ public SyntaxBase Expression(ExpressionFlags expressionFlags) var newlinesBeforeQuestion = this.reader.Peek(skipNewlines: true).IsOf(TokenType.Question) ? this.NewLines().ToImmutableArray() - : ImmutableArray.Empty; + : []; if (this.Check(TokenType.Question)) { @@ -172,7 +172,7 @@ public SyntaxBase Expression(ExpressionFlags expressionFlags) var newlinesBeforeColon = !trueExpression.IsSkipped && this.reader.Peek(skipNewlines: true).IsOf(TokenType.Colon) ? this.NewLines().ToImmutableArray() - : ImmutableArray.Empty; + : []; var colon = this.WithRecovery( () => this.Expect(TokenType.Colon, b => b.ExpectedCharacter(":")), @@ -350,7 +350,7 @@ protected ForSyntax ForExpression(ExpressionFlags expressionFlags, bool isResour GetSuppressionFlag(colon), TokenType.RightSquare, TokenType.NewLine); var closeNewlines = body.IsSkipped - ? ImmutableArray.Empty + ? [] : this.NewLines().ToImmutableArray(); var closeBracket = this.WithRecovery(() => this.Expect(TokenType.RightSquare, b => b.ExpectedCharacter("]")), GetSuppressionFlag(body), TokenType.RightSquare, TokenType.NewLine); @@ -418,7 +418,7 @@ private SyntaxBase FunctionCallOrVariableAccess(ExpressionFlags expressionFlags) var next = this.reader.Peek(skipNewlines: true); var newlinesBeforeBody = !LanguageConstants.DeclarationKeywords.Contains(next.Text) ? this.NewLines().ToImmutableArray() - : ImmutableArray.Empty; + : []; var expression = this.WithRecovery(() => this.Expression(ExpressionFlags.AllowComplexLiterals), RecoveryFlags.None, TokenType.NewLine, TokenType.RightParen); return new LambdaSyntax(new LocalVariableSyntax(identifier), arrow, newlinesBeforeBody, expression); @@ -661,11 +661,11 @@ protected SyntaxBase IfCondition(ExpressionFlags expressionFlags, bool insideFor var conditionExpression = this.WithRecovery( () => this.ParenthesizedExpression(WithoutExpressionFlag(expressionFlags, ExpressionFlags.AllowResourceDeclarations)), RecoveryFlags.None, - insideForExpression ? new[] { TokenType.RightSquare, TokenType.LeftBrace, TokenType.NewLine } : new[] { TokenType.LeftBrace, TokenType.NewLine }); + insideForExpression ? [TokenType.RightSquare, TokenType.LeftBrace, TokenType.NewLine] : [TokenType.LeftBrace, TokenType.NewLine]); var body = this.WithRecovery( () => this.Object(expressionFlags), GetSuppressionFlag(conditionExpression, conditionExpression is ParenthesizedExpressionSyntax { CloseParen: not SkippedTriviaSyntax }), - insideForExpression ? new[] { TokenType.RightSquare, TokenType.NewLine } : new[] { TokenType.NewLine }); + insideForExpression ? [TokenType.RightSquare, TokenType.NewLine] : [TokenType.NewLine]); return new IfConditionSyntax(keyword, conditionExpression, body); } @@ -1019,7 +1019,7 @@ private SyntaxBase MultilineString() return new SkippedTriviaSyntax(token.Span, token.AsEnumerable()); } - return new StringSyntax(token.AsEnumerable(), Enumerable.Empty(), stringValue.AsEnumerable()); + return new StringSyntax(token.AsEnumerable(), [], stringValue.AsEnumerable()); } protected Token NewLine() @@ -1204,11 +1204,11 @@ private SyntaxBase ParenthesizedExpressionOrLambda(ExpressionFlags expressionFla var next = this.reader.Peek(skipNewlines: true); var newlinesBeforeBody = !LanguageConstants.DeclarationKeywords.Contains(next.Text) ? this.NewLines().ToImmutableArray() - : ImmutableArray.Empty; + : []; var expression = this.WithRecovery(() => this.Expression(ExpressionFlags.AllowComplexLiterals), RecoveryFlags.None, TokenType.NewLine, TokenType.RightParen); var variableBlock = GetVariableBlock(openParen, expressionsOrCommas, closeParen); - return new LambdaSyntax(variableBlock, arrow, newlinesBeforeBody.ToImmutableArray(), expression); + return new LambdaSyntax(variableBlock, arrow, [.. newlinesBeforeBody], expression); } var innerSyntax = GetParenthesizedExpressionInnerContent(openParen, expressionsOrCommas, closeParen); @@ -1232,7 +1232,7 @@ protected SyntaxBase TypedLambda() var next = this.reader.Peek(skipNewlines: true); var newlinesBeforeBody = !arrow.IsSkipped && !LanguageConstants.DeclarationKeywords.Contains(next.Text) ? this.NewLines().ToImmutableArray() - : ImmutableArray.Empty; + : []; var expression = this.WithRecovery(() => this.Expression(ExpressionFlags.AllowComplexLiterals), RecoveryFlags.None, TokenType.NewLine, TokenType.RightParen); var variableBlock = new TypedVariableBlockSyntax(openParen, expressionsOrCommas, closeParen); @@ -1350,7 +1350,7 @@ protected SkippedTriviaSyntax SkipEmpty(DiagnosticBuilder.ErrorBuilderDelegate e private SkippedTriviaSyntax SkipEmpty(int position, DiagnosticBuilder.ErrorBuilderDelegate? errorFunc) { var span = new TextSpan(position, 0); - var errors = errorFunc is null ? Enumerable.Empty() : errorFunc(DiagnosticBuilder.ForPosition(span)).AsEnumerable(); + var errors = errorFunc is null ? [] : errorFunc(DiagnosticBuilder.ForPosition(span)).AsEnumerable(); return new SkippedTriviaSyntax(span, ImmutableArray.Empty, errors); } diff --git a/src/Bicep.Core/Parsing/Lexer.cs b/src/Bicep.Core/Parsing/Lexer.cs index 299732dd302..5936c841293 100644 --- a/src/Bicep.Core/Parsing/Lexer.cs +++ b/src/Bicep.Core/Parsing/Lexer.cs @@ -66,7 +66,7 @@ public void Lex() } } - public ImmutableArray GetTokens() => tokens.ToImmutableArray(); + public ImmutableArray GetTokens() => [.. tokens]; /// /// Converts a set of string literal tokens into their raw values. Returns null if any of the tokens are of the wrong type or malformed. @@ -466,7 +466,7 @@ private DisableNextLineDiagnosticsSyntaxTrivia GetDisableNextLineDiagnosticsSynt if (text.Length > 0) { - return new FreeformToken(TokenType.StringComplete, textWindow.GetSpan(), text.ToString(), Enumerable.Empty(), Enumerable.Empty()); + return new FreeformToken(TokenType.StringComplete, textWindow.GetSpan(), text.ToString(), [], []); } return null; diff --git a/src/Bicep.Core/Parsing/Parser.cs b/src/Bicep.Core/Parsing/Parser.cs index f4bc3244784..05a637e921a 100644 --- a/src/Bicep.Core/Parsing/Parser.cs +++ b/src/Bicep.Core/Parsing/Parser.cs @@ -185,7 +185,7 @@ private SyntaxBase ResourceDeclaration(IEnumerable leadingNodes) var newlines = !assignment.IsSkipped && reader.Peek(skipNewlines: true).IsKeyword(LanguageConstants.IfKeyword) ? this.NewLines().ToImmutableArray() - : ImmutableArray.Empty; + : []; var value = this.WithRecovery(() => { @@ -218,7 +218,7 @@ private SyntaxBase ModuleDeclaration(IEnumerable leadingNodes) var assignment = this.WithRecovery(this.Assignment, GetSuppressionFlag(path), TokenType.LeftBrace, TokenType.NewLine); var newlines = reader.Peek(skipNewlines: true).IsKeyword(LanguageConstants.IfKeyword) ? this.NewLines().ToImmutableArray() - : ImmutableArray.Empty; + : []; var value = this.WithRecovery(() => { diff --git a/src/Bicep.Core/PrettyPrint/DocumentBuildVisitor.cs b/src/Bicep.Core/PrettyPrint/DocumentBuildVisitor.cs index e164f08309b..bdcb4efc9c7 100644 --- a/src/Bicep.Core/PrettyPrint/DocumentBuildVisitor.cs +++ b/src/Bicep.Core/PrettyPrint/DocumentBuildVisitor.cs @@ -27,8 +27,8 @@ public class DocumentBuildVisitor : CstVisitor private static readonly ImmutableDictionary CommonTextCache = LanguageConstants.ContextualKeywords .Concat(LanguageConstants.Keywords.Keys) - .Concat(new[] { "(", ")", "[", "]", "{", "}", "=", ":", "+", "-", "*", "/", "!" }) - .Concat(new[] { "name", "properties", "string", "bool", "int", "array", "object" }) + .Concat(["(", ")", "[", "]", "{", "}", "=", ":", "+", "-", "*", "/", "!"]) + .Concat(["name", "properties", "string", "bool", "int", "array", "object"]) .ToImmutableDictionary(value => value, value => new TextDocument(value)); private readonly Stack documentStack = new(); @@ -351,7 +351,7 @@ private void VisitCommaAndNewLineSeparated(ImmutableArray nodes, boo return children[0]; } - return new NestDocument(1, children.ToImmutableArray()); + return new NestDocument(1, [.. children]); }); return; } @@ -676,7 +676,7 @@ void AggregateCurrentLine() } var line = Spread(currentLineDocs); - this.PushDocument(firstLineWritten ? new NestDocument(1, ImmutableArray.Create(line)) : line); + this.PushDocument(firstLineWritten ? new NestDocument(1, [line]) : line); firstLineWritten = true; stackTare++; } diff --git a/src/Bicep.Core/PrettyPrint/Documents/NestDocument.cs b/src/Bicep.Core/PrettyPrint/Documents/NestDocument.cs index 8f645ab01f2..a54f06b3a05 100644 --- a/src/Bicep.Core/PrettyPrint/Documents/NestDocument.cs +++ b/src/Bicep.Core/PrettyPrint/Documents/NestDocument.cs @@ -13,7 +13,7 @@ public class NestDocument : ILinkedDocument private readonly ImmutableArray successors; public NestDocument(int level) - : this(level, ImmutableArray.Empty) + : this(level, []) { } diff --git a/src/Bicep.Core/PrettyPrint/Documents/TextDocument.cs b/src/Bicep.Core/PrettyPrint/Documents/TextDocument.cs index 5839bd544a6..9081eb07dc2 100644 --- a/src/Bicep.Core/PrettyPrint/Documents/TextDocument.cs +++ b/src/Bicep.Core/PrettyPrint/Documents/TextDocument.cs @@ -14,7 +14,7 @@ public class TextDocument : ILinkedDocument private readonly ImmutableArray successors; public TextDocument(string text) - : this(text, ImmutableArray.Empty) + : this(text, []) { } diff --git a/src/Bicep.Core/PrettyPrintV2/Documents/DocumentOperators.cs b/src/Bicep.Core/PrettyPrintV2/Documents/DocumentOperators.cs index 5b5485bbf0d..3478fcadfef 100644 --- a/src/Bicep.Core/PrettyPrintV2/Documents/DocumentOperators.cs +++ b/src/Bicep.Core/PrettyPrintV2/Documents/DocumentOperators.cs @@ -5,7 +5,7 @@ namespace Bicep.Core.PrettyPrintV2.Documents { public static class DocumentOperators { - public static readonly IEnumerable Empty = Enumerable.Empty(); + public static readonly IEnumerable Empty = []; /// /// Prints a whitespace. diff --git a/src/Bicep.Core/PrettyPrintV2/SyntaxLayouts.SyntaxVisitor.cs b/src/Bicep.Core/PrettyPrintV2/SyntaxLayouts.SyntaxVisitor.cs index 5b5c9025ed7..762c739b707 100644 --- a/src/Bicep.Core/PrettyPrintV2/SyntaxLayouts.SyntaxVisitor.cs +++ b/src/Bicep.Core/PrettyPrintV2/SyntaxLayouts.SyntaxVisitor.cs @@ -15,7 +15,7 @@ private delegate IEnumerable SyntaxLayoutSpecifier(TSyntax sy private readonly PrettyPrinterV2Context context; - private IEnumerable current = Enumerable.Empty(); + private IEnumerable current = []; public SyntaxLayouts(PrettyPrinterV2Context context) { diff --git a/src/Bicep.Core/PrettyPrintV2/SyntaxLayouts.cs b/src/Bicep.Core/PrettyPrintV2/SyntaxLayouts.cs index 8f9c9cf4c94..ad3dbf3e68f 100644 --- a/src/Bicep.Core/PrettyPrintV2/SyntaxLayouts.cs +++ b/src/Bicep.Core/PrettyPrintV2/SyntaxLayouts.cs @@ -551,7 +551,7 @@ public IEnumerable LayoutImportedSymbolsListSyntax(ImportedSymbolsList public IEnumerable LayoutImportedSymbolsListItemSyntax(ImportedSymbolsListItemSyntax syntax) => Spread(syntax.OriginalSymbolName.AsEnumerable() - .Concat(syntax.AsClause is SyntaxBase nonNullAsClause ? nonNullAsClause.AsEnumerable() : Enumerable.Empty())); + .Concat(syntax.AsClause is SyntaxBase nonNullAsClause ? nonNullAsClause.AsEnumerable() : [])); public IEnumerable LayoutWildcardImportSyntax(WildcardImportSyntax syntax) => Spread(syntax.Wildcard, syntax.AliasAsClause); diff --git a/src/Bicep.Core/Registry/ModuleDispatcher.cs b/src/Bicep.Core/Registry/ModuleDispatcher.cs index d8559a3656c..c3ba87a4496 100644 --- a/src/Bicep.Core/Registry/ModuleDispatcher.cs +++ b/src/Bicep.Core/Registry/ModuleDispatcher.cs @@ -37,7 +37,7 @@ private ImmutableDictionary Registries(Uri parentModu => registryProvider.Registries(parentModuleUri).ToImmutableDictionary(r => r.Scheme); public ImmutableArray AvailableSchemes(Uri parentModuleUri) - => Registries(parentModuleUri).Keys.OrderBy(s => s).ToImmutableArray(); + => [.. Registries(parentModuleUri).Keys.OrderBy(s => s)]; public ResultWithDiagnostic TryGetArtifactReference(ArtifactType artifactType, string reference, Uri parentModuleUri) { diff --git a/src/Bicep.Core/Registry/Oci/OciArtifactReference.cs b/src/Bicep.Core/Registry/Oci/OciArtifactReference.cs index 2cb67bf3bca..4812a39db07 100644 --- a/src/Bicep.Core/Registry/Oci/OciArtifactReference.cs +++ b/src/Bicep.Core/Registry/Oci/OciArtifactReference.cs @@ -168,7 +168,7 @@ private static ResultWithDiagnostic TryParseParts(Ar static (int index, char? delimiter) FindLastSegmentDelimiter(string lastSegment) { - char[] delimiters = { ':', '@' }; + char[] delimiters = [':', '@']; int index = lastSegment.IndexOfAny(delimiters); return (index, index == -1 ? null : lastSegment[index]); diff --git a/src/Bicep.Core/Resources/ResourceTypeReference.cs b/src/Bicep.Core/Resources/ResourceTypeReference.cs index b7e21340dcc..c3a6fdb7a33 100644 --- a/src/Bicep.Core/Resources/ResourceTypeReference.cs +++ b/src/Bicep.Core/Resources/ResourceTypeReference.cs @@ -16,7 +16,7 @@ public ResourceTypeReference(string type, string? version) Name = version is null ? type : $"{type}@{version}"; Type = type; - TypeSegments = type.Split('/').ToImmutableArray(); + TypeSegments = [.. type.Split('/')]; ApiVersion = version; } diff --git a/src/Bicep.Core/Semantics/ArmTemplateSemanticModel.cs b/src/Bicep.Core/Semantics/ArmTemplateSemanticModel.cs index 7b0adae5dca..71009fa5926 100644 --- a/src/Bicep.Core/Semantics/ArmTemplateSemanticModel.cs +++ b/src/Bicep.Core/Semantics/ArmTemplateSemanticModel.cs @@ -95,7 +95,7 @@ public ArmTemplateSemanticModel(ArmTemplateFile sourceFile) { if (this.SourceFile.Template?.Outputs is null) { - return ImmutableArray.Empty; + return []; } return this.SourceFile.Template.Outputs diff --git a/src/Bicep.Core/Semantics/AuxiliaryFileCache.cs b/src/Bicep.Core/Semantics/AuxiliaryFileCache.cs index 265bd6007b5..a74f8768799 100644 --- a/src/Bicep.Core/Semantics/AuxiliaryFileCache.cs +++ b/src/Bicep.Core/Semantics/AuxiliaryFileCache.cs @@ -45,7 +45,7 @@ public ResultWithDiagnostic Read(Uri uri) }); public ImmutableArray GetEntries() - => fileCache.Keys.ToImmutableArray(); + => [.. fileCache.Keys]; public void ClearEntries(IEnumerable uris) { diff --git a/src/Bicep.Core/Semantics/Compilation.cs b/src/Bicep.Core/Semantics/Compilation.cs index 39bf34358ed..6ba6900ccaf 100644 --- a/src/Bicep.Core/Semantics/Compilation.cs +++ b/src/Bicep.Core/Semantics/Compilation.cs @@ -88,7 +88,7 @@ public ISemanticModel GetSemanticModel(ISourceFile sourceFile) public ImmutableDictionary> GetAllDiagnosticsByBicepFile() => SourceFileGrouping.SourceFiles.OfType().ToImmutableDictionary( bicepFile => bicepFile, - bicepFile => this.GetSemanticModel(bicepFile) is SemanticModel semanticModel ? semanticModel.GetAllDiagnostics() : ImmutableArray.Empty); + bicepFile => this.GetSemanticModel(bicepFile) is SemanticModel semanticModel ? semanticModel.GetAllDiagnostics() : []); private T GetSemanticModel(ISourceFile sourceFile) where T : class, ISemanticModel => this.GetSemanticModel(sourceFile) as T ?? diff --git a/src/Bicep.Core/Semantics/DeclarationVisitor.cs b/src/Bicep.Core/Semantics/DeclarationVisitor.cs index 0724a7dd33e..d238efc9d11 100644 --- a/src/Bicep.Core/Semantics/DeclarationVisitor.cs +++ b/src/Bicep.Core/Semantics/DeclarationVisitor.cs @@ -295,18 +295,22 @@ public override void VisitCompileTimeImportDeclarationSyntax(CompileTimeImportDe importedOriginalName, item, item.Name, - ImmutableArray.Create(DiagnosticBuilder.ForPosition(item.OriginalSymbolName).ImportedSymbolHasErrors(importedOriginalName, exportMetadata.Description ?? "unknown error"))), + [ + DiagnosticBuilder.ForPosition(item.OriginalSymbolName).ImportedSymbolHasErrors(importedOriginalName, exportMetadata.Description ?? "unknown error"), + ]), _ => new ErroredImportSymbol(context, importedOriginalName, item, item.Name, - ImmutableArray.Create(DiagnosticBuilder.ForPosition(item.OriginalSymbolName).ImportedSymbolHasErrors(importedOriginalName, $"Unsupported export kind: {exportMetadata.Kind}"))), + [ + DiagnosticBuilder.ForPosition(item.OriginalSymbolName).ImportedSymbolHasErrors(importedOriginalName, $"Unsupported export kind: {exportMetadata.Kind}"), + ]), }, false => new ErroredImportSymbol(context, importedOriginalName, item, item.Name, - ImmutableArray.Create(DiagnosticBuilder.ForPosition(item.OriginalSymbolName).ImportedSymbolNotFound(importedOriginalName))), + [DiagnosticBuilder.ForPosition(item.OriginalSymbolName).ImportedSymbolNotFound(importedOriginalName)]), }); } break; @@ -317,7 +321,7 @@ public override void VisitCompileTimeImportDeclarationSyntax(CompileTimeImportDe switch (syntax.ImportExpression) { case WildcardImportSyntax wildcardImport: - DeclareSymbol(new ErroredImportSymbol(context, wildcardImport.Name.IdentifierName, wildcardImport, wildcardImport.Name, ImmutableArray.Create(modelLoadError))); + DeclareSymbol(new ErroredImportSymbol(context, wildcardImport.Name.IdentifierName, wildcardImport, wildcardImport.Name, [modelLoadError])); break; case ImportedSymbolsListSyntax importedSymbolsList: var loadErrorRecorded = false; @@ -330,7 +334,7 @@ public override void VisitCompileTimeImportDeclarationSyntax(CompileTimeImportDe } // only include the load error once per import statement - var errors = loadErrorRecorded ? ImmutableArray.Empty : ImmutableArray.Create(modelLoadError); + var errors = loadErrorRecorded ? [] : ImmutableArray.Create(modelLoadError); DeclareSymbol(new ErroredImportSymbol(context, importedOriginalName, item, item.Name, errors)); } break; diff --git a/src/Bicep.Core/Semantics/DeclaredFunctionSymbol.cs b/src/Bicep.Core/Semantics/DeclaredFunctionSymbol.cs index 4286ee24b2a..8eaecd55982 100644 --- a/src/Bicep.Core/Semantics/DeclaredFunctionSymbol.cs +++ b/src/Bicep.Core/Semantics/DeclaredFunctionSymbol.cs @@ -28,7 +28,7 @@ public DeclaredFunctionSymbol(ISymbolContext context, string name, FunctionDecla // Unlike functions defined in the ARM engine, user-defined functions do not support multiple dispatch and will always have exactly one overload. public FunctionOverload Overload => overloadLazy.Value; - public ImmutableArray Overloads => ImmutableArray.Create(Overload); + public ImmutableArray Overloads => [Overload]; public FunctionFlags FunctionFlags => FunctionFlags.Default; diff --git a/src/Bicep.Core/Semantics/FunctionOverload.cs b/src/Bicep.Core/Semantics/FunctionOverload.cs index 46da8a2e499..ede8d92125f 100644 --- a/src/Bicep.Core/Semantics/FunctionOverload.cs +++ b/src/Bicep.Core/Semantics/FunctionOverload.cs @@ -65,7 +65,7 @@ public FunctionOverload(string name, string genericDescription, string descripti public IEnumerable ParameterTypeSignatures => this.FixedParameters .Select(fp => fp.Signature) - .Concat(this.VariableParameter?.GenericSignature.AsEnumerable() ?? Enumerable.Empty()); + .Concat(this.VariableParameter?.GenericSignature.AsEnumerable() ?? []); public bool HasParameters => this.MinimumArgumentCount > 0 || this.MaximumArgumentCount > 0; diff --git a/src/Bicep.Core/Semantics/ISemanticModelLookup.cs b/src/Bicep.Core/Semantics/ISemanticModelLookup.cs index 4903ec7715c..f01a7860faf 100644 --- a/src/Bicep.Core/Semantics/ISemanticModelLookup.cs +++ b/src/Bicep.Core/Semantics/ISemanticModelLookup.cs @@ -11,7 +11,7 @@ public interface ISemanticModelLookup ISemanticModel GetSemanticModel(ISourceFile sourceFile); static ISemanticModelLookup Excluding(ISemanticModelLookup inner, params ISourceFile[] toExcludeFromLookup) => toExcludeFromLookup.Length > 0 - ? new ExcludingSemanticModelLookupDecorator(inner, toExcludeFromLookup.ToImmutableHashSet()) + ? new ExcludingSemanticModelLookupDecorator(inner, [.. toExcludeFromLookup]) : inner; private class ExcludingSemanticModelLookupDecorator : ISemanticModelLookup diff --git a/src/Bicep.Core/Semantics/ImportedFunctionSymbol.cs b/src/Bicep.Core/Semantics/ImportedFunctionSymbol.cs index 632f1369d0b..59b0449a8f7 100644 --- a/src/Bicep.Core/Semantics/ImportedFunctionSymbol.cs +++ b/src/Bicep.Core/Semantics/ImportedFunctionSymbol.cs @@ -21,7 +21,7 @@ public ImportedFunctionSymbol(ISymbolContext context, ImportedSymbolsListItemSyn public FunctionOverload Overload => overloadLazy.Value; - public ImmutableArray Overloads => ImmutableArray.Create(Overload); + public ImmutableArray Overloads => [Overload]; public FunctionFlags FunctionFlags => FunctionFlags.Default; diff --git a/src/Bicep.Core/Semantics/NameBindingVisitor.cs b/src/Bicep.Core/Semantics/NameBindingVisitor.cs index 90aa8c810c6..2dfbb4d337e 100644 --- a/src/Bicep.Core/Semantics/NameBindingVisitor.cs +++ b/src/Bicep.Core/Semantics/NameBindingVisitor.cs @@ -41,7 +41,7 @@ public static ImmutableDictionary GetBindings( { // bind identifiers to declarations var bindings = new Dictionary(); - var allLocalScopes = ScopeCollectorVisitor.Build(ImmutableArray.Create(fileScope)); + var allLocalScopes = ScopeCollectorVisitor.Build([fileScope]); var binder = new NameBindingVisitor(bindings, namespaceResolver, allLocalScopes); binder.Visit(programSyntax); diff --git a/src/Bicep.Core/Semantics/Namespaces/AzNamespaceType.cs b/src/Bicep.Core/Semantics/Namespaces/AzNamespaceType.cs index ee2fa5aa5e5..250530ef9f5 100644 --- a/src/Bicep.Core/Semantics/Namespaces/AzNamespaceType.cs +++ b/src/Bicep.Core/Semantics/Namespaces/AzNamespaceType.cs @@ -52,18 +52,18 @@ private static FunctionOverload.ResultBuilderDelegate AddDiagnosticsAndReturnRes private static FunctionResult GetRestrictedResourceGroupReturnResult(SemanticModel model, IDiagnosticWriter diagnostics, FunctionCallSyntaxBase functionCall, ImmutableArray argumentTypes) => new( - new ResourceGroupScopeType(functionCall.Arguments, Enumerable.Empty()), - new ObjectExpression(functionCall, ImmutableArray.Empty)); + new ResourceGroupScopeType(functionCall.Arguments, []), + new ObjectExpression(functionCall, [])); private static FunctionResult GetRestrictedSubscriptionReturnResult(SemanticModel model, IDiagnosticWriter diagnostics, FunctionCallSyntaxBase functionCall, ImmutableArray argumentTypes) => new( - new SubscriptionScopeType(functionCall.Arguments, Enumerable.Empty()), - new ObjectExpression(functionCall, ImmutableArray.Empty)); + new SubscriptionScopeType(functionCall.Arguments, []), + new ObjectExpression(functionCall, [])); private static FunctionResult GetRestrictedManagementGroupReturnResult(SemanticModel model, IDiagnosticWriter diagnostics, FunctionCallSyntaxBase functionCall, ImmutableArray argumentTypes) => new( - new ManagementGroupScopeType(functionCall.Arguments, Enumerable.Empty()), - new ObjectExpression(functionCall, ImmutableArray.Empty)); + new ManagementGroupScopeType(functionCall.Arguments, []), + new ObjectExpression(functionCall, [])); private static FunctionResult GetTenantReturnResult(SemanticModel model, IDiagnosticWriter diagnostics, FunctionCallSyntaxBase functionCall, ImmutableArray argumentTypes) => new(new TenantScopeType(functionCall.Arguments, new[] @@ -236,7 +236,7 @@ private static ObjectType GetDeploymentReturnType(bool resourceGroupScope) yield return ( new FunctionOverloadBuilder("tenant") - .WithReturnResultBuilder(GetTenantReturnResult, new TenantScopeType(Enumerable.Empty(), Enumerable.Empty())) + .WithReturnResultBuilder(GetTenantReturnResult, new TenantScopeType([], [])) .WithGenericDescription("Returns the current tenant scope.") .Build(), ResourceScope.Tenant | ResourceScope.ManagementGroup | ResourceScope.Subscription | ResourceScope.ResourceGroup); @@ -244,14 +244,14 @@ private static ObjectType GetDeploymentReturnType(bool resourceGroupScope) const string managementGroupGenericDescription = "Returns a management group scope."; yield return ( new FunctionOverloadBuilder("managementGroup") - .WithReturnResultBuilder(GetManagementGroupReturnResult, new ManagementGroupScopeType(Enumerable.Empty(), Enumerable.Empty())) + .WithReturnResultBuilder(GetManagementGroupReturnResult, new ManagementGroupScopeType([], [])) .WithGenericDescription(managementGroupGenericDescription) .WithDescription("Returns the current management group scope.") .Build(), ResourceScope.ManagementGroup); yield return ( new FunctionOverloadBuilder("managementGroup") - .WithReturnResultBuilder(GetRestrictedManagementGroupReturnResult, new ManagementGroupScopeType(Enumerable.Empty(), Enumerable.Empty())) + .WithReturnResultBuilder(GetRestrictedManagementGroupReturnResult, new ManagementGroupScopeType([], [])) .WithGenericDescription(managementGroupGenericDescription) .WithDescription("Returns the scope for a named management group.") .WithRequiredParameter("name", LanguageConstants.String, "The unique identifier of the management group (not the display name).") @@ -261,14 +261,14 @@ private static ObjectType GetDeploymentReturnType(bool resourceGroupScope) const string subscriptionGenericDescription = "Returns a subscription scope."; yield return ( new FunctionOverloadBuilder("subscription") - .WithReturnResultBuilder(GetSubscriptionReturnResult, new SubscriptionScopeType(Enumerable.Empty(), Enumerable.Empty())) + .WithReturnResultBuilder(GetSubscriptionReturnResult, new SubscriptionScopeType([], [])) .WithGenericDescription(subscriptionGenericDescription) .WithDescription("Returns the subscription scope for the current deployment.") .Build(), ResourceScope.Subscription | ResourceScope.ResourceGroup); yield return ( new FunctionOverloadBuilder("subscription") - .WithReturnResultBuilder(GetRestrictedSubscriptionReturnResult, new SubscriptionScopeType(Enumerable.Empty(), Enumerable.Empty())) + .WithReturnResultBuilder(GetRestrictedSubscriptionReturnResult, new SubscriptionScopeType([], [])) .WithGenericDescription(subscriptionGenericDescription) .WithDescription("Returns a named subscription scope.") .WithRequiredParameter("subscriptionId", LanguageConstants.String, "The subscription ID") @@ -278,14 +278,14 @@ private static ObjectType GetDeploymentReturnType(bool resourceGroupScope) const string resourceGroupGenericDescription = "Returns a resource group scope."; yield return ( new FunctionOverloadBuilder("resourceGroup") - .WithReturnResultBuilder(GetResourceGroupReturnResult, new ResourceGroupScopeType(Enumerable.Empty(), Enumerable.Empty())) + .WithReturnResultBuilder(GetResourceGroupReturnResult, new ResourceGroupScopeType([], [])) .WithGenericDescription(resourceGroupGenericDescription) .WithDescription("Returns the current resource group scope.") .Build(), ResourceScope.ResourceGroup); yield return ( new FunctionOverloadBuilder("resourceGroup") - .WithReturnResultBuilder(GetRestrictedResourceGroupReturnResult, new ResourceGroupScopeType(Enumerable.Empty(), Enumerable.Empty())) + .WithReturnResultBuilder(GetRestrictedResourceGroupReturnResult, new ResourceGroupScopeType([], [])) .WithGenericDescription(resourceGroupGenericDescription) .WithDescription("Returns a named resource group scope") .WithRequiredParameter("resourceGroupName", LanguageConstants.String, "The resource group name") @@ -293,7 +293,7 @@ private static ObjectType GetDeploymentReturnType(bool resourceGroupScope) ResourceScope.Subscription | ResourceScope.ResourceGroup); yield return ( new FunctionOverloadBuilder("resourceGroup") - .WithReturnResultBuilder(GetRestrictedResourceGroupReturnResult, new ResourceGroupScopeType(Enumerable.Empty(), Enumerable.Empty())) + .WithReturnResultBuilder(GetRestrictedResourceGroupReturnResult, new ResourceGroupScopeType([], [])) .WithGenericDescription(resourceGroupGenericDescription) .WithDescription("Returns a named resource group scope.") .WithRequiredParameter("subscriptionId", LanguageConstants.String, "The subscription ID") diff --git a/src/Bicep.Core/Semantics/Namespaces/NamespaceResolver.cs b/src/Bicep.Core/Semantics/Namespaces/NamespaceResolver.cs index f18be272278..58ab5fbae84 100644 --- a/src/Bicep.Core/Semantics/Namespaces/NamespaceResolver.cs +++ b/src/Bicep.Core/Semantics/Namespaces/NamespaceResolver.cs @@ -120,7 +120,7 @@ public ImmutableArray GetMatchingResourceTypes(ResourceTypeReferen public IEnumerable GetAvailableAzureResourceTypes() => namespaceTypes.Values.SingleOrDefault(x => x.Name.Equals(AzNamespaceType.BuiltInName, StringComparison.Ordinal))?.ResourceTypeProvider.GetAvailableTypes() ?? - Enumerable.Empty(); + []; public ILookup> GetGroupedResourceTypes() { diff --git a/src/Bicep.Core/Semantics/Namespaces/SystemNamespaceType.cs b/src/Bicep.Core/Semantics/Namespaces/SystemNamespaceType.cs index c43c11f331d..e697008c944 100644 --- a/src/Bicep.Core/Semantics/Namespaces/SystemNamespaceType.cs +++ b/src/Bicep.Core/Semantics/Namespaces/SystemNamespaceType.cs @@ -5,12 +5,12 @@ using System.Globalization; using System.Numerics; using System.Text; +using Bicep.Core.Analyzers.Linter; using Bicep.Core.Diagnostics; using Bicep.Core.Extensions; using Bicep.Core.Features; using Bicep.Core.FileSystem; using Bicep.Core.Intermediate; -using Bicep.Core.Analyzers.Linter; using Bicep.Core.Modules; using Bicep.Core.Navigation; using Bicep.Core.Parsing; @@ -429,7 +429,7 @@ static int MinLength(ObjectType @object) => return new(argumentTypes[0] switch { TupleType tupleType when minToTake == maxToTake && minToTake >= tupleType.Items.Length => tupleType, - TupleType tupleType when minToTake == maxToTake && minToTake <= 0 => new TupleType(ImmutableArray.Empty, tupleType.ValidationFlags), + TupleType tupleType when minToTake == maxToTake && minToTake <= 0 => new TupleType([], tupleType.ValidationFlags), TupleType tupleType when minToTake == maxToTake && minToTake <= int.MaxValue => new TupleType(tupleType.Items.Take((int)minToTake).ToImmutableArray(), tupleType.ValidationFlags), ArrayType array => TypeFactory.CreateArrayType(array.Item, !array.MinLength.HasValue ? null : minToTake switch @@ -1175,7 +1175,7 @@ private static FunctionResult LoadContentResultBuilder(ObjectParser objectParser { var arguments = functionCall.Arguments.ToImmutableArray(); string? tokenSelectorPath = null; - IPositionable[] positionables = arguments.Length > 1 ? new IPositionable[] { arguments[0], arguments[1] } : new IPositionable[] { arguments[0] }; + IPositionable[] positionables = arguments.Length > 1 ? [arguments[0], arguments[1]] : [arguments[0]]; if (arguments.Length > 1) { if (argumentTypes[1] is not StringLiteralType tokenSelectorType) @@ -1222,24 +1222,25 @@ private static FunctionResult ReadEnvironmentVariableResultBuilder(SemanticModel suggestion = $" Did you mean \"{suggestion}\"?"; } //log available environment variables if verbose logging is enabled - if (model.Configuration.Analyzers.GetValue(LinterAnalyzer.LinterEnabledSetting, false) && model.Configuration.Analyzers.GetValue(LinterAnalyzer.LinterVerboseSetting, false)) { + if (model.Configuration.Analyzers.GetValue(LinterAnalyzer.LinterEnabledSetting, false) && model.Configuration.Analyzers.GetValue(LinterAnalyzer.LinterVerboseSetting, false)) + { diagnostics.Write( new Diagnostic( arguments[0].Span, DiagnosticLevel.Info, "Bicepparam ReadEnvironmentVariable function", - $"Available environment variables are: { string.Join(", ", envVariableNames) }", + $"Available environment variables are: {string.Join(", ", envVariableNames)}", null) - ); + ); } - + //error to fail the build-param with clear message of the missing env var name var paramAssignmentDefinition = model.Root.ParameterAssignments.Where( p => p.DeclaringParameterAssignment.Value.Span.Position == functionCall.Span.Position ).FirstOrDefault(); var paramName = paramAssignmentDefinition?.Name ?? ""; return new(ErrorType.Create(DiagnosticBuilder.ForPosition(arguments[0]).FailedToEvaluateParameter(paramName, - $"Environment variable \"{envVariableName}\" does not exist, and no default value set.{ suggestion }"))); + $"Environment variable \"{envVariableName}\" does not exist, and no default value set.{suggestion}"))); } } return new(TypeFactory.CreateStringLiteralType(envVariableValue), @@ -1330,7 +1331,7 @@ private static FunctionResult LoadContentAsBase64ResultBuilder(SemanticModel mod return new(ErrorType.Create(errorDiagnostic)); } - private static readonly ImmutableHashSet SupportedJsonTokenTypes = new[] { JTokenType.Object, JTokenType.Array, JTokenType.String, JTokenType.Integer, JTokenType.Float, JTokenType.Boolean, JTokenType.Null }.ToImmutableHashSet(); + private static readonly ImmutableHashSet SupportedJsonTokenTypes = [JTokenType.Object, JTokenType.Array, JTokenType.String, JTokenType.Integer, JTokenType.Float, JTokenType.Boolean, JTokenType.Null]; private static Expression ConvertJsonToExpression(JToken token) => token switch { @@ -1347,7 +1348,7 @@ private static Expression ConvertJsonToExpression(JToken token) JTokenType.String => new StringLiteralExpression(null, value.ToString(CultureInfo.InvariantCulture)), JTokenType.Integer => new IntegerLiteralExpression(null, value.ToObject()), // Floats are currently not supported in Bicep, so fall back to the default behavior of "any" - JTokenType.Float => new FunctionCallExpression(null, "json", ImmutableArray.Create(new StringLiteralExpression(null, value.ToObject().ToString(CultureInfo.InvariantCulture)))), + JTokenType.Float => new FunctionCallExpression(null, "json", [new StringLiteralExpression(null, value.ToObject().ToString(CultureInfo.InvariantCulture))]), JTokenType.Boolean => new BooleanLiteralExpression(null, value.ToObject()), JTokenType.Null => new NullLiteralExpression(null), _ => throw new InvalidOperationException($"Cannot parse JSON object. Unsupported value token type: {value.Type}"), @@ -1466,8 +1467,8 @@ private static FunctionResult JsonResultBuilder(SemanticModel model, IDiagnostic } // TODO: Add copyIndex here when we support loops. - private static readonly ImmutableArray BannedFunctions = new[] - { + private static readonly ImmutableArray BannedFunctions = + [ /* * The true(), false(), and null() functions are not included in this list because * we parse true, false and null as keywords in the lexer, so they can't be used as functions anyway. @@ -1493,7 +1494,7 @@ private static FunctionResult JsonResultBuilder(SemanticModel model, IDiagnostic BannedFunction.CreateForOperator("and", "&&"), BannedFunction.CreateForOperator("or", "||"), BannedFunction.CreateForOperator("coalesce", "??") - }.ToImmutableArray(); + ]; private static IEnumerable> GetSystemDecorators() { @@ -1911,9 +1912,11 @@ static IEnumerable GetResourceDerivedTypesTypeProperties() { yield return new(LanguageConstants.TypeNameResource, new TypeTemplate(LanguageConstants.TypeNameResource, - ImmutableArray.Create(new TypeParameter("ResourceTypeIdentifier", - "A string of the format '@' that identifies the kind of resource whose body type definition is to be used.", - LanguageConstants.StringResourceIdentifier)), + [ + new TypeParameter("ResourceTypeIdentifier", + "A string of the format '@' that identifies the kind of resource whose body type definition is to be used.", + LanguageConstants.StringResourceIdentifier), + ], (binder, syntax, argumentTypes) => { if (syntax.Arguments.FirstOrDefault()?.Expression is not StringTypeLiteralSyntax stringArg || stringArg.SegmentValues.Length > 1) diff --git a/src/Bicep.Core/Semantics/ResourceAncestorGraph.cs b/src/Bicep.Core/Semantics/ResourceAncestorGraph.cs index 7c1db43f4f6..4c8bf58ba99 100644 --- a/src/Bicep.Core/Semantics/ResourceAncestorGraph.cs +++ b/src/Bicep.Core/Semantics/ResourceAncestorGraph.cs @@ -34,7 +34,7 @@ public ImmutableArray GetAncestors(DeclaredResourceMetadata re } else { - return ImmutableArray.Empty; + return []; } } diff --git a/src/Bicep.Core/Semantics/ResourceSymbolVisitor.cs b/src/Bicep.Core/Semantics/ResourceSymbolVisitor.cs index ed8e72c7de1..7497fb7d7e7 100644 --- a/src/Bicep.Core/Semantics/ResourceSymbolVisitor.cs +++ b/src/Bicep.Core/Semantics/ResourceSymbolVisitor.cs @@ -12,7 +12,7 @@ public static ImmutableArray GetAllResources(Symbol symbol) var visitor = new ResourceSymbolVisitor(resources); visitor.Visit(symbol); - return resources.ToImmutableArray(); + return [.. resources]; } private readonly List resources; diff --git a/src/Bicep.Core/Semantics/SemanticModel.cs b/src/Bicep.Core/Semantics/SemanticModel.cs index e5a319deba5..4e9003874d4 100644 --- a/src/Bicep.Core/Semantics/SemanticModel.cs +++ b/src/Bicep.Core/Semantics/SemanticModel.cs @@ -153,7 +153,7 @@ public SemanticModel(Compilation compilation, BicepSourceFile sourceFile) } } - return outputs.ToImmutableArray(); + return [.. outputs]; }); } @@ -343,7 +343,7 @@ private ImmutableArray AssembleDiagnostics() filteredDiagnostics.Add(diagnostic); } - return filteredDiagnostics.ToImmutableArray(); + return [.. filteredDiagnostics]; } /// @@ -489,7 +489,7 @@ private IEnumerable GetAdditionalParamsSemanticDiagnostics() if (this.SourceFile.FileKind != BicepSourceFileKind.ParamsFile) { // not a param file - no additional diagnostics - return Enumerable.Empty(); + return []; } // try to get the bicep file's semantic model diff --git a/src/Bicep.Core/Semantics/WildcardImportInstanceFunctionSymbol.cs b/src/Bicep.Core/Semantics/WildcardImportInstanceFunctionSymbol.cs index 4450659a472..c15b077f534 100644 --- a/src/Bicep.Core/Semantics/WildcardImportInstanceFunctionSymbol.cs +++ b/src/Bicep.Core/Semantics/WildcardImportInstanceFunctionSymbol.cs @@ -12,7 +12,7 @@ public WildcardImportInstanceFunctionSymbol(WildcardImportSymbol baseSymbol, str : base(name) { BaseSymbol = baseSymbol; - Overloads = ImmutableArray.Create(TypeHelper.OverloadWithResolvedTypes(new(baseSymbol.Context.Binder), exportMetadata)); + Overloads = [TypeHelper.OverloadWithResolvedTypes(new(baseSymbol.Context.Binder), exportMetadata)]; } public override void Accept(SymbolVisitor visitor) => visitor.VisitWildcardImportInstanceFunctionSymbol(this); diff --git a/src/Bicep.Core/SourceCode/SourceArchive.cs b/src/Bicep.Core/SourceCode/SourceArchive.cs index ededccbfdc1..1eaa83ebcf4 100644 --- a/src/Bicep.Core/SourceCode/SourceArchive.cs +++ b/src/Bicep.Core/SourceCode/SourceArchive.cs @@ -432,7 +432,7 @@ private SourceArchive(Stream stream) } this.InstanceMetadata = metadata; - this.SourceFiles = infos.ToImmutableArray(); + this.SourceFiles = [.. infos]; } private string? TrimScheme(string artifactId) diff --git a/src/Bicep.Core/SourceCode/SourceCodeDocumentLinkHelper.cs b/src/Bicep.Core/SourceCode/SourceCodeDocumentLinkHelper.cs index 7ca4d19bba4..b5123eb308f 100644 --- a/src/Bicep.Core/SourceCode/SourceCodeDocumentLinkHelper.cs +++ b/src/Bicep.Core/SourceCode/SourceCodeDocumentLinkHelper.cs @@ -50,7 +50,7 @@ syntax.Path is { } && } } - dictionary.Add(referencingFile.FileUri, linksForReferencingFile.ToArray()); + dictionary.Add(referencingFile.FileUri, [.. linksForReferencingFile]); } return dictionary.ToImmutableDictionary(); diff --git a/src/Bicep.Core/Syntax/ParameterAssignmentSyntax.cs b/src/Bicep.Core/Syntax/ParameterAssignmentSyntax.cs index d83f80762c0..57fc5b8f67a 100644 --- a/src/Bicep.Core/Syntax/ParameterAssignmentSyntax.cs +++ b/src/Bicep.Core/Syntax/ParameterAssignmentSyntax.cs @@ -9,7 +9,7 @@ namespace Bicep.Core.Syntax public class ParameterAssignmentSyntax : StatementSyntax, ITopLevelNamedDeclarationSyntax { public ParameterAssignmentSyntax(Token keyword, IdentifierSyntax name, SyntaxBase assignment, SyntaxBase value) - : base(Enumerable.Empty()) + : base([]) { AssertKeyword(keyword, nameof(keyword), LanguageConstants.ParameterKeyword); AssertSyntaxType(name, nameof(name), typeof(IdentifierSyntax)); diff --git a/src/Bicep.Core/Syntax/SyntaxFactory.cs b/src/Bicep.Core/Syntax/SyntaxFactory.cs index cc176a705fe..3a6ee0319f2 100644 --- a/src/Bicep.Core/Syntax/SyntaxFactory.cs +++ b/src/Bicep.Core/Syntax/SyntaxFactory.cs @@ -8,12 +8,12 @@ namespace Bicep.Core.Syntax { public static class SyntaxFactory { - public static readonly IEnumerable EmptyTrivia = Enumerable.Empty(); + public static readonly IEnumerable EmptyTrivia = []; public static readonly IEnumerable SingleSpaceTrivia = ImmutableArray.Create( new SyntaxTrivia(SyntaxTriviaType.Whitespace, TextSpan.Nil, " ")); - public static readonly SkippedTriviaSyntax EmptySkippedTrivia = new(TextSpan.Nil, Enumerable.Empty()); + public static readonly SkippedTriviaSyntax EmptySkippedTrivia = new(TextSpan.Nil, []); public static Token CreateToken(TokenType tokenType, IEnumerable? leadingTrivia = null, IEnumerable? trailingTrivia = null) { @@ -251,7 +251,7 @@ private static StringSyntax CreateStringSyntaxWithComment(string value, string c var trailingTrivia = new SyntaxTrivia(SyntaxTriviaType.MultiLineComment, TextSpan.Nil, $"/*{comment.Replace("*/", "*\\/")}*/"); var stringToken = CreateFreeformToken(TokenType.StringComplete, value, EmptyTrivia, SyntaxFactory.SingleSpaceTrivia.Append(trailingTrivia)); - return new StringSyntax(stringToken.AsEnumerable(), Enumerable.Empty(), value.AsEnumerable()); + return new StringSyntax(stringToken.AsEnumerable(), [], value.AsEnumerable()); } public static StringSyntax CreateStringLiteralWithComment(string value, string comment) @@ -345,7 +345,7 @@ public static LambdaSyntax CreateLambdaSyntax(IReadOnlyList parameterNam return new LambdaSyntax( variableBlock, SyntaxFactory.ArrowToken, - ImmutableArray.Empty, + [], functionExpression); } diff --git a/src/Bicep.Core/Syntax/UsingDeclarationSyntax.cs b/src/Bicep.Core/Syntax/UsingDeclarationSyntax.cs index d403dbf7d59..3d74d686596 100644 --- a/src/Bicep.Core/Syntax/UsingDeclarationSyntax.cs +++ b/src/Bicep.Core/Syntax/UsingDeclarationSyntax.cs @@ -10,7 +10,7 @@ namespace Bicep.Core.Syntax public class UsingDeclarationSyntax : StatementSyntax, ITopLevelDeclarationSyntax, IArtifactReferenceSyntax { public UsingDeclarationSyntax(Token keyword, SyntaxBase path) - : base(Enumerable.Empty()) + : base([]) { AssertKeyword(keyword, nameof(keyword), LanguageConstants.UsingKeyword); AssertSyntaxType(path, nameof(path), typeof(StringSyntax), typeof(SkippedTriviaSyntax)); diff --git a/src/Bicep.Core/Text/TextCoordinateConverter.cs b/src/Bicep.Core/Text/TextCoordinateConverter.cs index e8e206bbdfc..cf1d4968282 100644 --- a/src/Bicep.Core/Text/TextCoordinateConverter.cs +++ b/src/Bicep.Core/Text/TextCoordinateConverter.cs @@ -30,7 +30,7 @@ public static ImmutableArray GetLineStarts(string text) } } - return lineStarts.ToImmutableArray(); + return [.. lineStarts]; } public static (int line, int character) GetPosition(IReadOnlyList lineStarts, int offset) diff --git a/src/Bicep.Core/Tracing/DiagnosticOptionsExtensions.cs b/src/Bicep.Core/Tracing/DiagnosticOptionsExtensions.cs index bc3b5810479..2ec77690140 100644 --- a/src/Bicep.Core/Tracing/DiagnosticOptionsExtensions.cs +++ b/src/Bicep.Core/Tracing/DiagnosticOptionsExtensions.cs @@ -8,20 +8,20 @@ namespace Bicep.Core.Tracing { public static class DiagnosticOptionsExtensions { - private static readonly ImmutableArray ArmClientAdditionalLoggedHeaders = new[] - { + private static readonly ImmutableArray ArmClientAdditionalLoggedHeaders = + [ "x-ms-ratelimit-remaining-subscription-reads", "x-ms-correlation-request-id", "x-ms-routing-request-id" - }.ToImmutableArray(); + ]; - private static readonly ImmutableArray ArmClientAdditionalLoggedQueryParams = new[] - { + private static readonly ImmutableArray ArmClientAdditionalLoggedQueryParams = + [ "api-version" - }.ToImmutableArray(); + ]; - private static readonly ImmutableArray AcrClientAdditionalLoggedHeaders = new[] - { + private static readonly ImmutableArray AcrClientAdditionalLoggedHeaders = + [ "Accept-Ranges", "x-ms-version", "Docker-Content-Digest", @@ -29,9 +29,9 @@ public static class DiagnosticOptionsExtensions "X-Content-Type-Options", "X-Ms-Correlation-Request-Id", "x-ms-ratelimit-remaining-calls-per-second" - }.ToImmutableArray(); + ]; - private static readonly ImmutableArray AcrClientAdditionalLoggedQueryParams = ImmutableArray.Empty; + private static readonly ImmutableArray AcrClientAdditionalLoggedQueryParams = []; public static void ApplySharedResourceManagerSettings(this DiagnosticsOptions options) => options.ApplySharedDiagnosticsSettings(ArmClientAdditionalLoggedHeaders, ArmClientAdditionalLoggedQueryParams); diff --git a/src/Bicep.Core/TypeSystem/ArmFunctionReturnTypeEvaluator.cs b/src/Bicep.Core/TypeSystem/ArmFunctionReturnTypeEvaluator.cs index 78c7d310229..7f1a958225f 100644 --- a/src/Bicep.Core/TypeSystem/ArmFunctionReturnTypeEvaluator.cs +++ b/src/Bicep.Core/TypeSystem/ArmFunctionReturnTypeEvaluator.cs @@ -20,7 +20,7 @@ public static class ArmFunctionReturnTypeEvaluator IEnumerable? prefixArgs = default) { var operandTypesArray = operandTypes.ToImmutableArray(); - var prefixArgsArray = prefixArgs?.ToImmutableArray() ?? ImmutableArray.Empty; + var prefixArgsArray = prefixArgs?.ToImmutableArray() ?? []; List builderDelegates = new(); diagnosticBuilders = builderDelegates; diff --git a/src/Bicep.Core/TypeSystem/ArmTemplateTypeLoader.cs b/src/Bicep.Core/TypeSystem/ArmTemplateTypeLoader.cs index d3caee09c86..700371ba0b3 100644 --- a/src/Bicep.Core/TypeSystem/ArmTemplateTypeLoader.cs +++ b/src/Bicep.Core/TypeSystem/ArmTemplateTypeLoader.cs @@ -71,7 +71,7 @@ private static ITypeReference ToTypeReferenceIgnoringNullability(SchemaValidatio var resourceTypeIdentifier = resourceTypeStringParts[0]; var internalPointerSegments = resourceTypeStringParts.Length > 1 ? resourceTypeStringParts[1].Split('/').Select(Bicep.Core.Extensions.StringExtensions.Rfc6901Decode).ToImmutableArray() - : ImmutableArray.Empty; + : []; return ResourceTypeReference.TryParse(resourceTypeIdentifier) is ResourceTypeReference resourceTypeReference ? new UnresolvedResourceDerivedType(resourceTypeReference, internalPointerSegments, fallbackType) @@ -152,7 +152,7 @@ private static TypeSymbol GetArrayType(SchemaValidationContext context, ITemplat tupleMembers.Add(type); } - return new TupleType(nameBuilder.ToString(), tupleMembers.ToImmutableArray(), default); + return new TupleType(nameBuilder.ToString(), [.. tupleMembers], default); } if (schemaNode.Items?.SchemaNode is { } items) @@ -236,7 +236,7 @@ private static TypeSymbol GetObjectType(SchemaValidationContext context, ITempla : GetObjectType( context: context, properties: schemaNode.Properties.CoalesceEnumerable().Concat(variant.Properties.CoalesceEnumerable()), - requiredProperties: (schemaNode.Required?.Value ?? Array.Empty()).Concat(variant.Required?.Value ?? Array.Empty()), + requiredProperties: (schemaNode.Required?.Value ?? []).Concat(variant.Required?.Value ?? []), additionalProperties: variant.AdditionalProperties ?? schemaNode.AdditionalProperties, flags)); } diff --git a/src/Bicep.Core/TypeSystem/DeployTimeConstantValidator.cs b/src/Bicep.Core/TypeSystem/DeployTimeConstantValidator.cs index e1cc4e8a47f..d2a16f6c89c 100644 --- a/src/Bicep.Core/TypeSystem/DeployTimeConstantValidator.cs +++ b/src/Bicep.Core/TypeSystem/DeployTimeConstantValidator.cs @@ -79,7 +79,7 @@ public static ImmutableHashSet GetVariableDependencies(Sem visitor.Visit(syntax); - return visitor.variableDependencies.ToImmutableHashSet(); + return [.. visitor.variableDependencies]; } public override void VisitVariableAccessSyntax(VariableAccessSyntax syntax) diff --git a/src/Bicep.Core/TypeSystem/DiscriminatedObjectTypeBuilder.cs b/src/Bicep.Core/TypeSystem/DiscriminatedObjectTypeBuilder.cs index 26375309fe6..3697180993a 100644 --- a/src/Bicep.Core/TypeSystem/DiscriminatedObjectTypeBuilder.cs +++ b/src/Bicep.Core/TypeSystem/DiscriminatedObjectTypeBuilder.cs @@ -90,5 +90,5 @@ public bool TryInclude(ObjectType @object) } public (ImmutableHashSet Members, ImmutableHashSet ViableDiscriminators) Build() - => new(members.ToImmutable(), discriminatorCandidates.Keys.ToImmutableHashSet()); + => new(members.ToImmutable(), [.. discriminatorCandidates.Keys]); } diff --git a/src/Bicep.Core/TypeSystem/OperationReturnTypeEvaluator.cs b/src/Bicep.Core/TypeSystem/OperationReturnTypeEvaluator.cs index 7dea2da946a..76cb1e1001b 100644 --- a/src/Bicep.Core/TypeSystem/OperationReturnTypeEvaluator.cs +++ b/src/Bicep.Core/TypeSystem/OperationReturnTypeEvaluator.cs @@ -11,45 +11,34 @@ namespace Bicep.Core.TypeSystem; public static class OperationReturnTypeEvaluator { - private static readonly ImmutableArray unaryEvaluators = ImmutableArray.Create( - new NotEvaluator(), - new MinusEvaluator()); + private static readonly ImmutableArray unaryEvaluators = [new NotEvaluator(), new MinusEvaluator()]; private static readonly IBinaryEvaluator equalsEvaluator = new BinaryEvaluator(BinaryOperator.Equals, (LanguageConstants.Any, LanguageConstants.Any), "equals", LanguageConstants.Bool); - private static readonly ImmutableArray binaries = ImmutableArray.Create( - // logical + private static readonly ImmutableArray binaries = + [ new LogicalOrEvaluator(), new LogicalAndEvaluator(), - - // equality equalsEvaluator, new NotEqualsEvaluator(), new InsensitiveEqualityEvaluator(BinaryOperator.EqualsInsensitive), new InsensitiveEqualityEvaluator(BinaryOperator.NotEqualsInsensitive, negated: true), - - // relational (int) new LessThanEvaluator(), new LessThanOrEqualToEvaluator(), new GreaterThanEvaluator(), new GreaterThanOrEqualToEvaluator(), - - // relational (string) new BinaryEvaluator(BinaryOperator.LessThan, (LanguageConstants.String, LanguageConstants.String), "less", LanguageConstants.Bool), new BinaryEvaluator(BinaryOperator.LessThanOrEqual, (LanguageConstants.String, LanguageConstants.String), "lessOrEquals", LanguageConstants.Bool), new BinaryEvaluator(BinaryOperator.GreaterThan, (LanguageConstants.String, LanguageConstants.String), "greater", LanguageConstants.Bool), new BinaryEvaluator(BinaryOperator.GreaterThanOrEqual, (LanguageConstants.String, LanguageConstants.String), "greaterOrEquals", LanguageConstants.Bool), - - // arithmetic new AdditionEvaluator(), new SubtractionEvaluator(), new BinaryEvaluator(BinaryOperator.Multiply, (LanguageConstants.Int, LanguageConstants.Int), "mul", LanguageConstants.Int), new BinaryEvaluator(BinaryOperator.Divide, (LanguageConstants.Int, LanguageConstants.Int), "div", LanguageConstants.Int), new ModuloEvaluator(), - - // coalesce - new CoalesceEvaluator()); + new CoalesceEvaluator(), + ]; public static TypeSymbol? TryFoldUnaryExpression(UnaryOperator unaryOperator, TypeSymbol operandType, IDiagnosticWriter diagnosticWriter) => unaryEvaluators.Where(e => e.IsMatch(unaryOperator, operandType)).FirstOrDefault()?.Evaluate(operandType); diff --git a/src/Bicep.Core/TypeSystem/Providers/Az/AzResourceTypeLoader.cs b/src/Bicep.Core/TypeSystem/Providers/Az/AzResourceTypeLoader.cs index 37c45586afb..add52230965 100644 --- a/src/Bicep.Core/TypeSystem/Providers/Az/AzResourceTypeLoader.cs +++ b/src/Bicep.Core/TypeSystem/Providers/Az/AzResourceTypeLoader.cs @@ -44,7 +44,7 @@ public ResourceTypeComponents LoadType(ResourceTypeReference reference) reference.ApiVersion is null || !apiFunctions.TryGetValue(reference.ApiVersion, out var functions)) { - functions = ImmutableArray.Empty; + functions = []; } var functionOverloads = functions.SelectMany(typeLocation => resourceTypeFactory.GetResourceFunctionOverloads(typeLoader.LoadResourceFunctionType(typeLocation))); diff --git a/src/Bicep.Core/TypeSystem/Providers/Az/AzResourceTypeProvider.cs b/src/Bicep.Core/TypeSystem/Providers/Az/AzResourceTypeProvider.cs index 823e270995c..446e2f44528 100644 --- a/src/Bicep.Core/TypeSystem/Providers/Az/AzResourceTypeProvider.cs +++ b/src/Bicep.Core/TypeSystem/Providers/Az/AzResourceTypeProvider.cs @@ -47,8 +47,8 @@ public static readonly ImmutableSortedSet ReadWriteDeployTimeConstantPro * - Their values may be normalized by RPs * - Some RPs are doing Put-as-Patch */ - public static readonly string[] WriteOnlyDeployTimeConstantPropertyNames = new[] - { + public static readonly string[] WriteOnlyDeployTimeConstantPropertyNames = + [ "location", "kind", "subscriptionId", @@ -62,21 +62,21 @@ public static readonly ImmutableSortedSet ReadWriteDeployTimeConstantPro "managedByExtended", "tags", "asserts", - }; + ]; - public static readonly TypeSymbol Tags = new ObjectType(nameof(Tags), TypeSymbolValidationFlags.Default, Enumerable.Empty(), LanguageConstants.String, TypePropertyFlags.None); - public static readonly TypeSymbol ResourceAsserts = new ObjectType(nameof(ResourceAsserts), TypeSymbolValidationFlags.Default, Enumerable.Empty(), LanguageConstants.Bool, TypePropertyFlags.DeployTimeConstant); + public static readonly TypeSymbol Tags = new ObjectType(nameof(Tags), TypeSymbolValidationFlags.Default, [], LanguageConstants.String, TypePropertyFlags.None); + public static readonly TypeSymbol ResourceAsserts = new ObjectType(nameof(ResourceAsserts), TypeSymbolValidationFlags.Default, [], LanguageConstants.Bool, TypePropertyFlags.DeployTimeConstant); private readonly IResourceTypeLoader resourceTypeLoader; private readonly ResourceTypeCache definedTypeCache; private readonly ResourceTypeCache generatedTypeCache; - public static readonly ImmutableHashSet UniqueIdentifierProperties = new[] - { + public static readonly ImmutableHashSet UniqueIdentifierProperties = + [ ResourceNamePropertyName, LanguageConstants.ResourceScopePropertyName, LanguageConstants.ResourceParentPropertyName, - }.ToImmutableHashSet(); + ]; public static IEnumerable GetCommonResourceProperties(ResourceTypeReference reference) { @@ -182,7 +182,7 @@ public static IEnumerable KnownTopLevelResourceProperties() new TypeProperty("tenantId", LanguageConstants.String), new TypeProperty("type", resourceIdentityType, TypePropertyFlags.Required), new TypeProperty("identityIds", new TypedArrayType(LanguageConstants.String, TypeSymbolValidationFlags.Default)), - new TypeProperty("userAssignedIdentities", new ObjectType("userAssignedIdentities", TypeSymbolValidationFlags.Default, Enumerable.Empty(), userAssignedIdentity)), + new TypeProperty("userAssignedIdentities", new ObjectType("userAssignedIdentities", TypeSymbolValidationFlags.Default, [], userAssignedIdentity)), new TypeProperty("delegatedResources", LanguageConstants.Object), }, null)); } diff --git a/src/Bicep.Core/TypeSystem/Providers/EmptyResourceTypeProvider.cs b/src/Bicep.Core/TypeSystem/Providers/EmptyResourceTypeProvider.cs index 9e065eba3f7..21152bd7bc8 100644 --- a/src/Bicep.Core/TypeSystem/Providers/EmptyResourceTypeProvider.cs +++ b/src/Bicep.Core/TypeSystem/Providers/EmptyResourceTypeProvider.cs @@ -9,7 +9,7 @@ namespace Bicep.Core.TypeSystem.Providers public class EmptyResourceTypeProvider : IResourceTypeProvider { public IEnumerable GetAvailableTypes() - => Enumerable.Empty(); + => []; public ResourceType? TryGetDefinedType(NamespaceType declaringNamespace, ResourceTypeReference reference, ResourceTypeGenerationFlags flags) => null; diff --git a/src/Bicep.Core/TypeSystem/Providers/K8s/K8sResourceTypeProvider.cs b/src/Bicep.Core/TypeSystem/Providers/K8s/K8sResourceTypeProvider.cs index 5e2503f8a3a..d90f7daf657 100644 --- a/src/Bicep.Core/TypeSystem/Providers/K8s/K8sResourceTypeProvider.cs +++ b/src/Bicep.Core/TypeSystem/Providers/K8s/K8sResourceTypeProvider.cs @@ -12,16 +12,16 @@ public class K8sResourceTypeProvider : ResourceTypeProviderBase, IResourceTypePr public const string MetadataPropertyName = "metadata"; public const string NamespaceProperty = "namespace"; - public static readonly TypeSymbol Tags = new ObjectType(nameof(Tags), TypeSymbolValidationFlags.Default, Enumerable.Empty(), LanguageConstants.String, TypePropertyFlags.None); + public static readonly TypeSymbol Tags = new ObjectType(nameof(Tags), TypeSymbolValidationFlags.Default, [], LanguageConstants.String, TypePropertyFlags.None); private readonly K8sResourceTypeLoader resourceTypeLoader; private readonly ResourceTypeCache definedTypeCache; private readonly ResourceTypeCache generatedTypeCache; - public static readonly ImmutableHashSet UniqueIdentifierProperties = new[] - { + public static readonly ImmutableHashSet UniqueIdentifierProperties = + [ NamePropertyName, - }.ToImmutableHashSet(); + ]; public K8sResourceTypeProvider(K8sResourceTypeLoader resourceTypeLoader) : base(resourceTypeLoader.GetAvailableTypes().ToImmutableHashSet()) @@ -177,7 +177,7 @@ private static TypePropertyFlags ConvertToReadOnly(TypePropertyFlags typePropert ResourceScope.Tenant | ResourceScope.ManagementGroup | ResourceScope.Subscription | ResourceScope.ResourceGroup | ResourceScope.Resource, ResourceScope.None, ResourceFlags.None, - new ObjectType(typeReference.FormatName(), TypeSymbolValidationFlags.Default, Enumerable.Empty(), LanguageConstants.Any)); + new ObjectType(typeReference.FormatName(), TypeSymbolValidationFlags.Default, [], LanguageConstants.Any)); return SetBicepResourceProperties(resourceType, flags); }); diff --git a/src/Bicep.Core/TypeSystem/Providers/MicrosoftGraph/MicrosoftGraphResourceTypeProvider.cs b/src/Bicep.Core/TypeSystem/Providers/MicrosoftGraph/MicrosoftGraphResourceTypeProvider.cs index b4001f609e2..6fbaa4a9180 100644 --- a/src/Bicep.Core/TypeSystem/Providers/MicrosoftGraph/MicrosoftGraphResourceTypeProvider.cs +++ b/src/Bicep.Core/TypeSystem/Providers/MicrosoftGraph/MicrosoftGraphResourceTypeProvider.cs @@ -12,18 +12,18 @@ public class MicrosoftGraphResourceTypeProvider : ResourceTypeProviderBase, IRes public const string AppIdPropertyName = "appId"; public const string NamePropertyName = "name"; - public static readonly TypeSymbol Tags = new ObjectType(nameof(Tags), TypeSymbolValidationFlags.Default, Enumerable.Empty(), LanguageConstants.String, TypePropertyFlags.None); + public static readonly TypeSymbol Tags = new ObjectType(nameof(Tags), TypeSymbolValidationFlags.Default, [], LanguageConstants.String, TypePropertyFlags.None); private readonly MicrosoftGraphResourceTypeLoader resourceTypeLoader; private readonly ResourceTypeCache definedTypeCache; private readonly ResourceTypeCache generatedTypeCache; - public static readonly ImmutableHashSet UniqueIdentifierProperties = new[] - { + public static readonly ImmutableHashSet UniqueIdentifierProperties = + [ UniqueNamePropertyName, AppIdPropertyName, NamePropertyName, - }.ToImmutableHashSet(); + ]; /* * The following top-level properties must be set deploy-time constant values, diff --git a/src/Bicep.Core/TypeSystem/Providers/ThirdParty/ThirdPartyResourceTypeProvider.cs b/src/Bicep.Core/TypeSystem/Providers/ThirdParty/ThirdPartyResourceTypeProvider.cs index a2208f5e8b0..ee36e0ea40d 100644 --- a/src/Bicep.Core/TypeSystem/Providers/ThirdParty/ThirdPartyResourceTypeProvider.cs +++ b/src/Bicep.Core/TypeSystem/Providers/ThirdParty/ThirdPartyResourceTypeProvider.cs @@ -8,7 +8,7 @@ namespace Bicep.Core.TypeSystem.Providers.ThirdParty { public class ThirdPartyResourceTypeProvider : ResourceTypeProviderBase, IResourceTypeProvider { - public static readonly TypeSymbol Tags = new ObjectType(nameof(Tags), TypeSymbolValidationFlags.Default, Enumerable.Empty(), LanguageConstants.String, TypePropertyFlags.None); + public static readonly TypeSymbol Tags = new ObjectType(nameof(Tags), TypeSymbolValidationFlags.Default, [], LanguageConstants.String, TypePropertyFlags.None); private readonly ThirdPartyResourceTypeLoader resourceTypeLoader; private readonly ResourceTypeCache definedTypeCache; @@ -133,7 +133,7 @@ private static TypePropertyFlags ConvertToReadOnly(TypePropertyFlags typePropert resourceType.ReadOnlyScopes, resourceType.Flags, resourceType.Body, - ImmutableHashSet.Empty); + []); } public ResourceType? TryGenerateFallbackType(NamespaceType declaringNamespace, ResourceTypeReference typeReference, ResourceTypeGenerationFlags flags) @@ -161,7 +161,7 @@ private static TypePropertyFlags ConvertToReadOnly(TypePropertyFlags typePropert resourceType.ReadOnlyScopes, resourceType.Flags, resourceType.Body, - ImmutableHashSet.Empty); + []); } return null; diff --git a/src/Bicep.Core/TypeSystem/ResourceDerivedTypeDiagnosticReporter.cs b/src/Bicep.Core/TypeSystem/ResourceDerivedTypeDiagnosticReporter.cs index 87b11838975..66088967a03 100644 --- a/src/Bicep.Core/TypeSystem/ResourceDerivedTypeDiagnosticReporter.cs +++ b/src/Bicep.Core/TypeSystem/ResourceDerivedTypeDiagnosticReporter.cs @@ -51,7 +51,7 @@ public ResourceDerivedTypeDiagnosticReporter(IFeatureProvider features, IBinder UnionType union => union.Members.SelectMany(ReportResourceDerivedTypeDiagnostics), TypeType typeType => ReportResourceDerivedTypeDiagnostics(typeType.Unwrapped), LambdaType lambda => lambda.ArgumentTypes.Concat(lambda.OptionalArgumentTypes).Concat(lambda.ReturnType).SelectMany(ReportResourceDerivedTypeDiagnostics), - _ => Enumerable.Empty(), + _ => [], }) { yield return diagnostic; diff --git a/src/Bicep.Core/TypeSystem/TypeAssignment.cs b/src/Bicep.Core/TypeSystem/TypeAssignment.cs index e7dd774d9c9..2ec41386591 100644 --- a/src/Bicep.Core/TypeSystem/TypeAssignment.cs +++ b/src/Bicep.Core/TypeSystem/TypeAssignment.cs @@ -7,7 +7,7 @@ namespace Bicep.Core.TypeSystem public class TypeAssignment { public TypeAssignment(ITypeReference reference) - : this(reference, Enumerable.Empty()) + : this(reference, []) { } diff --git a/src/Bicep.Core/TypeSystem/TypeAssignmentVisitor.cs b/src/Bicep.Core/TypeSystem/TypeAssignmentVisitor.cs index 6e48c5416f8..be2e389d60e 100644 --- a/src/Bicep.Core/TypeSystem/TypeAssignmentVisitor.cs +++ b/src/Bicep.Core/TypeSystem/TypeAssignmentVisitor.cs @@ -1231,7 +1231,7 @@ public override void VisitSkippedTriviaSyntax(SkippedTriviaSyntax syntax) => AssignType(syntax, () => { // error should have already been raised by the ParseDiagnosticsVisitor - no need to add another - return ErrorType.Create(Enumerable.Empty()); + return ErrorType.Create([]); }); public override void VisitObjectSyntax(ObjectSyntax syntax) @@ -1450,7 +1450,7 @@ childType is not ErrorType && return new TypedArrayType(itemType, TypeSymbolValidationFlags.Default); } - return new TupleType(tupleEntries.ToImmutableArray(), TypeSymbolValidationFlags.Default); + return new TupleType([.. tupleEntries], TypeSymbolValidationFlags.Default); }); public override void VisitTernaryOperationSyntax(TernaryOperationSyntax syntax) @@ -1940,7 +1940,7 @@ public override void VisitLambdaSyntax(LambdaSyntax syntax) var argumentTypes = syntax.GetLocalVariables().Select(x => typeManager.GetTypeInfo(x)); var returnType = this.GetTypeInfo(syntax.Body); - return new LambdaType(argumentTypes.ToImmutableArray(), ImmutableArray.Empty, returnType); + return new LambdaType(argumentTypes.ToImmutableArray(), [], returnType); }); public override void VisitTypedLambdaSyntax(TypedLambdaSyntax syntax) @@ -2368,7 +2368,7 @@ private IEnumerable GetOutputDeclarationDiagnostics(TypeSymbol assi if (assignedType is ErrorType) { // no point in checking that the value is assignable to the declared output type if no valid declared type could be discerned - return Enumerable.Empty(); + return []; } var diagnosticWriter = ToListDiagnosticWriter.Create(); @@ -2448,7 +2448,7 @@ syntax.ConditionExpression is ParenthesizedExpressionSyntax parenthesized : builder.ValueTypeMismatch(LanguageConstants.Bool).AsEnumerable(); } - return Enumerable.Empty(); + return []; } public static TypeSymbol UnwrapType(TypeSymbol baseType) => diff --git a/src/Bicep.Core/TypeSystem/TypeFactory.cs b/src/Bicep.Core/TypeSystem/TypeFactory.cs index aa0c6da295b..20b51fa60c7 100644 --- a/src/Bicep.Core/TypeSystem/TypeFactory.cs +++ b/src/Bicep.Core/TypeSystem/TypeFactory.cs @@ -43,7 +43,7 @@ public static ArrayType CreateArrayType(ITypeReference itemType, long? minLength { if (maxLength.HasValue && maxLength.Value == 0) { - return new TupleType(ImmutableArray.Empty, validationFlags); + return new TupleType([], validationFlags); } if (ReferenceEquals(itemType, LanguageConstants.Any)) diff --git a/src/Bicep.Core/TypeSystem/TypeHelper.cs b/src/Bicep.Core/TypeSystem/TypeHelper.cs index ba82c8f63b5..f96f90b9dd6 100644 --- a/src/Bicep.Core/TypeSystem/TypeHelper.cs +++ b/src/Bicep.Core/TypeSystem/TypeHelper.cs @@ -143,7 +143,7 @@ JTokenType.Integer when token.ToObject() is BigInteger intVal && lon } } - return new TupleType(nameBuilder.ToString(), convertedItems.ToImmutableArray(), TypeSymbolValidationFlags.Default); + return new TupleType(nameBuilder.ToString(), [.. convertedItems], TypeSymbolValidationFlags.Default); } /// @@ -256,7 +256,7 @@ static TypeSymbol FlattenTuple(TypeSymbol flattenInputType, TupleType tupleType, return FlattenArray(flattenInputType, tupleType, argumentPosition); } - return new TupleType(nameBuilder.ToString(), flattenedItems.ToImmutableArray(), flags); + return new TupleType(nameBuilder.ToString(), [.. flattenedItems], flags); } static TypeSymbol FlattenUnionOfArrays(TypeSymbol flattenInputType, UnionType unionType, IPositionable argumentPosition) => UnionOfFlattened( @@ -493,7 +493,7 @@ private static ImmutableArray NormalizeTypeList(IEnumerable(LanguageConstants.Any); + return [LanguageConstants.Any]; } if (hasUnrefinedUntypedArrayMember && member is ArrayType) @@ -510,7 +510,7 @@ private static ImmutableArray NormalizeTypeList(IEnumerable(); + return [.. distinctMembers.Order(typeComparer)]; } private static IEnumerable FlattenMembers(IEnumerable members) => diff --git a/src/Bicep.Core/TypeSystem/TypeValidator.cs b/src/Bicep.Core/TypeSystem/TypeValidator.cs index 1c30f9c848b..cca68a10210 100644 --- a/src/Bicep.Core/TypeSystem/TypeValidator.cs +++ b/src/Bicep.Core/TypeSystem/TypeValidator.cs @@ -741,7 +741,7 @@ private TypeSymbol NarrowLambdaType(TypeValidatorConfig config, LambdaSyntax lam narrowedVariables[i] = NarrowType(config, variables[i], targetType.GetArgumentType(i).Type); } - return new LambdaType(narrowedVariables.ToImmutableArray(), ImmutableArray.Empty, returnType); + return new LambdaType([.. narrowedVariables], [], returnType); } private TypeSymbol NarrowVariableAccessType(TypeValidatorConfig config, VariableAccessSyntax variableAccess, TypeSymbol targetType) @@ -1056,7 +1056,7 @@ static TypeSymbol RemoveImplicitNull(TypeSymbol type, bool typeWasPreserved) { var missingRequiredProperties = expressionObjectType.AdditionalPropertiesType is not null // if the assigned value allows additional properties, we can't know if it's missing any - ? ImmutableArray.Empty + ? [] // otherwise, look for required properties on the target for which there is no declared counterpart on the assigned value : targetType.Properties.Values .Where(p => p.Flags.HasFlag(TypePropertyFlags.Required) && @@ -1192,7 +1192,7 @@ static TypeSymbol RemoveImplicitNull(TypeSymbol type, bool typeWasPreserved) }); } - foreach (var unknownProperty in (expression as ObjectSyntax)?.Properties.Where(p => p.TryGetKeyText() is null) ?? Enumerable.Empty()) + foreach (var unknownProperty in (expression as ObjectSyntax)?.Properties.Where(p => p.TryGetKeyText() is null) ?? []) { diagnosticWriter.Write(DiagnosticBuilder.ForPosition(unknownProperty.Key).DisallowedInterpolatedKeyProperty(shouldWarn, TryGetSourceDeclaration(config), diff --git a/src/Bicep.Core/TypeSystem/Types/ErrorType.cs b/src/Bicep.Core/TypeSystem/Types/ErrorType.cs index a19cb86c861..c306733de44 100644 --- a/src/Bicep.Core/TypeSystem/Types/ErrorType.cs +++ b/src/Bicep.Core/TypeSystem/Types/ErrorType.cs @@ -24,7 +24,7 @@ public static ErrorType Create(IEnumerable errors) => new(errors.ToImmutableArray()); public static ErrorType Empty() - => new(ImmutableArray.Empty); + => new([]); public override IEnumerable GetDiagnostics() => errors; diff --git a/src/Bicep.Core/Workspaces/SourceFileFactory.cs b/src/Bicep.Core/Workspaces/SourceFileFactory.cs index 378715966c9..622a891a2aa 100644 --- a/src/Bicep.Core/Workspaces/SourceFileFactory.cs +++ b/src/Bicep.Core/Workspaces/SourceFileFactory.cs @@ -127,7 +127,7 @@ private static void ValidateTemplate(Template template) // To validate resources we would need to know what API version the user will use to deploy the template, which is impossible. // Replacing resources with an empty array to skip validating them. var templateResources = template.Resources; - template.Resources = Array.Empty(); + template.Resources = []; // The apiVersion and deploymentScope parameters don't matter here as they are only used when validating resources. TemplateEngine.ValidateTemplate(template, CoreConstants.ApiVersion20200101, TemplateDeploymentScope.NotSpecified); diff --git a/src/Bicep.Core/Workspaces/SourceFileGrouping.cs b/src/Bicep.Core/Workspaces/SourceFileGrouping.cs index ca17a3bff2a..6a088c6683d 100644 --- a/src/Bicep.Core/Workspaces/SourceFileGrouping.cs +++ b/src/Bicep.Core/Workspaces/SourceFileGrouping.cs @@ -81,6 +81,6 @@ public ImmutableHashSet GetFilesDependingOn(ISourceFile sourceFile) } } - return knownFiles.ToImmutableHashSet(); + return [.. knownFiles]; } } diff --git a/src/Bicep.Decompiler.UnitTests/ArmHelpers/ExpressionHelpersTests.cs b/src/Bicep.Decompiler.UnitTests/ArmHelpers/ExpressionHelpersTests.cs index ca0ffcb0753..8ad1542edf8 100644 --- a/src/Bicep.Decompiler.UnitTests/ArmHelpers/ExpressionHelpersTests.cs +++ b/src/Bicep.Decompiler.UnitTests/ArmHelpers/ExpressionHelpersTests.cs @@ -110,7 +110,7 @@ public void RewriteExpressions_replaces_expressions(string jsonInput, string exp { if (expression is FunctionExpression function && function.Function == "replaceMe") { - return new FunctionExpression("replaced", Array.Empty(), Array.Empty()); + return new FunctionExpression("replaced", [], []); } return expression; diff --git a/src/Bicep.Decompiler/ArmHelpers/ExpressionHelpers.cs b/src/Bicep.Decompiler/ArmHelpers/ExpressionHelpers.cs index 541bc2e1af8..68af82bcd47 100644 --- a/src/Bicep.Decompiler/ArmHelpers/ExpressionHelpers.cs +++ b/src/Bicep.Decompiler/ArmHelpers/ExpressionHelpers.cs @@ -25,7 +25,7 @@ public static LanguageExpression ParseExpression(string value) } public static FunctionExpression Concat(params LanguageExpression[] expressions) - => new("concat", expressions, new LanguageExpression[0]); + => new("concat", expressions, []); private static IEnumerable CombineConcatArguments(IEnumerable arguments) { @@ -122,7 +122,7 @@ public static LanguageExpression FlattenStringOperations(LanguageExpression orig } // overwrite the original expression - functionExpression = Concat(concatExpressions.ToArray()); + functionExpression = Concat([.. concatExpressions]); } // flatten nested 'concat' functions @@ -161,7 +161,7 @@ private static LanguageExpression FormatNameExpression(IEnumerable i == 0 ? new[] { expression } : new[] { new JTokenExpression("/"), expression }) + .SelectMany((expression, i) => i == 0 ? new[] { expression } : [new JTokenExpression("/"), expression]) .ToArray(); return pathSegments.Length > 1 ? Concat(pathSegments) : pathSegments.First(); @@ -215,7 +215,7 @@ public static (string typeString, LanguageExpression nameExpression)? TryGetReso functionExpression = new FunctionExpression( "resourceId", typeParam.AsEnumerable().Concat(names).ToArray(), - new LanguageExpression[] { }); + []); } if (!functionExpression.NameEquals("resourceId") || diff --git a/src/Bicep.Decompiler/ArmHelpers/TemplateHelpers.cs b/src/Bicep.Decompiler/ArmHelpers/TemplateHelpers.cs index 43c0c00313b..c076473dc93 100644 --- a/src/Bicep.Decompiler/ArmHelpers/TemplateHelpers.cs +++ b/src/Bicep.Decompiler/ArmHelpers/TemplateHelpers.cs @@ -151,7 +151,7 @@ LanguageExpression ReplaceWithParameter(FunctionExpression function, string type var withoutProperties = new FunctionExpression( function.Function, function.Parameters, - Array.Empty()); + []); var paramNameSerialized = ExpressionsEngine.SerializeExpression(paramNameExpression); var paramName = UniqueNamingResolver.EscapeIdentifier(paramNameSerialized, isGenerated: true); @@ -247,7 +247,7 @@ LanguageExpression ReplaceWithParameter(FunctionExpression function, string type var paramExpression = new FunctionExpression( "parameters", function.Parameters, - Array.Empty()); + []); parameters[parameterName.Value.ToString()] = (paramExpression, "__BICEP_REPLACE"); } diff --git a/src/Bicep.Decompiler/TemplateConverter.cs b/src/Bicep.Decompiler/TemplateConverter.cs index eb996805b4f..c14fe2dfce3 100644 --- a/src/Bicep.Decompiler/TemplateConverter.cs +++ b/src/Bicep.Decompiler/TemplateConverter.cs @@ -338,10 +338,10 @@ rightParameter is FunctionExpression rightFunctionExpression && SyntaxFactory.LeftParenToken, new TernaryOperationSyntax( ParseLanguageExpression(expression.Parameters[0]), - ImmutableArray.Empty, + [], SyntaxFactory.QuestionToken, ParseLanguageExpression(expression.Parameters[1]), - ImmutableArray.Empty, + [], SyntaxFactory.ColonToken, ParseLanguageExpression(expression.Parameters[2])), SyntaxFactory.RightParenToken); @@ -1030,7 +1030,7 @@ private ForSyntax ProcessNamedCopySyntax(TToken input, string indexIdent // copyIndex() -> copyIndex(, ) return new FunctionExpression( "copyIndex", - new[] { new JTokenExpression(name), function.Parameters[0] }, + [new JTokenExpression(name), function.Parameters[0]], function.Properties); } } @@ -1059,15 +1059,14 @@ private ForSyntax ProcessNamedCopySyntax(TToken input, string indexIdent var varExpression = new FunctionExpression( "variables", new[] { new JTokenExpression(indexIdentifier), }, - Array.Empty()); + []); return new FunctionExpression( "add", - new[] - { + [ varExpression, function.Parameters[1], - }, + ], function.Properties); } @@ -1431,7 +1430,7 @@ private JObject ExpectObject(JToken jToken) private ObjectSyntax ProcessModuleBody(IReadOnlyDictionary copyResourceLookup, JObject resource) { - var parameters = (resource["properties"]?["parameters"] as JObject)?.Properties() ?? Enumerable.Empty(); + var parameters = (resource["properties"]?["parameters"] as JObject)?.Properties() ?? []; var paramProperties = new List(); foreach (var param in parameters) { diff --git a/src/Bicep.LangServer.IntegrationTests/Assertions/AssertionScopeExtensions.cs b/src/Bicep.LangServer.IntegrationTests/Assertions/AssertionScopeExtensions.cs index cfc5a24b0d9..03f7584aa4f 100644 --- a/src/Bicep.LangServer.IntegrationTests/Assertions/AssertionScopeExtensions.cs +++ b/src/Bicep.LangServer.IntegrationTests/Assertions/AssertionScopeExtensions.cs @@ -17,7 +17,7 @@ public static AssertionScope WithAnnotations(this AssertionScope assertionSco assertionScope, bicepFile, contextName, - (data ?? Enumerable.Empty()).Select(x => new PrintHelper.Annotation(FromRange(bicepFile, rangeFunc(x)), messageFunc(x)))); + (data ?? []).Select(x => new PrintHelper.Annotation(FromRange(bicepFile, rangeFunc(x)), messageFunc(x)))); public static TextSpan FromRange(BicepSourceFile bicepFile, Range range) { diff --git a/src/Bicep.LangServer.IntegrationTests/CodeLensTests.cs b/src/Bicep.LangServer.IntegrationTests/CodeLensTests.cs index e9d2a6224bf..47d8b05e1ac 100644 --- a/src/Bicep.LangServer.IntegrationTests/CodeLensTests.cs +++ b/src/Bicep.LangServer.IntegrationTests/CodeLensTests.cs @@ -261,7 +261,7 @@ private async Task GetExternalSourceCodeLenses(MultiFileLanguageServ { TextDocument = new TextDocumentIdentifier(documentUri) }))?.Where(a => a.IsExternalSourceCodeLens()).ToArray() - ?? Array.Empty(); + ?? []; } } } diff --git a/src/Bicep.LangServer.IntegrationTests/Helpers/ServerRequestHelper.cs b/src/Bicep.LangServer.IntegrationTests/Helpers/ServerRequestHelper.cs index 0c17e06c015..74f224c9612 100644 --- a/src/Bicep.LangServer.IntegrationTests/Helpers/ServerRequestHelper.cs +++ b/src/Bicep.LangServer.IntegrationTests/Helpers/ServerRequestHelper.cs @@ -39,7 +39,7 @@ public async Task> RequestCompletions(IEnumerable completions.Add(completionList); } - return completions.ToImmutableArray(); + return [.. completions]; } public async Task RequestCompletion(int cursor) diff --git a/src/Bicep.LangServer.IntegrationTests/HoverTests.cs b/src/Bicep.LangServer.IntegrationTests/HoverTests.cs index 27f17e6db31..ed701815f07 100644 --- a/src/Bicep.LangServer.IntegrationTests/HoverTests.cs +++ b/src/Bicep.LangServer.IntegrationTests/HoverTests.cs @@ -1240,7 +1240,7 @@ private static void ValidateHover(Hover? hover, Symbol symbol) case VariableSymbol variable: // the hovers with errors don't appear in VS code and only occur in tests - tooltip.Should().ContainAny(new[] { $"var {variable.Name}: {variable.Type}", $"var {variable.Name}: error" }); + tooltip.Should().ContainAny([$"var {variable.Name}: {variable.Type}", $"var {variable.Name}: error"]); break; case ImportedVariableSymbol importedVariable: @@ -1249,7 +1249,7 @@ private static void ValidateHover(Hover? hover, Symbol symbol) case TestSymbol variable: // the hovers with errors don't appear in VS code and only occur in tests - tooltip.Should().ContainAny(new[] { $"test {variable.Name}", $"var {variable.Name}" }); + tooltip.Should().ContainAny([$"test {variable.Name}", $"var {variable.Name}"]); break; case ResourceSymbol resource: diff --git a/src/Bicep.LangServer.IntegrationTests/Registry/ModuleRestoreSchedulerTests.cs b/src/Bicep.LangServer.IntegrationTests/Registry/ModuleRestoreSchedulerTests.cs index c973a2ddce4..02574d78360 100644 --- a/src/Bicep.LangServer.IntegrationTests/Registry/ModuleRestoreSchedulerTests.cs +++ b/src/Bicep.LangServer.IntegrationTests/Registry/ModuleRestoreSchedulerTests.cs @@ -71,7 +71,7 @@ public async Task PublicMethodsShouldThrowAfterDispose() Action startFail = () => scheduler.Start(); startFail.Should().Throw(); - Action requestFail = () => scheduler.RequestModuleRestore(Repository.Create().Object, DocumentUri.From("untitled://one"), Enumerable.Empty()); + Action requestFail = () => scheduler.RequestModuleRestore(Repository.Create().Object, DocumentUri.From("untitled://one"), []); requestFail.Should().Throw(); } diff --git a/src/Bicep.LangServer.UnitTests/BicepCompletionProviderTests.cs b/src/Bicep.LangServer.UnitTests/BicepCompletionProviderTests.cs index 64ad08c81d5..5372e40d40b 100644 --- a/src/Bicep.LangServer.UnitTests/BicepCompletionProviderTests.cs +++ b/src/Bicep.LangServer.UnitTests/BicepCompletionProviderTests.cs @@ -189,7 +189,7 @@ param p string resourceCompletion.Kind.Should().Be(CompletionItemKind.Interface); resourceCompletion.InsertTextFormat.Should().Be(InsertTextFormat.PlainText); resourceCompletion.TextEdit!.TextEdit!.NewText.Should().Be(expectedResource); - resourceCompletion.CommitCharacters.Should().BeEquivalentTo(new[] { ":", }); + resourceCompletion.CommitCharacters.Should().BeEquivalentTo([":",]); resourceCompletion.Detail.Should().Be(expectedResource); const string expectedParam = "p"; @@ -268,7 +268,7 @@ param concat string resourceCompletion.Kind.Should().Be(CompletionItemKind.Interface); resourceCompletion.InsertTextFormat.Should().Be(InsertTextFormat.PlainText); resourceCompletion.TextEdit!.TextEdit!.NewText.Should().Be(expectedResource); - resourceCompletion.CommitCharacters.Should().BeEquivalentTo(new[] { ":", }); + resourceCompletion.CommitCharacters.Should().BeEquivalentTo([":",]); resourceCompletion.Detail.Should().Be(expectedResource); const string expectedParam = "concat"; @@ -481,7 +481,7 @@ private static void AssertExpectedDeclarationTypeCompletions(List completions, bool expectParamDefaultFunctions, IEnumerable? fullyQualifiedFunctionNames = null) { - fullyQualifiedFunctionNames ??= Enumerable.Empty(); + fullyQualifiedFunctionNames ??= []; var fullyQualifiedFunctionParts = fullyQualifiedFunctionNames.Select(fqfn => { diff --git a/src/Bicep.LangServer.UnitTests/Completions/PublicRegistryModuleMetadataProviderTests.cs b/src/Bicep.LangServer.UnitTests/Completions/PublicRegistryModuleMetadataProviderTests.cs index 50aac04edd1..dd3a25bdc43 100644 --- a/src/Bicep.LangServer.UnitTests/Completions/PublicRegistryModuleMetadataProviderTests.cs +++ b/src/Bicep.LangServer.UnitTests/Completions/PublicRegistryModuleMetadataProviderTests.cs @@ -1160,7 +1160,7 @@ public void GetModules_ForwardsCompatibleWithOriginalVersion() { // Earlier Bicep versions should not be confused by new metadata formats var metadataStream = new MemoryStream(Encoding.UTF8.GetBytes(ModuleIndexJson)); - ModuleMetadata_Original[] metadata = JsonSerializer.Deserialize(metadataStream)!.ToArray(); + ModuleMetadata_Original[] metadata = [.. JsonSerializer.Deserialize(metadataStream)!]; metadata.Length.Should().BeGreaterThanOrEqualTo(29); metadata.Select(m => m.moduleName).Should().Contain("samples/array-loop"); diff --git a/src/Bicep.LangServer.UnitTests/Handlers/BicepDecompileCommandHandlerTests.cs b/src/Bicep.LangServer.UnitTests/Handlers/BicepDecompileCommandHandlerTests.cs index 0c989e9109e..c1526abdd3d 100644 --- a/src/Bicep.LangServer.UnitTests/Handlers/BicepDecompileCommandHandlerTests.cs +++ b/src/Bicep.LangServer.UnitTests/Handlers/BicepDecompileCommandHandlerTests.cs @@ -398,7 +398,7 @@ public async Task SimpleJson_OutputFileAlreadyExists_AndUserSelectsOverwrite() new BicepDecompileCommandParams(DocumentUri.File(jsonPath)), CancellationToken.None); - result.conflictingOutputPaths.Should().BeEquivalentToPaths(new string[] { Path.Join(testOutputPath, "main.bicep") }); + result.conflictingOutputPaths.Should().BeEquivalentToPaths([Path.Join(testOutputPath, "main.bicep")]); result.errorMessage.Should().BeNull(); result.mainBicepPath.Should().BeEquivalentToPath(expectedBicepPath); result.errorMessage.Should().BeNull(); @@ -426,7 +426,7 @@ public async Task SimpleJson_OutputFileAlreadyExists_AndUserSelectsCopy() new BicepDecompileCommandParams(DocumentUri.File(jsonPath)), CancellationToken.None); - result.conflictingOutputPaths.Should().BeEquivalentToPaths(new string[] { Path.Join(testOutputPath, "main.bicep") }); + result.conflictingOutputPaths.Should().BeEquivalentToPaths([Path.Join(testOutputPath, "main.bicep")]); result.errorMessage.Should().BeNull(); var saveResult = await saveHandler.Handle(new(result.decompileId, result.outputFiles, overwrite: false), CancellationToken.None); @@ -462,7 +462,7 @@ public async Task SimpleJson_OutputFileAlreadyExists_AndLotsOfExistingCopies_And new BicepDecompileCommandParams(DocumentUri.File(jsonPath)), CancellationToken.None); - result.conflictingOutputPaths.Should().BeEquivalentToPaths(new string[] { Path.Join(testOutputPath, "main.bicep") }); + result.conflictingOutputPaths.Should().BeEquivalentToPaths([Path.Join(testOutputPath, "main.bicep")]); result.mainBicepPath.Should().EndWith("main.bicep"); result.errorMessage.Should().BeNull(); @@ -532,7 +532,7 @@ public async Task MultiFileDecompilation_MainFileConflicts_UserSelectsOverwriteA new BicepDecompileCommandParams(DocumentUri.File(jsonPath)), CancellationToken.None); - result.conflictingOutputPaths.Should().BeEquivalentToPaths(new string[] { expectedBicepPath }); + result.conflictingOutputPaths.Should().BeEquivalentToPaths([expectedBicepPath]); result.mainBicepPath.Should().BeEquivalentToPath(expectedBicepPath); result.errorMessage.Should().BeNull(); @@ -570,10 +570,10 @@ public async Task MultiFileDecompilation_OtherFilesConflict_UserSelectsOverwrite new BicepDecompileCommandParams(DocumentUri.File(jsonPath)), CancellationToken.None); - result.conflictingOutputPaths.Should().BeEquivalentToPaths(new string[] { + result.conflictingOutputPaths.Should().BeEquivalentToPaths([ Path.Join(testOutputPath, "main file.bicep"), - Path.Join(testOutputPath, ComplexExpectedBicep_Filename3) - }); + Path.Join(testOutputPath, ComplexExpectedBicep_Filename3) + ]); result.mainBicepPath.Should().BeEquivalentToPath(expectedBicepPath); result.errorMessage.Should().BeNull(); @@ -613,10 +613,10 @@ public async Task MultiFileDecompilation_OtherFilesConflict_UserSelectsCopy() new BicepDecompileCommandParams(DocumentUri.File(jsonPath)), CancellationToken.None); - result.conflictingOutputPaths.Should().BeEquivalentToPaths(new string[] { + result.conflictingOutputPaths.Should().BeEquivalentToPaths([ Path.Join(testOutputPath, "main file.bicep"), - Path.Join(testOutputPath, ComplexExpectedBicep_Filename3) - }); + Path.Join(testOutputPath, ComplexExpectedBicep_Filename3) + ]); result.mainBicepPath.Should().BeEquivalentToPath(Path.Join(testOutputPath, "main file.bicep")); result.errorMessage.Should().BeNull(); diff --git a/src/Bicep.LangServer.UnitTests/Handlers/BicepEditLinterRuleCommandHandlerTests.cs b/src/Bicep.LangServer.UnitTests/Handlers/BicepEditLinterRuleCommandHandlerTests.cs index ec13af7c3f9..8bab2e52d4e 100644 --- a/src/Bicep.LangServer.UnitTests/Handlers/BicepEditLinterRuleCommandHandlerTests.cs +++ b/src/Bicep.LangServer.UnitTests/Handlers/BicepEditLinterRuleCommandHandlerTests.cs @@ -413,7 +413,7 @@ public async Task IfConfigDoesNotExist_ThenCreateAndAddRuleAndSelect() server.WorkspaceMock.OnRequestWorkspaceFolders( new Container( - new WorkspaceFolder[] { new() { Name = "my workspace", Uri = DocumentUri.File(rootFolder) } })); + [new() { Name = "my workspace", Uri = DocumentUri.File(rootFolder) }])); var telemetryProvider = StrictMock.Of(); BicepTelemetryEvent? ev = null; diff --git a/src/Bicep.LangServer.UnitTests/Handlers/BicepGetRecommendedConfigLocationHandlerTests.cs b/src/Bicep.LangServer.UnitTests/Handlers/BicepGetRecommendedConfigLocationHandlerTests.cs index 0c513125b56..80f91221059 100644 --- a/src/Bicep.LangServer.UnitTests/Handlers/BicepGetRecommendedConfigLocationHandlerTests.cs +++ b/src/Bicep.LangServer.UnitTests/Handlers/BicepGetRecommendedConfigLocationHandlerTests.cs @@ -40,7 +40,7 @@ public void EmptyWorkspaceArray_ShouldBeInBicepFolder() { var bicepFilePath = Path.Join(Environment.CurrentDirectory, "main.bicep"); - var actual = BicepGetRecommendedConfigLocationHandler.GetRecommendedConfigFileLocation(new string[] { }, bicepFilePath); + var actual = BicepGetRecommendedConfigLocationHandler.GetRecommendedConfigFileLocation([], bicepFilePath); var expected = Environment.CurrentDirectory; actual.Should().Be(expected); @@ -49,10 +49,10 @@ public void EmptyWorkspaceArray_ShouldBeInBicepFolder() [TestMethod] public void SingleWorkspaceFolder_NoBicepFile_ShouldReturnFirstWorkspaceFolder() { - string[] workspaceFolders = new string[] - { + string[] workspaceFolders = + [ Environment.CurrentDirectory - }; + ]; var actual = BicepGetRecommendedConfigLocationHandler.GetRecommendedConfigFileLocation(workspaceFolders, null); var expected = workspaceFolders[0]; @@ -63,11 +63,11 @@ public void SingleWorkspaceFolder_NoBicepFile_ShouldReturnFirstWorkspaceFolder() [TestMethod] public void SingleWorkspaceFolder_CurrentFileUnsaved_ShouldReturnFirstWorkspaceFolder() { - string[] workspaceFolders = new string[] - { + string[] workspaceFolders = + [ Environment.CurrentDirectory, Environment.GetFolderPath(Environment.SpecialFolder.Desktop), - }; + ]; var actual = BicepGetRecommendedConfigLocationHandler.GetRecommendedConfigFileLocation(workspaceFolders, "Untitled-1"); var expected = Environment.CurrentDirectory; @@ -78,9 +78,7 @@ public void SingleWorkspaceFolder_CurrentFileUnsaved_ShouldReturnFirstWorkspaceF [TestMethod] public void NoWorkspaceFolder_CurrentFileUnsaved_ShouldReturnProfileFolder() { - string[] workspaceFolders = new string[] - { - }; + string[] workspaceFolders = []; var actual = BicepGetRecommendedConfigLocationHandler.GetRecommendedConfigFileLocation(workspaceFolders, "Untitled-1"); var expected = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile); diff --git a/src/Bicep.LangServer/BicepCompilationManager.cs b/src/Bicep.LangServer/BicepCompilationManager.cs index c2ffbc9c6dc..18e0a2bde25 100644 --- a/src/Bicep.LangServer/BicepCompilationManager.cs +++ b/src/Bicep.LangServer/BicepCompilationManager.cs @@ -182,7 +182,7 @@ public void CloseCompilation(DocumentUri documentUri) { // close and clear diagnostics for the file // if upsert failed to create a compilation due to a fatal error, we still need to clean up the diagnostics - CloseCompilationInternal(documentUri, 0, Enumerable.Empty()); + CloseCompilationInternal(documentUri, 0, []); } public void RefreshChangedFiles(IEnumerable files) @@ -286,7 +286,7 @@ private ImmutableArray CloseCompilationInternal(DocumentUri documen if (removedPotentiallyUnsafeContext is not CompilationContext removedContext) { - return ImmutableArray.Empty; + return []; } var closedFiles = removedContext.Compilation.SourceFileGrouping.SourceFiles.ToHashSet(); @@ -297,7 +297,7 @@ private ImmutableArray CloseCompilationInternal(DocumentUri documen workspace.RemoveSourceFiles(closedFiles); - return closedFiles.ToImmutableArray(); + return [.. closedFiles]; } private CompilationContextBase CreateCompilationContext(IWorkspace workspace, DocumentUri documentUri, ImmutableDictionary modelLookup) diff --git a/src/Bicep.LangServer/Completions/BicepCompletionContext.cs b/src/Bicep.LangServer/Completions/BicepCompletionContext.cs index f4a37d99f1c..3a21be48ec0 100644 --- a/src/Bicep.LangServer/Completions/BicepCompletionContext.cs +++ b/src/Bicep.LangServer/Completions/BicepCompletionContext.cs @@ -44,12 +44,13 @@ public record IndexedSyntaxContext(T Syntax, int ArgumentIndex) where T : Syn // completions will replace only these token types // all others will result in an insertion upon completion commit - private static readonly ImmutableHashSet ReplaceableTokens = new[] - { + private static readonly ImmutableHashSet ReplaceableTokens = + [ TokenType.Identifier, TokenType.Integer, - TokenType.StringComplete - }.Concat(LanguageConstants.Keywords.Values).ToImmutableHashSet(); + TokenType.StringComplete, + .. LanguageConstants.Keywords.Values, + ]; private BicepCompletionContext( BicepCompletionContextKind kind, @@ -148,7 +149,7 @@ public static BicepCompletionContext Create(IFeatureProvider featureProvider, Co if (previousTrivia is DisableNextLineDiagnosticsSyntaxTrivia) { - return new BicepCompletionContext(BicepCompletionContextKind.DisableNextLineDiagnosticsCodes, replacementRange, replacementTarget, null, null, null, null, null, null, null, null, null, null, null, null, null, ImmutableArray.Empty); + return new BicepCompletionContext(BicepCompletionContextKind.DisableNextLineDiagnosticsCodes, replacementRange, replacementTarget, null, null, null, null, null, null, null, null, null, null, null, null, null, []); } } break; @@ -156,18 +157,18 @@ public static BicepCompletionContext Create(IFeatureProvider featureProvider, Co // This will handle the following case: #disable-next-line | if (triviaMatchingOffset.Text.EndsWith(' ')) { - return new BicepCompletionContext(BicepCompletionContextKind.DisableNextLineDiagnosticsCodes, replacementRange, replacementTarget, null, null, null, null, null, null, null, null, null, null, null, null, null, ImmutableArray.Empty); + return new BicepCompletionContext(BicepCompletionContextKind.DisableNextLineDiagnosticsCodes, replacementRange, replacementTarget, null, null, null, null, null, null, null, null, null, null, null, null, null, []); } - return new BicepCompletionContext(BicepCompletionContextKind.None, replacementRange, replacementTarget, null, null, null, null, null, null, null, null, null, null, null, null, null, ImmutableArray.Empty); + return new BicepCompletionContext(BicepCompletionContextKind.None, replacementRange, replacementTarget, null, null, null, null, null, null, null, null, null, null, null, null, null, []); case SyntaxTriviaType.SingleLineComment when offset > triviaMatchingOffset.Span.Position: case SyntaxTriviaType.MultiLineComment when offset > triviaMatchingOffset.Span.Position && offset < triviaMatchingOffset.Span.Position + triviaMatchingOffset.Span.Length: // we're in a comment, no hints here - return new BicepCompletionContext(BicepCompletionContextKind.None, replacementRange, replacementTarget, null, null, null, null, null, null, null, null, null, null, null, null, null, ImmutableArray.Empty); + return new BicepCompletionContext(BicepCompletionContextKind.None, replacementRange, replacementTarget, null, null, null, null, null, null, null, null, null, null, null, null, null, []); } if (IsDisableNextLineDiagnosticsDirectiveStartContext(bicepFile, offset, matchingNodes)) { - return new BicepCompletionContext(BicepCompletionContextKind.DisableNextLineDiagnosticsDirectiveStart, replacementRange, replacementTarget, null, null, null, null, null, null, null, null, null, null, null, null, null, ImmutableArray.Empty); + return new BicepCompletionContext(BicepCompletionContextKind.DisableNextLineDiagnosticsDirectiveStart, replacementRange, replacementTarget, null, null, null, null, null, null, null, null, null, null, null, null, null, []); } var topLevelDeclarationInfo = SyntaxMatcher.FindLastNodeOfType(matchingNodes); @@ -1401,7 +1402,7 @@ public static ImmutableArray GetActiveScopes(FileSymbol file, in var visitor = new ActiveScopesVisitor(offset); visitor.Visit(file); - return visitor.ActiveScopes.ToImmutableArray(); + return [.. visitor.ActiveScopes]; } } } diff --git a/src/Bicep.LangServer/Completions/BicepCompletionProvider.cs b/src/Bicep.LangServer/Completions/BicepCompletionProvider.cs index db1e16e0a10..c4e5f48012e 100644 --- a/src/Bicep.LangServer/Completions/BicepCompletionProvider.cs +++ b/src/Bicep.LangServer/Completions/BicepCompletionProvider.cs @@ -122,7 +122,7 @@ private IEnumerable GetParamValueCompletions(SemanticModel param if (!paramsCompletionContext.Kind.HasFlag(BicepCompletionContextKind.ParamValue) || paramsCompletionContext.EnclosingDeclaration is not ParameterAssignmentSyntax paramAssignment) { - return Enumerable.Empty(); + return []; } var declaredType = paramsSemanticModel.GetDeclaredType(paramAssignment); @@ -241,7 +241,7 @@ private IEnumerable GetTargetScopeCompletions(SemanticModel mode { return context.Kind.HasFlag(BicepCompletionContextKind.TargetScope) && context.TargetScope is { } targetScope ? GetValueCompletionsForType(model, context, model.GetDeclaredType(targetScope), targetScope.Assignment, loopsAllowed: false) - : Enumerable.Empty(); + : []; } private IEnumerable GetSymbolCompletions(SemanticModel model, BicepCompletionContext context) @@ -249,13 +249,13 @@ private IEnumerable GetSymbolCompletions(SemanticModel model, Bi if (!context.Kind.HasFlag(BicepCompletionContextKind.Expression) && !context.Kind.HasFlag(BicepCompletionContextKind.DecoratorName)) { - return Enumerable.Empty(); + return []; } if (context.Kind.HasFlag(BicepCompletionContextKind.DecoratorName | BicepCompletionContextKind.MemberAccess)) { // This is already handled by GetMemberAccessCompletions. - return Enumerable.Empty(); + return []; } if (context.Property != null && model.GetDeclaredTypeAssignment(context.Property)?.Flags == DeclaredTypeFlags.Constant) @@ -263,7 +263,7 @@ private IEnumerable GetSymbolCompletions(SemanticModel model, Bi // the enclosing property's declared type is supposed to be a constant value // the constant flag comes from TypeProperty constant flag, so nothing else can really alter it except for another property // (in other words constant flag inherits down into the expression tree of the property value) - return Enumerable.Empty(); + return []; } // when we're inside an expression that is inside a property that expects a compile-time constant value, @@ -325,7 +325,7 @@ private IEnumerable GetDeclarationTypeCompletions(SemanticModel return completions; } - return Enumerable.Empty(); + return []; } private static IEnumerable GetTypeCompletions(SemanticModel model, BicepCompletionContext context) @@ -419,7 +419,7 @@ private static IEnumerable GetResourceTypeCompletions(SemanticMo { if (!context.Kind.HasFlag(BicepCompletionContextKind.ResourceType)) { - return Enumerable.Empty(); + return []; } // For a nested resource, we want to filter the set of types. @@ -551,8 +551,8 @@ private record FileCompletionInfo( BicepFileParentUri: cwdUri, EnteredParentUri: query, ShowCwdPrefix: entered.StartsWith("./"), - Files: files.ToImmutableArray(), - Directories: dirs.ToImmutableArray()); + Files: [.. files], + Directories: [.. dirs]); } private IEnumerable CreateFileCompletionItems(Uri mainFileUri, Range replacementRange, FileCompletionInfo info, Predicate predicate, CompletionPriority priority) @@ -610,12 +610,12 @@ private IEnumerable GetLocalModulePathCompletions(SemanticModel if (!context.Kind.HasFlag(BicepCompletionContextKind.ModulePath) && !context.Kind.HasFlag(BicepCompletionContextKind.UsingFilePath)) { - return Enumerable.Empty(); + return []; } if (IsOciArtifactRegistryReference(context)) { - return Enumerable.Empty(); + return []; } // To provide intellisense before the quotes are typed @@ -631,7 +631,7 @@ private IEnumerable GetLocalModulePathCompletions(SemanticModel // These should only fail if we're not able to resolve cwd path or the entered string if (TryGetFilesForPathCompletions(model.SourceFile.FileUri, entered) is not { } fileCompletionInfo) { - return Enumerable.Empty(); + return []; } var replacementSyntax = (context.EnclosingDeclaration as IArtifactReferenceSyntax)?.Path; @@ -646,7 +646,7 @@ private IEnumerable GetLocalModulePathCompletions(SemanticModel } catch (DirectoryNotFoundException) { - return Enumerable.Empty(); + return []; } // Local functions. @@ -687,7 +687,7 @@ private IEnumerable GetLocalTestPathCompletions(SemanticModel mo { if (!context.Kind.HasFlag(BicepCompletionContextKind.TestPath)) { - return Enumerable.Empty(); + return []; } // To provide intellisense before the quotes are typed @@ -703,7 +703,7 @@ private IEnumerable GetLocalTestPathCompletions(SemanticModel mo // These should only fail if we're not able to resolve cwd path or the entered string if (TryGetFilesForPathCompletions(model.SourceFile.FileUri, entered) is not { } fileCompletionInfo) { - return Enumerable.Empty(); + return []; } var replacementRange = context.EnclosingDeclaration is TestDeclarationSyntax test ? test.Path.ToRange(model.SourceFile.LineStarts) : context.ReplacementRange; @@ -716,7 +716,7 @@ private IEnumerable GetLocalTestPathCompletions(SemanticModel mo } catch (DirectoryNotFoundException) { - return Enumerable.Empty(); + return []; } // Local functions. @@ -765,7 +765,7 @@ private IEnumerable GetParameterDefaultValueCompletions(Semantic { if (!context.Kind.HasFlag(BicepCompletionContextKind.ParameterDefaultValue) || context.EnclosingDeclaration is not ParameterDeclarationSyntax parameter) { - return Enumerable.Empty(); + return []; } var declaredType = model.GetDeclaredType(parameter); @@ -777,7 +777,7 @@ private IEnumerable GetVariableValueCompletions(BicepCompletionC { if (!context.Kind.HasFlag(BicepCompletionContextKind.VariableValue)) { - return Enumerable.Empty(); + return []; } // we don't know what the variable type is, so assume "any" @@ -788,7 +788,7 @@ private IEnumerable GetOutputValueCompletions(SemanticModel mode { if (!context.Kind.HasFlag(BicepCompletionContextKind.OutputValue) || context.EnclosingDeclaration is not OutputDeclarationSyntax output) { - return Enumerable.Empty(); + return []; } var declaredType = model.GetDeclaredType(output); @@ -910,7 +910,7 @@ private IEnumerable GetAssertValueCompletions(SemanticModel mode { if (!context.Kind.HasFlag(BicepCompletionContextKind.AssertValue) || context.EnclosingDeclaration is not AssertDeclarationSyntax assert) { - return Enumerable.Empty(); + return []; } return GetValueCompletionsForType(model, context, LanguageConstants.Bool, assert.Value, loopsAllowed: false); @@ -1154,7 +1154,7 @@ IEnumerable GetAccessible(IEnumerable symbols, T * we don't know which kind of declaration it will attach to. */ null => knownDecoratorFunctions, - _ => Enumerable.Empty() + _ => [] }; } @@ -1162,7 +1162,7 @@ private IEnumerable GetMemberAccessCompletions(Compilation compi { if (!context.Kind.HasFlag(BicepCompletionContextKind.MemberAccess) || context.PropertyAccess == null) { - return Enumerable.Empty(); + return []; } var declaredType = compilation.GetEntrypointSemanticModel().GetDeclaredType(context.PropertyAccess.BaseExpression); @@ -1197,7 +1197,7 @@ private IEnumerable GetTypeMemberAccessCompletions(Compilation c { if (!context.Kind.HasFlag(BicepCompletionContextKind.TypeMemberAccess) || context.TypePropertyAccess is null) { - return Enumerable.Empty(); + return []; } var declaredType = compilation.GetEntrypointSemanticModel().GetDeclaredType(context.TypePropertyAccess.BaseExpression); @@ -1231,18 +1231,18 @@ private IEnumerable GetResourceAccessCompletions(Compilation com { if (!context.Kind.HasFlag(BicepCompletionContextKind.ResourceAccess) || context.ResourceAccess == null) { - return Enumerable.Empty(); + return []; } var symbol = compilation.GetEntrypointSemanticModel().GetSymbolInfo(context.ResourceAccess.BaseExpression) as ResourceSymbol; if (symbol == null) { - return Enumerable.Empty(); + return []; } var model = compilation.GetEntrypointSemanticModel(); // Find child resources - var children = symbol.DeclaringResource.TryGetBody()?.Resources ?? Enumerable.Empty(); + var children = symbol.DeclaringResource.TryGetBody()?.Resources ?? []; return children .Select(r => new { resource = r, symbol = compilation.GetEntrypointSemanticModel().GetSymbolInfo(r) as ResourceSymbol, }) .Where(entry => entry.symbol != null) @@ -1253,7 +1253,7 @@ private IEnumerable GetArrayIndexCompletions(Compilation compila { if (!context.Kind.HasFlag(BicepCompletionContextKind.ArrayIndex) || context.ArrayAccess == null) { - return Enumerable.Empty(); + return []; } var declaredType = compilation.GetEntrypointSemanticModel().GetDeclaredType(context.ArrayAccess.BaseExpression); @@ -1267,7 +1267,7 @@ private IEnumerable GetObjectPropertyNameCompletions(SemanticMod { if (context.Kind.HasFlag(BicepCompletionContextKind.ObjectPropertyName) == false || context.Object == null) { - return Enumerable.Empty(); + return []; } // in order to provide completions for property names, @@ -1275,7 +1275,7 @@ private IEnumerable GetObjectPropertyNameCompletions(SemanticMod var declaredType = model.GetDeclaredType(context.Object); if (declaredType == null) { - return Enumerable.Empty(); + return []; } var specifiedPropertyNames = context.Object.ToNamedPropertyDictionary(); @@ -1298,7 +1298,7 @@ private static IEnumerable GetProperties(TypeSymbol? type) TestType testType => GetProperties(testType.Body.Type), ObjectType objectType => objectType.Properties.Values, DiscriminatedObjectType discriminated => discriminated.DiscriminatorProperty.AsEnumerable(), - _ => Enumerable.Empty(), + _ => [], }).Where(p => !p.Flags.HasFlag(TypePropertyFlags.FallbackProperty)); } @@ -1316,7 +1316,7 @@ private static IEnumerable GetProperties(TypeSymbol? type) { ObjectType objectType => objectType.MethodResolver.GetKnownFunctions().Values, ResourceType resourceType => GetMethods(resourceType.Body.Type), - _ => Enumerable.Empty(), + _ => [], }; private static DeclaredTypeAssignment? GetDeclaredTypeAssignment(SemanticModel model, SyntaxBase? syntax) => syntax == null @@ -1327,13 +1327,13 @@ private IEnumerable GetPropertyValueCompletions(SemanticModel mo { if (!context.Kind.HasFlag(BicepCompletionContextKind.PropertyValue)) { - return Enumerable.Empty(); + return []; } var declaredTypeAssignment = GetDeclaredTypeAssignment(model, context.Property); if (declaredTypeAssignment == null) { - return Enumerable.Empty(); + return []; } var loopsAllowed = context.Property is not null && ForSyntaxValidatorVisitor.IsAddingPropertyLoopAllowed(model, context.Property); @@ -1344,13 +1344,13 @@ private IEnumerable GetArrayItemCompletions(SemanticModel model, { if (!context.Kind.HasFlag(BicepCompletionContextKind.ArrayItem) || context.Array?.Syntax is not ArraySyntax arraySyntax) { - return Enumerable.Empty(); + return []; } var declaredTypeAssignment = GetDeclaredTypeAssignment(model, arraySyntax); if (declaredTypeAssignment?.Reference.Type is not ArrayType arrayType) { - return Enumerable.Empty(); + return []; } // Special case: there is a distinction in the type system that needs to be made for resource.dependsOn resource collections @@ -1358,7 +1358,7 @@ private IEnumerable GetArrayItemCompletions(SemanticModel model, // don't provide value completions as the resource collections completions are handled by GetSymbolCompletions. if (ReferenceEquals(arrayType.Item.Type, LanguageConstants.ResourceOrResourceCollectionRefItem)) { - return Enumerable.Empty(); + return []; } return GetValueCompletionsForType(model, context, arrayType.Item.Type, arraySyntax.Items.Skip(context.Array.ArgumentIndex).FirstOrDefault(), loopsAllowed: false); @@ -1370,7 +1370,7 @@ private IEnumerable GetFunctionParamCompletions(SemanticModel mo || context.FunctionArgument is not { } functionArgument || model.GetSymbolInfo(functionArgument.Syntax) is not IFunctionSymbol functionSymbol) { - return Enumerable.Empty(); + return []; } var argType = functionSymbol.GetDeclaredArgumentType(functionArgument.ArgumentIndex); @@ -1385,7 +1385,7 @@ context.TypeArgument is not { } typeArgument || GetSymbolType(model.GetSymbolInfo(typeArgument.Syntax)) is not TypeTemplate typeTemplate || typeTemplate.Parameters.Length <= typeArgument.ArgumentIndex) { - return Enumerable.Empty(); + return []; } return typeTemplate.Parameters[typeArgument.ArgumentIndex].Type is TypeSymbol type @@ -1409,7 +1409,7 @@ private IEnumerable GetFileCompletionPaths(SemanticModel model, { if (context.FunctionArgument is not { } functionArgument || !argType.ValidationFlags.HasFlag(TypeSymbolValidationFlags.IsStringFilePath)) { - return Enumerable.Empty(); + return []; } //try get entered text. we need to provide path completions when something else than string is entered and in that case we use the token value to get what's currently entered @@ -1419,7 +1419,7 @@ private IEnumerable GetFileCompletionPaths(SemanticModel model, // These should only fail if we're not able to resolve cwd path or the entered string if (TryGetFilesForPathCompletions(model.SourceFile.FileUri, entered) is not { } fileCompletionInfo) { - return Enumerable.Empty(); + return []; } IEnumerable fileItems; @@ -1617,7 +1617,7 @@ private IEnumerable GetDiagnosticCodes(Range range, SemanticModel m if (nextLineSpan.IsNil) { - return Enumerable.Empty(); + return []; } return model.GetAllDiagnostics() diff --git a/src/Bicep.LangServer/Completions/ModuleReferenceCompletionProvider.cs b/src/Bicep.LangServer/Completions/ModuleReferenceCompletionProvider.cs index 4989cb71e04..60d716f7804 100644 --- a/src/Bicep.LangServer/Completions/ModuleReferenceCompletionProvider.cs +++ b/src/Bicep.LangServer/Completions/ModuleReferenceCompletionProvider.cs @@ -84,12 +84,12 @@ private IEnumerable GetTopLevelCompletions(BicepCompletionContex if (!context.Kind.HasFlag(BicepCompletionContextKind.ModulePath) && !context.Kind.HasFlag(BicepCompletionContextKind.UsingFilePath)) { - return Enumerable.Empty(); + return []; } if (!string.IsNullOrWhiteSpace(replacementText.Trim('\''))) { - return Enumerable.Empty(); + return []; } List completionItems = new(); @@ -180,7 +180,7 @@ private async Task> GetMCRModuleRegistryVersionCompl { if (!IsOciArtifactRegistryReference(replacementText)) { - return Enumerable.Empty(); + return []; } string? modulePath; @@ -202,7 +202,7 @@ private async Task> GetMCRModuleRegistryVersionCompl if (modulePath is null) { - return Enumerable.Empty(); + return []; } List completions = new(); @@ -292,7 +292,7 @@ private async Task> GetOciModulePathCompletions(Bice { if (!IsOciArtifactRegistryReference(replacementText)) { - return Enumerable.Empty(); + return []; } if (replacementText == "'br/public:'" || diff --git a/src/Bicep.LangServer/Completions/PublicRegistryModuleMetadataClient.cs b/src/Bicep.LangServer/Completions/PublicRegistryModuleMetadataClient.cs index 73590dd5175..9a186da6775 100644 --- a/src/Bicep.LangServer/Completions/PublicRegistryModuleMetadataClient.cs +++ b/src/Bicep.LangServer/Completions/PublicRegistryModuleMetadataClient.cs @@ -34,7 +34,7 @@ public async Task> GetModuleMetadata() if (metadata is not null) { Trace.WriteLine($"{nameof(PublicRegistryModuleMetadataProvider)}: Retrieved info on {metadata.Length} public registry modules."); - return metadata.ToImmutableArray(); + return [.. metadata]; } else { diff --git a/src/Bicep.LangServer/Completions/PublicRegistryModuleMetadataProvider.cs b/src/Bicep.LangServer/Completions/PublicRegistryModuleMetadataProvider.cs index 592fd72daa3..b012cdcb218 100644 --- a/src/Bicep.LangServer/Completions/PublicRegistryModuleMetadataProvider.cs +++ b/src/Bicep.LangServer/Completions/PublicRegistryModuleMetadataProvider.cs @@ -23,7 +23,7 @@ public class PublicRegistryModuleMetadataProvider : IPublicRegistryModuleMetadat private readonly object queryingLiveSyncObject = new(); - private ImmutableArray cachedModules = ImmutableArray.Empty; + private ImmutableArray cachedModules = []; private bool isQueryingLiveData = false; diff --git a/src/Bicep.LangServer/Completions/SyntaxPatterns/SyntaxPattern.cs b/src/Bicep.LangServer/Completions/SyntaxPatterns/SyntaxPattern.cs index c181bbfe5a5..8ee9ef0ace8 100644 --- a/src/Bicep.LangServer/Completions/SyntaxPatterns/SyntaxPattern.cs +++ b/src/Bicep.LangServer/Completions/SyntaxPatterns/SyntaxPattern.cs @@ -69,7 +69,7 @@ public bool TailMatch(ImmutableArray nodes) var (leftSiblings, overlappingNode) = LeftSiblingsCollector.CollectLeftSiblings(ancestors[^1], offset); // pattern nodes = ancestors + left siblings + overlapping node. - return ancestors.Concat(leftSiblings).Append(overlappingNode).ToImmutableArray(); + return [.. ancestors, .. leftSiblings, overlappingNode]; } private static (string text, int offset) ProcessTextWithCursor(char cursor, string textWithCursor) diff --git a/src/Bicep.LangServer/Deploy/DeploymentParametersHelper.cs b/src/Bicep.LangServer/Deploy/DeploymentParametersHelper.cs index 7106e929a57..1345e579c0b 100644 --- a/src/Bicep.LangServer/Deploy/DeploymentParametersHelper.cs +++ b/src/Bicep.LangServer/Deploy/DeploymentParametersHelper.cs @@ -85,7 +85,7 @@ public static string GetUpdatedParametersFileContents( updatedDeploymentParameter.value, JObject.Parse("{}")); - (int line, int column, string text)? insertion = jsonEditor.InsertIfNotExist(propertyPaths.ToArray(), valueObject); + (int line, int column, string text)? insertion = jsonEditor.InsertIfNotExist([.. propertyPaths], valueObject); if (insertion.HasValue) { diff --git a/src/Bicep.LangServer/Handlers/BicepDecompileCommandHandler.cs b/src/Bicep.LangServer/Handlers/BicepDecompileCommandHandler.cs index 0256bbad768..692e603b93b 100644 --- a/src/Bicep.LangServer/Handlers/BicepDecompileCommandHandler.cs +++ b/src/Bicep.LangServer/Handlers/BicepDecompileCommandHandler.cs @@ -54,7 +54,7 @@ public BicepDecompileCommandResult( string decompileId, string output, string? errorMessage - ) : this(decompileId, output, errorMessage, null, new DecompiledFile[] { }, new string[] { }) + ) : this(decompileId, output, errorMessage, null, [], []) { } @@ -137,7 +137,7 @@ public override Task Handle(BicepDecompileCommandPa (string path, string content)[] pathsToSave = filesToSave.Select(kvp => (kvp.Key.LocalPath, kvp.Value)).ToArray(); // Put main bicep file first in the array - pathsToSave = pathsToSave.OrderByAscending(f => f.path == bicepUri.LocalPath ? "" : f.path).ToArray(); + pathsToSave = [.. pathsToSave.OrderByAscending(f => f.path == bicepUri.LocalPath ? "" : f.path)]; Debug.Assert(pathsToSave[0].path == bicepUri.LocalPath, "Expected Bicep URL to be in the files to save"); Debug.Assert(pathsToSave.Length >= 1, "No files to save?"); diff --git a/src/Bicep.LangServer/Handlers/BicepDecompileSaveCommandHandler.cs b/src/Bicep.LangServer/Handlers/BicepDecompileSaveCommandHandler.cs index d45a4206ff2..28a0529844e 100644 --- a/src/Bicep.LangServer/Handlers/BicepDecompileSaveCommandHandler.cs +++ b/src/Bicep.LangServer/Handlers/BicepDecompileSaveCommandHandler.cs @@ -121,7 +121,7 @@ await this.languageServerFacade.Window.ShowDocument( output.ToString(), ex.Message, null, - new string[] { }) + []) ); } } @@ -139,7 +139,7 @@ await this.languageServerFacade.Window.ShowDocument( { // Create a bicep file with unique name alongside the existing bicep file string newBicepPath = FindUniqueFileOrFolderName(outputFolder, mainBicepPath); - return new[] { (newBicepPath, outputFiles[0].bicepContents) }; + return [(newBicepPath, outputFiles[0].bicepContents)]; } else { @@ -154,7 +154,7 @@ await this.languageServerFacade.Window.ShowDocument( newOutputFiles.Add((newPath, outputFile.bicepContents)); } - return newOutputFiles.ToArray(); + return [.. newOutputFiles]; } } diff --git a/src/Bicep.LangServer/Handlers/BicepDeploymentParametersHandler.cs b/src/Bicep.LangServer/Handlers/BicepDeploymentParametersHandler.cs index 0d3a997b53e..bbf94576465 100644 --- a/src/Bicep.LangServer/Handlers/BicepDeploymentParametersHandler.cs +++ b/src/Bicep.LangServer/Handlers/BicepDeploymentParametersHandler.cs @@ -210,7 +210,7 @@ private IEnumerable GetParameterSymbols(string documentPath) if (compilation is null) { - return Enumerable.Empty(); + return []; } var semanticModel = compilation.GetEntrypointSemanticModel(); diff --git a/src/Bicep.LangServer/Handlers/BicepEditLinterRuleCommandHandler.cs b/src/Bicep.LangServer/Handlers/BicepEditLinterRuleCommandHandler.cs index 4aa92e46de4..edeca1b2bc4 100644 --- a/src/Bicep.LangServer/Handlers/BicepEditLinterRuleCommandHandler.cs +++ b/src/Bicep.LangServer/Handlers/BicepEditLinterRuleCommandHandler.cs @@ -99,7 +99,7 @@ public static async Task AddAndSelectRuleLevel(ILanguageServerFacade serve string json = File.ReadAllText(bicepConfigFilePath); (int line, int column, string text)? insertion = new JsonEditor(json).InsertIfNotExist( - new string[] { "analyzers", "core", "rules", ruleCode, "level" }, + ["analyzers", "core", "rules", ruleCode, "level"], "warning"); bool added = false; diff --git a/src/Bicep.LangServer/Handlers/ImportKubernetesManifestHandler.cs b/src/Bicep.LangServer/Handlers/ImportKubernetesManifestHandler.cs index e1de4abf7d8..3dc8943981d 100644 --- a/src/Bicep.LangServer/Handlers/ImportKubernetesManifestHandler.cs +++ b/src/Bicep.LangServer/Handlers/ImportKubernetesManifestHandler.cs @@ -143,7 +143,7 @@ private static ResourceDeclarationSyntax ProcessResourceYaml(YamlDocument yamlDo var symbolName = GetResourceSymbolName(type, resourceBody); return new ResourceDeclarationSyntax( - Enumerable.Empty(), + [], SyntaxFactory.ResourceKeywordToken, SyntaxFactory.CreateIdentifierWithTrailingSpace(symbolName), SyntaxFactory.CreateStringLiteral($"{type}@{apiVersion}"), diff --git a/src/Bicep.LangServer/Handlers/LocalDeployHandler.cs b/src/Bicep.LangServer/Handlers/LocalDeployHandler.cs index a734b274277..2334c5bc602 100644 --- a/src/Bicep.LangServer/Handlers/LocalDeployHandler.cs +++ b/src/Bicep.LangServer/Handlers/LocalDeployHandler.cs @@ -2,8 +2,6 @@ // Licensed under the MIT License. using System.Collections.Immutable; -using Bicep.Local.Deploy; -using Bicep.Local.Deploy.Extensibility; using Azure.Deployments.Core.Definitions; using Azure.Deployments.Core.ErrorResponses; using Bicep.Core.Extensions; @@ -11,6 +9,8 @@ using Bicep.Core.Semantics; using Bicep.Core.TypeSystem.Types; using Bicep.LanguageServer.CompilationManager; +using Bicep.Local.Deploy; +using Bicep.Local.Deploy.Extensibility; using MediatR; using Microsoft.WindowsAzure.ResourceStack.Common.Json; using Newtonsoft.Json.Linq; @@ -75,8 +75,8 @@ public async Task Handle(LocalDeployRequest request, Cancel } var parameters = context.Compilation.Emitter.Parameters(); - if (parameters.Parameters is not {} parametersString || - parameters.Template?.Template is not {} templateString) + if (parameters.Parameters is not { } parametersString || + parameters.Template?.Template is not { } templateString) { throw new InvalidOperationException("Bicep file had errors."); } @@ -93,7 +93,7 @@ public async Task Handle(LocalDeployRequest request, Cancel server.Window.LogError($"Unhandled exception during local deployment: {ex}"); return new( new("Failed", ImmutableDictionary.Empty, new("UnhandledException", ex.Message, "")), - ImmutableArray.Empty + [] ); } } @@ -102,7 +102,7 @@ private static LocalDeploymentOperationContent FromOperation(DeploymentOperation { var result = operation.Properties.StatusMessage.TryFromJToken(); var error = result?.Error?.Message.TryFromJson()?.Error; - var operationError = error is {} ? new LocalDeploymentOperationError(error.Code, error.Message, error.Target) : null; + var operationError = error is { } ? new LocalDeploymentOperationError(error.Code, error.Message, error.Target) : null; return new LocalDeploymentOperationContent( operation.Properties.TargetResource.SymbolicName, @@ -112,7 +112,7 @@ private static LocalDeploymentOperationContent FromOperation(DeploymentOperation private static LocalDeployResponse FromResult(LocalDeployment.Result result) { - var deployError = result.Deployment.Properties.Error is {} error ? + var deployError = result.Deployment.Properties.Error is { } error ? new LocalDeploymentOperationError(error.Code, error.Message, error.Target) : null; @@ -125,4 +125,4 @@ private static LocalDeployResponse FromResult(LocalDeployment.Result result) return new(deployment, operations); } -} \ No newline at end of file +} diff --git a/src/Bicep.LangServer/Snippets/Snippet.cs b/src/Bicep.LangServer/Snippets/Snippet.cs index 684633ddb46..aa9d70f35af 100644 --- a/src/Bicep.LangServer/Snippets/Snippet.cs +++ b/src/Bicep.LangServer/Snippets/Snippet.cs @@ -26,10 +26,13 @@ public Snippet(string text, CompletionPriority completionPriority = CompletionPr this.Prefix = prefix; this.Detail = detail; this.CompletionPriority = completionPriority; - this.Placeholders = matches - .Select(CreatePlaceholder) - .OrderBy(p => p.Index) - .ToImmutableArray(); + this.Placeholders = + [ + .. matches + .Select(CreatePlaceholder) + .OrderBy(p => p.Index) +, + ]; } public string Prefix { get; } diff --git a/src/Bicep.LangServer/Snippets/SnippetCacheBuilder.cs b/src/Bicep.LangServer/Snippets/SnippetCacheBuilder.cs index e855c0d15f2..e3ec1adac7b 100644 --- a/src/Bicep.LangServer/Snippets/SnippetCacheBuilder.cs +++ b/src/Bicep.LangServer/Snippets/SnippetCacheBuilder.cs @@ -69,7 +69,7 @@ public async Task Build() resourceTypeReferenceInfoMap.ToImmutableDictionary(), resourceTypeReferenceToDependentsMap.ToImmutableDictionary(), resourceTypeReferenceToChildTypeSymbolsMap.ToImmutableDictionary(k => k.Key, k => k.Value.OrderBy(r => r.ToString()).ToImmutableArray()), - topLevelNamedDeclarationSnippets.ToImmutableArray()); + [.. topLevelNamedDeclarationSnippets]); } public async Task<(string description, string snippet)> GetDescriptionAndSnippetText(string template, string manifestResourceName) @@ -153,7 +153,7 @@ private void CacheResourceDependencies(ResourceTypeReference childResourceTypeRe { resourceTypeReferenceToChildTypeSymbolsMap.AddOrUpdate( resourceTypeReference, - _ => ImmutableArray.Create(childResourceTypeReference), + _ => [childResourceTypeReference], (_, children) => children.Add(childResourceTypeReference)); } diff --git a/src/Bicep.LangServer/Snippets/SnippetsProvider.cs b/src/Bicep.LangServer/Snippets/SnippetsProvider.cs index 001dfd5a0ca..08edb23f5e4 100644 --- a/src/Bicep.LangServer/Snippets/SnippetsProvider.cs +++ b/src/Bicep.LangServer/Snippets/SnippetsProvider.cs @@ -25,20 +25,7 @@ public class SnippetsProvider : ISnippetsProvider // The common properties should be authored consistently to provide for understandability and consumption of the code. // See https://github.com/Azure/azure-quickstart-templates/blob/master/1-CONTRIBUTION-GUIDE/best-practices.md#resources // for more information - private readonly ImmutableArray propertiesSortPreferenceList = ImmutableArray.Create( - "scope", - "parent", - "name", - "location", - "zones", - "sku", - "kind", - "scale", - "plan", - "identity", - "tags", - "properties", - "dependsOn"); + private readonly ImmutableArray propertiesSortPreferenceList = ["scope", "parent", "name", "location", "zones", "sku", "kind", "scale", "plan", "identity", "tags", "properties", "dependsOn"]; private static readonly SnippetCache snippetCache = SnippetCache.FromManifest(); @@ -122,7 +109,7 @@ private IEnumerable GetRequiredPropertiesSnippetsForDisciminatedObjectT foreach (var kvp in discriminatedObjectType.UnionMembersByKey.OrderBy(x => x.Key)) { string disciminatedObjectKey = kvp.Key; - string label = "required-properties-" + disciminatedObjectKey.Trim(new char[] { '\'' }); + string label = "required-properties-" + disciminatedObjectKey.Trim(['\'']); Snippet? snippet = GetRequiredPropertiesSnippet(kvp.Value, label, disciminatedObjectKey); if (snippet is not null) diff --git a/src/Bicep.LangServer/Telemetry/TelemetryHelper.cs b/src/Bicep.LangServer/Telemetry/TelemetryHelper.cs index 57670ffd1ed..b29fcf02e57 100644 --- a/src/Bicep.LangServer/Telemetry/TelemetryHelper.cs +++ b/src/Bicep.LangServer/Telemetry/TelemetryHelper.cs @@ -27,7 +27,7 @@ public static IEnumerable GetTelemetryEventsForBicepConfigC if (!prevLinterEnabledSettingValue && !curLinterEnabledSettingValue) { - return Enumerable.Empty(); + return []; } List telemetryEvents = new(); diff --git a/src/Bicep.LangServer/Utils/DocumentSelectorFactory.cs b/src/Bicep.LangServer/Utils/DocumentSelectorFactory.cs index dc1845c4174..5489a5764e7 100644 --- a/src/Bicep.LangServer/Utils/DocumentSelectorFactory.cs +++ b/src/Bicep.LangServer/Utils/DocumentSelectorFactory.cs @@ -7,18 +7,18 @@ namespace Bicep.LanguageServer.Utils { public class DocumentSelectorFactory { - public static readonly TextDocumentFilter[] BicepAndParams = { + public static readonly TextDocumentFilter[] BicepAndParams = [ TextDocumentFilter.ForLanguage(LanguageConstants.LanguageId), TextDocumentFilter.ForLanguage(LanguageConstants.ParamsLanguageId) - }; + ]; - public static readonly TextDocumentFilter[] AllSupportedLangIds = { + public static readonly TextDocumentFilter[] AllSupportedLangIds = [ TextDocumentFilter.ForLanguage(LanguageConstants.LanguageId), - TextDocumentFilter.ForLanguage(LanguageConstants.ParamsLanguageId), - TextDocumentFilter.ForLanguage(LanguageConstants.JsoncLanguageId), - TextDocumentFilter.ForLanguage(LanguageConstants.JsonLanguageId), - TextDocumentFilter.ForLanguage(LanguageConstants.ArmTemplateLanguageId) - }; + TextDocumentFilter.ForLanguage(LanguageConstants.ParamsLanguageId), + TextDocumentFilter.ForLanguage(LanguageConstants.JsoncLanguageId), + TextDocumentFilter.ForLanguage(LanguageConstants.JsonLanguageId), + TextDocumentFilter.ForLanguage(LanguageConstants.ArmTemplateLanguageId) + ]; public static TextDocumentSelector CreateForBicepAndParams() => new(BicepAndParams); public static TextDocumentSelector CreateForAllSupportedLangIds() => new(AllSupportedLangIds); diff --git a/src/Bicep.Local.Deploy/LocalDeploymentSettings.cs b/src/Bicep.Local.Deploy/LocalDeploymentSettings.cs index bd216ed4a30..27916d594fc 100644 --- a/src/Bicep.Local.Deploy/LocalDeploymentSettings.cs +++ b/src/Bicep.Local.Deploy/LocalDeploymentSettings.cs @@ -28,10 +28,10 @@ public class LocalDeploymentSettings : IAzureDeploymentSettings public string? RemotePdpAadResource { get; set; } - public string[] DeploymentFrontdoorLocationEnabledSubscriptions { get; } = new string[] { }; + public string[] DeploymentFrontdoorLocationEnabledSubscriptions { get; } = []; - public string[] AllowedApiVersions { get; set; } = new string[] - { + public string[] AllowedApiVersions { get; set; } = + [ "2022-09-01", "2022-06-01", "2022-01-01", @@ -79,7 +79,7 @@ public class LocalDeploymentSettings : IAzureDeploymentSettings "2013-03-01", "2014-02-26", "2014-04" - }; + ]; public int DeploymentNameLengthLimit { get; set; } = 64; @@ -107,13 +107,13 @@ public class LocalDeploymentSettings : IAzureDeploymentSettings public int MaxTagsSizePerResourceInBytes { get; set; } = 24576; - public string[] ReservedTagKeyPrefixes { get; set; } = new string[] { "microsoft", "azure", "windows" }; + public string[] ReservedTagKeyPrefixes { get; set; } = ["microsoft", "azure", "windows"]; - public string[] ProtectedTagKeyPrefixes { get; set; } = new string[] { "hidden", "link" }; + public string[] ProtectedTagKeyPrefixes { get; set; } = ["hidden", "link"]; - public string[] ReservedTagValues { get; set; } = new string[] { "null", "(null)" }; + public string[] ReservedTagValues { get; set; } = ["null", "(null)"]; - public string[] AsyncOperationCallbackAllowedProviders { get; set; } = new string[] { }; + public string[] AsyncOperationCallbackAllowedProviders { get; set; } = []; public TimeSpan ResourceMaximumRetryInterval { get; set; } = TimeSpan.FromMinutes(10); @@ -133,7 +133,7 @@ public class LocalDeploymentSettings : IAzureDeploymentSettings public int ExtensibleResourceUnhandledExceptionRetryCount { get; set; } = 5; - public string[] AllowedProvidersForHeaderBasedOperationTimeout { get; set; } = new string[] { }; + public string[] AllowedProvidersForHeaderBasedOperationTimeout { get; set; } = []; public int ResourceGroupNameLengthLimit { get; set; } = 90; @@ -157,11 +157,11 @@ public class LocalDeploymentSettings : IAzureDeploymentSettings public double WhatIfLiveTrafficValidationPercentage { get; set; } = 0.2; - public string[] WhatIfLiveTrafficValidationApplicationWhitelist { get; set; } = new string[] { }; + public string[] WhatIfLiveTrafficValidationApplicationWhitelist { get; set; } = []; - public string[] WhatIfLiveTrafficValidationTenantBlacklist { get; set; } = new string[] { }; + public string[] WhatIfLiveTrafficValidationTenantBlacklist { get; set; } = []; - public string[] WhatIfLiveTrafficValidationSubscriptionBlacklist { get; set; } = new string[] { }; + public string[] WhatIfLiveTrafficValidationSubscriptionBlacklist { get; set; } = []; public string DefaultFrontdoorEndpoint { get; set; } = "localhost"; @@ -179,7 +179,7 @@ public class LocalDeploymentSettings : IAzureDeploymentSettings public int ResourceValidationRequestSynchronousLimit { get; set; } = 10; - public KeyValuePair[] BlacklistedDeploymentParameters { get; set; } = new KeyValuePair[] { }; + public KeyValuePair[] BlacklistedDeploymentParameters { get; set; } = []; public TimeSpan DeploymentJobTimeout { get; set; } = TimeSpan.FromSeconds(60); @@ -197,22 +197,22 @@ public class LocalDeploymentSettings : IAzureDeploymentSettings public TimeSpan PreflightJobMaximumRetryInterval { get; set; } = TimeSpan.FromMinutes(value: 2); - public string[] PreviewFunctionalityPermittedTenants { get; set; } = new string[] { }; + public string[] PreviewFunctionalityPermittedTenants { get; set; } = []; - public string[] PreviewFunctionalityDisabledFeatures { get; set; } = new string[] { }; + public string[] PreviewFunctionalityDisabledFeatures { get; set; } = []; - public string[] PreviewFunctionalityExternalPermittedTenants { get; set; } = new string[] { }; + public string[] PreviewFunctionalityExternalPermittedTenants { get; set; } = []; - public string[] PreviewFunctionalityPublicFeatures { get; set; } = new string[] { + public string[] PreviewFunctionalityPublicFeatures { get; set; } = [ "ResourceGroupGrooming", - "ScopeEscaping", - "WhatIfInlineNestedResourcesNormalization", - "SubscriptionGrooming", - "WhatIfKeyVaultAccessPolicyOperationsNormalization", - "TenantLevelGrooming", - "ExtensibleResources", - "ExpandDeploymentsMetadata" - }; + "ScopeEscaping", + "WhatIfInlineNestedResourcesNormalization", + "SubscriptionGrooming", + "WhatIfKeyVaultAccessPolicyOperationsNormalization", + "TenantLevelGrooming", + "ExtensibleResources", + "ExpandDeploymentsMetadata" + ]; public IReadOnlyDictionary> PreviewFeatureSubscriptionsDictionary { get; set; } = new Dictionary>(); public IReadOnlyDictionary> PreviewFeatureTenantDictionary { get; set; } = new Dictionary>(); @@ -223,18 +223,18 @@ public class LocalDeploymentSettings : IAzureDeploymentSettings public IReadOnlyDictionary> DisabledRegionDictionary { get; set; } = new Dictionary>(); public IEnumerable DisabledThresholdFeatures { get; set; } = []; - public string[] AllowedLocations => new string[] { "local", "west us", "east us" }; + public string[] AllowedLocations => ["local", "west us", "east us"]; public TimeSpan WhatIfJobMinimumRetryInterval { get; set; } = TimeSpan.FromSeconds(15); public TimeSpan WhatIfJobMaximumRetryInterval { get; set; } = TimeSpan.FromMinutes(5); - public string[] StorageAccountHostNameMappings { get; set; } = new[] - { + public string[] StorageAccountHostNameMappings { get; set; } = + [ ".blob.core.windows.net", ".table.core.windows.net", ".queue.core.windows.net", - }; + ]; public TimeSpan CleanupJobRetryInterval { get; set; } = TimeSpan.FromMinutes(1); diff --git a/src/Bicep.RegistryModuleTool.IntegrationTests/Commands/GenerateCommandTests.cs b/src/Bicep.RegistryModuleTool.IntegrationTests/Commands/GenerateCommandTests.cs index 8d2409522d8..d9d1a4f7741 100644 --- a/src/Bicep.RegistryModuleTool.IntegrationTests/Commands/GenerateCommandTests.cs +++ b/src/Bicep.RegistryModuleTool.IntegrationTests/Commands/GenerateCommandTests.cs @@ -92,11 +92,11 @@ private static IEnumerable GetSuccessData() yield return CreateTestCase(Sample.Modified, Sample.Valid); yield return CreateTestCase(Sample.Modified_Experimental, Sample.Valid_Experimental); - static object[] CreateTestCase(Sample before, Sample after) => new object[] - { + static object[] CreateTestCase(Sample before, Sample after) => + [ MockFileSystemFactory.CreateForSample(before), MockFileSystemFactory.CreateForSample(after), - }; + ]; } private static GenerateCommand CreateGenerateCommand(IFileSystem fileSystem) diff --git a/src/Bicep.RegistryModuleTool.TestFixtures/Samples/Sample.cs b/src/Bicep.RegistryModuleTool.TestFixtures/Samples/Sample.cs index af79fa714ee..bcd6cb89353 100644 --- a/src/Bicep.RegistryModuleTool.TestFixtures/Samples/Sample.cs +++ b/src/Bicep.RegistryModuleTool.TestFixtures/Samples/Sample.cs @@ -17,7 +17,7 @@ public Sample(IEnumerable<(string, string)> resources) this.resources = resources; } - public static Sample Empty { get; } = new(Enumerable.Empty<(string, string)>()); + public static Sample Empty { get; } = new([]); public static Sample NewlyGenerated { get; } = LoadSample(); diff --git a/src/Bicep.RegistryModuleTool.UnitTests/Extensions/ITypeReferenceExtensionsTests.cs b/src/Bicep.RegistryModuleTool.UnitTests/Extensions/ITypeReferenceExtensionsTests.cs index 91dbb3959d4..f3f323547ed 100644 --- a/src/Bicep.RegistryModuleTool.UnitTests/Extensions/ITypeReferenceExtensionsTests.cs +++ b/src/Bicep.RegistryModuleTool.UnitTests/Extensions/ITypeReferenceExtensionsTests.cs @@ -38,30 +38,31 @@ private static IEnumerable GetTestData() yield return CreateTestCase(TypeFactory.CreateBooleanLiteralType(true), LanguageConstants.Bool.Name); yield return CreateTestCase(TypeFactory.CreateStringLiteralType("foobar"), LanguageConstants.String.Name); - var tupleType = new TupleType(ImmutableArray.Create(LanguageConstants.Int, LanguageConstants.Bool), TypeSymbolValidationFlags.Default); + var tupleType = new TupleType([LanguageConstants.Int, LanguageConstants.Bool], TypeSymbolValidationFlags.Default); yield return CreateTestCase(tupleType, LanguageConstants.ArrayType); - var discriminatedObjectType = new DiscriminatedObjectType("", TypeSymbolValidationFlags.Default, "", Enumerable.Empty()); + var discriminatedObjectType = new DiscriminatedObjectType("", TypeSymbolValidationFlags.Default, "", []); yield return CreateTestCase(discriminatedObjectType, LanguageConstants.ObjectType); var unionType = new UnionType( "int | bool | object | array", - ImmutableArray.Create( + [ LanguageConstants.Int, TypeFactory.CreateIntegerLiteralType(0), TypeFactory.CreateBooleanLiteralType(false), LanguageConstants.Object, discriminatedObjectType, tupleType, - LanguageConstants.Array)); + LanguageConstants.Array, + ]); yield return CreateTestCase(unionType, unionType.Name); - static object[] CreateTestCase(ITypeReference typeReference, string expectedPrimitiveTypeName) => new object[] - { + static object[] CreateTestCase(ITypeReference typeReference, string expectedPrimitiveTypeName) => + [ typeReference, expectedPrimitiveTypeName, - }; + ]; } } } diff --git a/src/Bicep.RegistryModuleTool/Commands/BaseCommandHandler.cs b/src/Bicep.RegistryModuleTool/Commands/BaseCommandHandler.cs index 6dec05796a2..f391753d43d 100644 --- a/src/Bicep.RegistryModuleTool/Commands/BaseCommandHandler.cs +++ b/src/Bicep.RegistryModuleTool/Commands/BaseCommandHandler.cs @@ -104,7 +104,7 @@ private string GetModulePath(string directoryPath) throw new BicepException(exception.Message, exception); } - var modulePath = string.Join(this.FileSystem.Path.DirectorySeparatorChar, directoryStack.ToArray()); + var modulePath = string.Join(this.FileSystem.Path.DirectorySeparatorChar, [.. directoryStack]); return modulePath; } diff --git a/src/Bicep.RegistryModuleTool/ModuleFileValidators/TestValidator.cs b/src/Bicep.RegistryModuleTool/ModuleFileValidators/TestValidator.cs index b91e55728cd..805301fd879 100644 --- a/src/Bicep.RegistryModuleTool/ModuleFileValidators/TestValidator.cs +++ b/src/Bicep.RegistryModuleTool/ModuleFileValidators/TestValidator.cs @@ -40,7 +40,7 @@ public async Task> ValidateAsync(MainBicepTestFile file) return NoTestError(); } - return Enumerable.Empty(); + return []; } private static IEnumerable NoTestError() diff --git a/src/Bicep.Wasm/EmptyModuleRegistryProvider.cs b/src/Bicep.Wasm/EmptyModuleRegistryProvider.cs index ce529445c67..44dd6bfcc44 100644 --- a/src/Bicep.Wasm/EmptyModuleRegistryProvider.cs +++ b/src/Bicep.Wasm/EmptyModuleRegistryProvider.cs @@ -8,6 +8,6 @@ namespace Bicep.Wasm { public class EmptyModuleRegistryProvider : IArtifactRegistryProvider { - public ImmutableArray Registries(Uri _) => ImmutableArray.Empty; + public ImmutableArray Registries(Uri _) => []; } }