diff --git a/.editorconfig b/.editorconfig index b59760c3f90..9e27c427bc7 100644 --- a/.editorconfig +++ b/.editorconfig @@ -37,6 +37,19 @@ dotnet_diagnostic.IDE0005.severity = none # Private member is unused dotnet_diagnostic.IDE0051.severity = warning +# Use collection expression for array +dotnet_diagnostic.IDE0300.severity = warning +# Use collection expression for empty +dotnet_diagnostic.IDE0301.severity = warning +# Use collection expression for stackalloc +dotnet_diagnostic.IDE0302.severity = warning +# Use collection expression for `Create() +dotnet_diagnostic.IDE0303.severity = warning +# Use collection expression for builder +dotnet_diagnostic.IDE0304.severity = warning +# Use collection expression for fluent +dotnet_diagnostic.IDE0305.severity = warning + # Unused local variables dotnet_diagnostic.CA1804.severity = warning # Private methods that are not called from any other code 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.IntegrationTests/RestoreCommandTests.cs b/src/Bicep.Cli.IntegrationTests/RestoreCommandTests.cs index 6c0c5b12b27..78d685b1f7a 100644 --- a/src/Bicep.Cli.IntegrationTests/RestoreCommandTests.cs +++ b/src/Bicep.Cli.IntegrationTests/RestoreCommandTests.cs @@ -177,7 +177,7 @@ public async Task Restore_Artifacts_BackwardsAndForwardsCompatibility(string? me mediaType, artifactType, configContents, - new (string, string)[] { (BicepMediaTypes.BicepModuleLayerV1Json, "data") }); + [(BicepMediaTypes.BicepModuleLayerV1Json, "data")]); client.Blobs.Should().HaveCount(2); client.Manifests.Should().HaveCount(1); 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..953da4868c6 100644 --- a/src/Bicep.Cli/Helpers/ParamsFileHelper.cs +++ b/src/Bicep.Cli/Helpers/ParamsFileHelper.cs @@ -12,7 +12,16 @@ 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/Logging/DiagnosticLogger.cs b/src/Bicep.Cli/Logging/DiagnosticLogger.cs index f2e8adfb450..f31e5c3ff7e 100644 --- a/src/Bicep.Cli/Logging/DiagnosticLogger.cs +++ b/src/Bicep.Cli/Logging/DiagnosticLogger.cs @@ -92,7 +92,7 @@ private static void LogSarifDiagnostics(TextWriter writer, ImmutableDictionary 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/AssertTests.cs b/src/Bicep.Core.IntegrationTests/AssertTests.cs index 18c3f0efb68..fd9aaab0181 100644 --- a/src/Bicep.Core.IntegrationTests/AssertTests.cs +++ b/src/Bicep.Core.IntegrationTests/AssertTests.cs @@ -46,9 +46,9 @@ param appServicePlanSku object var result = CompilationHelper.Compile(services, fileContent); - result.Should().HaveDiagnostics(new[] { + result.Should().HaveDiagnostics([ ("BCP349", DiagnosticLevel.Error, "Using an assert declaration requires enabling EXPERIMENTAL feature \"Assertions\".") - }); + ]); result = CompilationHelper.Compile(ServicesWithAsserts, fileContent); @@ -58,9 +58,9 @@ param appServicePlanSku object assert a1 = true """); - result.Should().HaveDiagnostics(new[] { + result.Should().HaveDiagnostics([ ("BCP349", DiagnosticLevel.Error, "Using an assert declaration requires enabling EXPERIMENTAL feature \"Assertions\".") - }); + ]); result = CompilationHelper.Compile(ServicesWithAsserts, """ assert a1 = true @@ -98,9 +98,9 @@ param location string } } """); - result.Should().HaveDiagnostics(new[] { + result.Should().HaveDiagnostics([ ("BCP018", DiagnosticLevel.Error, "Expected the \":\" character at this location."), - }); + ]); result = CompilationHelper.Compile(ServicesWithAsserts, """ param location string @@ -118,30 +118,30 @@ param location string } } """); - result.Should().HaveDiagnostics(new[] { + result.Should().HaveDiagnostics([ ("BCP009", DiagnosticLevel.Error, "Expected a literal value, an array, an object, a parenthesized expression, or a function call at this location."), - }); + ]); result = CompilationHelper.Compile(ServicesWithAsserts, """ assert """); - result.Should().HaveDiagnostics(new[] { + result.Should().HaveDiagnostics([ ("BCP344", DiagnosticLevel.Error, "Expected an assert identifier at this location."), - }); + ]); result = CompilationHelper.Compile(ServicesWithAsserts, """ assert a1 """); - result.Should().HaveDiagnostics(new[] { + result.Should().HaveDiagnostics([ ("BCP018", DiagnosticLevel.Error, "Expected the \"=\" character at this location."), - }); + ]); result = CompilationHelper.Compile(ServicesWithAsserts, """ assert a1 = """); - result.Should().HaveDiagnostics(new[] { + result.Should().HaveDiagnostics([ ("BCP009", DiagnosticLevel.Error, "Expected a literal value, an array, an object, a parenthesized expression, or a function call at this location."), - }); + ]); } [TestMethod] @@ -166,12 +166,12 @@ param location string assert location = contains(location, 'west') """); - result.Should().HaveDiagnostics(new[] { + result.Should().HaveDiagnostics([ ("BCP028", DiagnosticLevel.Error, "Identifier \"location\" is declared multiple times. Remove or rename the duplicates."), ("BCP025", DiagnosticLevel.Error, "The property \"ra1\" is declared multiple times in this object. Remove or rename the duplicate properties."), ("BCP025", DiagnosticLevel.Error, "The property \"ra1\" is declared multiple times in this object. Remove or rename the duplicate properties."), ("BCP028", DiagnosticLevel.Error, "Identifier \"location\" is declared multiple times. Remove or rename the duplicates."), - }); + ]); } [TestMethod] @@ -217,8 +217,8 @@ param environment string """)); result.Should().NotGenerateATemplate(); - result.ExcludingLinterDiagnostics().Should().HaveDiagnostics(new[] - { + result.ExcludingLinterDiagnostics().Should().HaveDiagnostics( + [ ("BCP036", DiagnosticLevel.Error, "The property \"ra1\" expected a value of type \"bool\" but the provided value is of type \"0\"."), ("BCP036", DiagnosticLevel.Error, "The property \"ra5\" expected a value of type \"bool\" but the provided value is of type \"null\"."), ("BCP036", DiagnosticLevel.Error, "The property \"ra6\" expected a value of type \"bool\" but the provided value is of type \"[4, 5, 6]\"."), @@ -231,7 +231,7 @@ param environment string ("BCP350", DiagnosticLevel.Error, "Value of type \"[1, 2, 3]\" cannot be assigned to an assert. Asserts can take values of type 'bool' only."), ("BCP350", DiagnosticLevel.Error, "Value of type \"object\" cannot be assigned to an assert. Asserts can take values of type 'bool' only."), ("BCP350", DiagnosticLevel.Error, "Value of type \"string\" cannot be assigned to an assert. Asserts can take values of type 'bool' only."), - }); + ]); } [TestMethod] diff --git a/src/Bicep.Core.IntegrationTests/CompileTimeImportTests.cs b/src/Bicep.Core.IntegrationTests/CompileTimeImportTests.cs index 06be07c6298..181b8ea6a1e 100644 --- a/src/Bicep.Core.IntegrationTests/CompileTimeImportTests.cs +++ b/src/Bicep.Core.IntegrationTests/CompileTimeImportTests.cs @@ -30,11 +30,11 @@ public void Importing_unexported_symbol_should_raise_diagnostic() var bar = 'bar' """)); - result.ExcludingLinterDiagnostics().Should().HaveDiagnostics(new[] - { + result.ExcludingLinterDiagnostics().Should().HaveDiagnostics( + [ ("BCP360", DiagnosticLevel.Error, "The 'foo' symbol was not found in (or was not exported by) the imported template."), ("BCP360", DiagnosticLevel.Error, "The 'bar' symbol was not found in (or was not exported by) the imported template."), - }); + ]); } [TestMethod] @@ -51,10 +51,10 @@ public void Imported_variable_cannot_be_used_in_a_type_expression() var bar = 'bar' """)); - result.ExcludingLinterDiagnostics().Should().HaveDiagnostics(new[] - { + result.ExcludingLinterDiagnostics().Should().HaveDiagnostics( + [ ("BCP287", DiagnosticLevel.Error, "'bar' refers to a value but is being used as a type here."), - }); + ]); } [TestMethod] @@ -71,10 +71,10 @@ public void Imported_type_cannot_be_used_in_a_value_expression() type foo = string[] """)); - result.ExcludingLinterDiagnostics().Should().HaveDiagnostics(new[] - { + result.ExcludingLinterDiagnostics().Should().HaveDiagnostics( + [ ("BCP288", DiagnosticLevel.Error, "'foo' refers to a type but is being used as a value here."), - }); + ]); } [TestMethod] @@ -89,10 +89,10 @@ param baz bar.foo type foo = string[] """)); - result.ExcludingLinterDiagnostics().Should().HaveDiagnostics(new[] - { + result.ExcludingLinterDiagnostics().Should().HaveDiagnostics( + [ ("BCP052", DiagnosticLevel.Error, "The type \"bar\" does not contain property \"foo\"."), - }); + ]); } [TestMethod] @@ -105,10 +105,10 @@ public void Exporting_type_property_should_raise_diagnostic() } """); - result.ExcludingLinterDiagnostics().Should().HaveDiagnostics(new[] - { + result.ExcludingLinterDiagnostics().Should().HaveDiagnostics( + [ ("BCP361", DiagnosticLevel.Error, "The \"@export()\" decorator must target a top-level statement.") - }); + ]); } [TestMethod] @@ -1172,11 +1172,11 @@ public void Importing_the_same_symbol_under_two_separate_names_should_raise_diag type foo = string[] """)); - result.ExcludingLinterDiagnostics().Should().HaveDiagnostics(new[] - { + result.ExcludingLinterDiagnostics().Should().HaveDiagnostics( + [ ("BCP362", DiagnosticLevel.Error, "This symbol is imported multiple times under the names 'foo', 'fizz'."), ("BCP362", DiagnosticLevel.Error, "This symbol is imported multiple times under the names 'foo', 'fizz'."), // The same diagnostic should be raised on each import - }); + ]); } [TestMethod] @@ -1204,11 +1204,11 @@ public void Importing_the_same_symbol_from_json_template_under_two_separate_name } """)); - result.ExcludingLinterDiagnostics().Should().HaveDiagnostics(new[] - { + result.ExcludingLinterDiagnostics().Should().HaveDiagnostics( + [ ("BCP362", DiagnosticLevel.Error, "This symbol is imported multiple times under the names 'foo', 'fizz'."), ("BCP362", DiagnosticLevel.Error, "This symbol is imported multiple times under the names 'foo', 'fizz'."), // The same diagnostic should be raised on each import - }); + ]); } [TestMethod] @@ -1223,10 +1223,10 @@ param foo string var quux = baz """); - result.ExcludingLinterDiagnostics().Should().HaveDiagnostics(new[] - { + result.ExcludingLinterDiagnostics().Should().HaveDiagnostics( + [ ("BCP372", DiagnosticLevel.Error, "The \"@export()\" decorator may not be applied to variables that refer to parameters, modules, or resource, either directly or indirectly. The target of this decorator contains direct or transitive references to the following unexportable symbols: \"foo\"."), - }); + ]); } [TestMethod] @@ -1253,10 +1253,10 @@ public void Exporting_a_variable_that_references_a_resource_should_raise_diagnos var quux = baz """); - result.ExcludingLinterDiagnostics().Should().HaveDiagnostics(new[] - { + result.ExcludingLinterDiagnostics().Should().HaveDiagnostics( + [ ("BCP372", DiagnosticLevel.Error, "The \"@export()\" decorator may not be applied to variables that refer to parameters, modules, or resource, either directly or indirectly. The target of this decorator contains direct or transitive references to the following unexportable symbols: \"foo\"."), - }); + ]); } [TestMethod] @@ -1305,10 +1305,10 @@ public void Importing_a_name_that_refers_to_mulitple_exports_should_raise_diagno } """)); - result.ExcludingLinterDiagnostics().Should().HaveDiagnostics(new[] - { + result.ExcludingLinterDiagnostics().Should().HaveDiagnostics( + [ ("BCP373", DiagnosticLevel.Error, "Unable to import the symbol named \"foo\": The name \"foo\" is ambiguous because it refers to exports of the following kinds: Type, Variable."), - }); + ]); } [TestMethod] @@ -1346,10 +1346,10 @@ public void Wildcard_importing_a_target_with_multiple_exports_using_the_same_nam } """)); - result.ExcludingLinterDiagnostics().Should().HaveDiagnostics(new[] - { + result.ExcludingLinterDiagnostics().Should().HaveDiagnostics( + [ ("BCP374", DiagnosticLevel.Error, "The imported model cannot be loaded with a wildcard because it contains the following duplicated exports: \"foo\"."), - }); + ]); } [TestMethod] @@ -1506,10 +1506,10 @@ public void Named_import_by_quoted_string_should_block_interpolation() } """)); - result.ExcludingLinterDiagnostics().Should().HaveDiagnostics(new[] - { + result.ExcludingLinterDiagnostics().Should().HaveDiagnostics( + [ ("BCP032", DiagnosticLevel.Error, "The value must be a compile-time constant."), - }); + ]); } [TestMethod] @@ -1539,10 +1539,10 @@ public void Named_import_by_quoted_string_without_alias_should_raise_diagnostic( } """)); - result.ExcludingLinterDiagnostics().Should().HaveDiagnostics(new[] - { + result.ExcludingLinterDiagnostics().Should().HaveDiagnostics( + [ ("BCP375", DiagnosticLevel.Error, "An import list item that identifies its target with a quoted string must include an 'as ' clause."), - }); + ]); } [TestMethod] @@ -1554,10 +1554,10 @@ public void Named_import_with_invalid_original_symbol_name_syntax_should_raise_d """), ("mod.bicep", string.Empty)); - result.ExcludingLinterDiagnostics().Should().HaveDiagnostics(new[] - { + result.ExcludingLinterDiagnostics().Should().HaveDiagnostics( + [ ("BCP355", DiagnosticLevel.Error, "Expected the name of an exported symbol at this location."), - }); + ]); } [TestMethod] @@ -1668,10 +1668,10 @@ public void Importing_types_is_blocked_in_bicepparam_files() type foo = string """)); - result.ExcludingLinterDiagnostics().Should().HaveDiagnostics(new[] - { + result.ExcludingLinterDiagnostics().Should().HaveDiagnostics( + [ ("BCP376", DiagnosticLevel.Error, "The \"foo\" symbol cannot be imported because imports of kind Type are not supported in files of kind ParamsFile."), - }); + ]); } // https://github.com/Azure/bicep/issues/12042 @@ -1944,11 +1944,11 @@ public void Imported_objects_can_be_used_in_object_type_narrowing() var obj = {foo: 'foo', bar: 'bar'} """)); - result.Should().HaveDiagnostics(new[] - { + result.Should().HaveDiagnostics( + [ ("BCP037", DiagnosticLevel.Error, """The property "bar" is not allowed on objects of type "{ }". No other properties are allowed."""), ("BCP037", DiagnosticLevel.Error, """The property "foo" is not allowed on objects of type "{ }". No other properties are allowed."""), - }); + ]); } [TestMethod] @@ -1966,10 +1966,10 @@ public void Imported_objects_can_be_used_in_discriminated_object_type_narrowing( var obj = {type: 'foo', bar: 'bar'} """)); - result.Should().HaveDiagnostics(new[] - { + result.Should().HaveDiagnostics( + [ ("BCP035", DiagnosticLevel.Error, """The specified "output" declaration is missing the following required properties: "pop"."""), - }); + ]); } // https://github.com/Azure/bicep/issues/12897 @@ -2003,11 +2003,11 @@ public void Bicepparam_imported_variables_from_invalid_bicep_file_cause_errors() INVALID FILE """)); - result.ExcludingLinterDiagnostics().Should().HaveDiagnostics(new[] - { + result.ExcludingLinterDiagnostics().Should().HaveDiagnostics( + [ ("BCP104", DiagnosticLevel.Error, "The referenced module has errors."), ("BCP104", DiagnosticLevel.Error, "The referenced module has errors."), - }); + ]); } // https://github.com/Azure/bicep/issues/12899 @@ -2078,10 +2078,10 @@ public void Resource_derived_types_are_bound_when_imported_from_ARM_JSON_models( """)); result.Should().NotHaveAnyCompilationBlockingDiagnostics(); - result.Should().HaveDiagnostics(new[] - { + result.Should().HaveDiagnostics( + [ ("BCP037", DiagnosticLevel.Warning, """The property "unknownProperty" is not allowed on objects of type "StorageAccountPropertiesCreateParametersOrStorageAccountProperties". Permissible properties include "accessTier", "allowBlobPublicAccess", "allowCrossTenantReplication", "allowedCopyScope", "allowSharedKeyAccess", "azureFilesIdentityBasedAuthentication", "customDomain", "defaultToOAuthAuthentication", "dnsEndpointType", "encryption", "immutableStorageWithVersioning", "isHnsEnabled", "isLocalUserEnabled", "isNfsV3Enabled", "isSftpEnabled", "keyPolicy", "largeFileSharesState", "minimumTlsVersion", "networkAcls", "publicNetworkAccess", "routingPreference", "sasPolicy", "supportsHttpsTrafficOnly"."""), - }); + ]); } [TestMethod] @@ -2128,10 +2128,10 @@ public void Resource_derived_typed_compile_time_imports_raise_diagnostic_when_im } """)); - result.Should().HaveDiagnostics(new[] - { + result.Should().HaveDiagnostics( + [ ("BCP385", DiagnosticLevel.Error, """Using resource-derived types requires enabling EXPERIMENTAL feature "ResourceDerivedTypes"."""), - }); + ]); } [TestMethod] @@ -2178,10 +2178,10 @@ public void Resource_derived_typed_compile_time_imports_raise_diagnostic_when_im } """)); - result.Should().HaveDiagnostics(new[] - { + result.Should().HaveDiagnostics( + [ ("BCP081", DiagnosticLevel.Warning, """Resource type "Microsoft.Foo/bars@2022-09-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."""), - }); + ]); } // https://github.com/Azure/bicep/issues/12981 diff --git a/src/Bicep.Core.IntegrationTests/DecoratorTests.cs b/src/Bicep.Core.IntegrationTests/DecoratorTests.cs index 0343266828e..8918ebdb451 100644 --- a/src/Bicep.Core.IntegrationTests/DecoratorTests.cs +++ b/src/Bicep.Core.IntegrationTests/DecoratorTests.cs @@ -25,9 +25,9 @@ public void ParameterDecorator_MissingDeclaration_ExpectedParameterDeclaration() using (new AssertionScope()) { template.Should().NotHaveValue(); - diagnostics.ExcludingLinterDiagnostics().Should().HaveDiagnostics(new[] { + diagnostics.ExcludingLinterDiagnostics().Should().HaveDiagnostics([ ("BCP290", DiagnosticLevel.Error, "Expected a parameter or type declaration after the decorator."), - }); + ]); } } @@ -79,11 +79,11 @@ param inputb string using (new AssertionScope()) { - diagnosticsByFile[mainUri].ExcludingLinterDiagnostics().ExcludingMissingTypes().Should().HaveDiagnostics(new[] { + diagnosticsByFile[mainUri].ExcludingLinterDiagnostics().ExcludingMissingTypes().Should().HaveDiagnostics([ ("BCP126", DiagnosticLevel.Error, "Function \"maxLength\" cannot be used as a variable decorator."), ("BCP127", DiagnosticLevel.Error, "Function \"allowed\" cannot be used as a resource decorator."), ("BCP128", DiagnosticLevel.Error, "Function \"secure\" cannot be used as a module decorator."), - }); + ]); success.Should().BeFalse(); } } @@ -160,11 +160,11 @@ public void NonDecoratorFunction_MissingDeclaration_CannotBeUsedAsDecorator() using (new AssertionScope()) { template.Should().NotHaveValue(); - diagnostics.ExcludingLinterDiagnostics().Should().HaveDiagnostics(new[] { + diagnostics.ExcludingLinterDiagnostics().Should().HaveDiagnostics([ ("BCP152", DiagnosticLevel.Error, "Function \"concat\" cannot be used as a decorator."), ("BCP132", DiagnosticLevel.Error, "Expected a declaration after the decorator."), ("BCP152", DiagnosticLevel.Error, "Function \"resourceId\" cannot be used as a decorator.") - }); + ]); } } @@ -220,13 +220,13 @@ param inputb string using (new AssertionScope()) { - diagnosticsByFile[mainUri].ExcludingLinterDiagnostics().ExcludingMissingTypes().Should().HaveDiagnostics(new[] { + diagnosticsByFile[mainUri].ExcludingLinterDiagnostics().ExcludingMissingTypes().Should().HaveDiagnostics([ ("BCP152", DiagnosticLevel.Error, "Function \"resourceId\" cannot be used as a decorator."), ("BCP152", DiagnosticLevel.Error, "Function \"concat\" cannot be used as a decorator."), ("BCP152", DiagnosticLevel.Error, "Function \"environment\" cannot be used as a decorator."), ("BCP152", DiagnosticLevel.Error, "Function \"union\" cannot be used as a decorator."), ("BCP152", DiagnosticLevel.Error, "Function \"guid\" cannot be used as a decorator."), - }); + ]); success.Should().BeFalse(); } } @@ -286,10 +286,10 @@ public void DecoratorDescriptionInResourceBody_ShouldPromptForDeclaration() "); using (new AssertionScope()) { - diagnostics.ExcludingLinterDiagnostics().Should().HaveDiagnostics(new[] - { + diagnostics.ExcludingLinterDiagnostics().Should().HaveDiagnostics( + [ ("BCP132", DiagnosticLevel.Error, "Expected a declaration after the decorator."), - }); + ]); template.Should().BeNull(); } } @@ -307,10 +307,10 @@ public void DecoratorBatchSizeInResourceBody_ShouldPromptForResourceDeclaration( "); using (new AssertionScope()) { - diagnostics.ExcludingLinterDiagnostics().Should().HaveDiagnostics(new[] - { + diagnostics.ExcludingLinterDiagnostics().Should().HaveDiagnostics( + [ ("BCP153", DiagnosticLevel.Error, "Expected a resource or module declaration after the decorator."), - }); + ]); template.Should().BeNull(); } } @@ -328,10 +328,10 @@ public void UnfinishedDecoratorInResourceBody_ShouldPromptForNamespaceOrDecorato "); using (new AssertionScope()) { - diagnostics.ExcludingLinterDiagnostics().Should().HaveDiagnostics(new[] - { + diagnostics.ExcludingLinterDiagnostics().Should().HaveDiagnostics( + [ ("BCP123", DiagnosticLevel.Error, "Expected a namespace or decorator name at this location."), - }); + ]); template.Should().BeNull(); } } diff --git a/src/Bicep.Core.IntegrationTests/DeployTimeConstantTests.cs b/src/Bicep.Core.IntegrationTests/DeployTimeConstantTests.cs index ef26cf22890..caed970ded2 100644 --- a/src/Bicep.Core.IntegrationTests/DeployTimeConstantTests.cs +++ b/src/Bicep.Core.IntegrationTests/DeployTimeConstantTests.cs @@ -128,8 +128,8 @@ param ident resource 'Microsoft.ManagedIdentity/userAssignedIdentities@2018-11-3 } } "); - result.ExcludingLinterDiagnostics().Should().HaveDiagnostics(new[] - { + result.ExcludingLinterDiagnostics().Should().HaveDiagnostics( + [ ("BCP178", DiagnosticLevel.Error, "This expression is being used in the for-expression, which requires a value that can be calculated at the start of the deployment. Properties of dnsZone which can be calculated at the start include \"apiVersion\", \"id\", \"name\", \"type\"."), ("BCP178", DiagnosticLevel.Error, "This expression is being used in the for-expression, which requires a value that can be calculated at the start of the deployment. Properties of storageAccounts which can be calculated at the start include \"apiVersion\", \"id\", \"name\", \"type\"."), ("BCP178", DiagnosticLevel.Error, "This expression is being used in the for-expression, which requires a value that can be calculated at the start of the deployment. Properties of aRecord which can be calculated at the start include \"apiVersion\", \"id\", \"name\", \"type\"."), @@ -140,7 +140,7 @@ param ident resource 'Microsoft.ManagedIdentity/userAssignedIdentities@2018-11-3 ("BCP120", DiagnosticLevel.Error, @"This expression is being used in an assignment to the ""parent"" property of the ""Microsoft.Network/virtualNetworks/subnets"" type, which requires a value that can be calculated at the start of the deployment. Properties of vnet which can be calculated at the start include ""apiVersion"", ""id"", ""type""."), ("BCP120", DiagnosticLevel.Error, @"This expression is being used in an assignment to the ""scope"" property of the ""Microsoft.Insights/diagnosticSettings"" type, which requires a value that can be calculated at the start of the deployment. Properties of subnet1 which can be calculated at the start include ""apiVersion"", ""id"", ""type""."), ("BCP120", DiagnosticLevel.Error, @"This expression is being used in an assignment to the ""name"" property of the ""Microsoft.Authorization/roleAssignments"" type, which requires a value that can be calculated at the start of the deployment. Properties of ident which can be calculated at the start include ""apiVersion"", ""id"", ""name"", ""type""."), - }); + ]); } [TestMethod] @@ -165,11 +165,11 @@ public void DtcValidation_RuntimeValueAsDtcPropertyKey_ProducesDiagnostics() } } "); - result.ExcludingLinterDiagnostics().Should().HaveDiagnostics(new[] - { + result.ExcludingLinterDiagnostics().Should().HaveDiagnostics( + [ ("BCP120", DiagnosticLevel.Error, "This expression is being used in an assignment to the \"tags\" property of the \"Microsoft.Web/serverfarms\" type, which requires a value that can be calculated at the start of the deployment."), ("BCP120", DiagnosticLevel.Error, "This expression is being used in an assignment to the \"tags\" property of the \"Microsoft.Web/serverfarms\" type, which requires a value that can be calculated at the start of the deployment. Properties of dnsZone which can be calculated at the start include \"apiVersion\", \"id\", \"name\", \"type\"."), - }); + ]); } [TestMethod] @@ -311,12 +311,12 @@ param location string } """); - result.ExcludingLinterDiagnostics().Should().HaveDiagnostics(new[] - { + result.ExcludingLinterDiagnostics().Should().HaveDiagnostics( + [ ("BCP036", DiagnosticLevel.Warning, @"The property ""location"" expected a value of type ""string"" but the provided value is of type ""Microsoft.ManagedIdentity/userAssignedIdentities@2023-01-31"". If this is an inaccuracy in the documentation, please report it to the Bicep Team."), ("BCP120", DiagnosticLevel.Error, @"This expression is being used in an assignment to the ""location"" property of the ""Microsoft.Storage/storageAccounts"" type, which requires a value that can be calculated at the start of the deployment. Properties of userAssignedIdentity which can be calculated at the start include ""apiVersion"", ""id"", ""name"", ""type""."), ("BCP120", DiagnosticLevel.Error, @"This expression is being used in an assignment to the ""identity"" property of the ""Microsoft.Storage/storageAccounts"" type, which requires a value that can be calculated at the start of the deployment. Properties of userAssignedIdentity which can be calculated at the start include ""apiVersion"", ""id"", ""name"", ""type""."), - }); + ]); } } } diff --git a/src/Bicep.Core.IntegrationTests/DirectResourceCollectionTests.cs b/src/Bicep.Core.IntegrationTests/DirectResourceCollectionTests.cs index e0cd84cb85e..f35f7e56a65 100644 --- a/src/Bicep.Core.IntegrationTests/DirectResourceCollectionTests.cs +++ b/src/Bicep.Core.IntegrationTests/DirectResourceCollectionTests.cs @@ -20,8 +20,8 @@ public void DirectResourceCollectionAccess_NonSymbolic_Basic() result.WithErrorDiagnosticsOnly() .Should() - .HaveDiagnostics(new[] - { + .HaveDiagnostics( + [ ("BCP144", DiagnosticLevel.Error, "Directly referencing a resource or module collection is not currently supported here. Apply an array indexer to the expression."), ("BCP144", DiagnosticLevel.Error, "Directly referencing a resource or module collection is not currently supported here. Apply an array indexer to the expression."), ("BCP144", DiagnosticLevel.Error, "Directly referencing a resource or module collection is not currently supported here. Apply an array indexer to the expression."), @@ -30,7 +30,7 @@ public void DirectResourceCollectionAccess_NonSymbolic_Basic() ("BCP144", DiagnosticLevel.Error, "Directly referencing a resource or module collection is not currently supported here. Apply an array indexer to the expression."), ("BCP144", DiagnosticLevel.Error, "Directly referencing a resource or module collection is not currently supported here. The collection was accessed by the chain of \"containerWorkersAlias\" -> \"containerWorkers\". Apply an array indexer to the expression."), ("BCP144", DiagnosticLevel.Error, "Directly referencing a resource or module collection is not currently supported here. The collection was accessed by the chain of \"ipAddresses\" -> \"containerWorkers\". Apply an array indexer to the expression."), - }); + ]); } [TestMethod] @@ -156,10 +156,9 @@ public void DirectResourceCollectionAccess_NotAllowedWithinLoops(string addition result.WithErrorDiagnosticsOnly() .Should() .HaveDiagnostics( - new[] - { + [ ("BCP144", DiagnosticLevel.Error, "Directly referencing a resource or module collection is not currently supported here. Apply an array indexer to the expression."), - }); + ]); } [TestMethod] @@ -176,10 +175,9 @@ public void DirectResourceCollectionAccess_NotAllowedWithinLoops_InlinedVariable result.WithErrorDiagnosticsOnly() .Should() .HaveDiagnostics( - new[] - { + [ ("BCP144", DiagnosticLevel.Error, "Directly referencing a resource or module collection is not currently supported here. The collection was accessed by the chain of \"containerWorkersAliased\" -> \"containerWorkers\". Apply an array indexer to the expression."), - }); + ]); } [TestMethod] @@ -198,10 +196,9 @@ public void DirectResourceCollectionAccess_NotAllowedWithinUnsupportedResourcePr result.WithErrorDiagnosticsOnly() .Should() .HaveDiagnostics( - new[] - { + [ ("BCP144", DiagnosticLevel.Error, "Directly referencing a resource or module collection is not currently supported here. Apply an array indexer to the expression."), - }); + ]); } [TestMethod] @@ -223,10 +220,9 @@ public void DirectResourceCollectionAccess_NotAllowedWithinUnsupportedResourcePr result.WithErrorDiagnosticsOnly() .Should() .HaveDiagnostics( - new[] - { + [ ("BCP144", DiagnosticLevel.Error, "Directly referencing a resource or module collection is not currently supported here. The collection was accessed by the chain of \"containerWorkerIps\" -> \"containerWorkers\". Apply an array indexer to the expression."), - }); + ]); } [TestMethod] @@ -250,10 +246,9 @@ public void DirectResourceCollectionAccess_NotAllowedWithinUnsupportedResourcePr result.WithErrorDiagnosticsOnly() .Should() .HaveDiagnostics( - new[] - { + [ ("BCP144", DiagnosticLevel.Error, "Directly referencing a resource or module collection is not currently supported here. The collection was accessed by the chain of \"containerWorkerIps\" -> \"containerWorkersAliased\" -> \"containerWorkers\". Apply an array indexer to the expression."), - }); + ]); } [TestMethod] @@ -299,10 +294,9 @@ public void DirectResourceCollectionAccess_NotAllowedWithinResourceCollection() result.WithErrorDiagnosticsOnly() .Should() .HaveDiagnostics( - new[] - { + [ ("BCP144", DiagnosticLevel.Error, "Directly referencing a resource or module collection is not currently supported here. Apply an array indexer to the expression.") - }); + ]); } [TestMethod] @@ -349,10 +343,9 @@ public void DirectResourceCollectionAccess_NotAllowedWithinResourceCollection_In result.WithErrorDiagnosticsOnly() .Should() .HaveDiagnostics( - new[] - { + [ ("BCP144", DiagnosticLevel.Error, "Directly referencing a resource or module collection is not currently supported here. The collection was accessed by the chain of \"ipAddresses\" -> \"containerWorkers\". Apply an array indexer to the expression.") - }); + ]); } [TestMethod] @@ -421,8 +414,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 +484,7 @@ private static (string fileName, string fileContents)[] CreateReferencesBicepCon output modOutput1 string = storage.properties.modInput1 """) - }; + ]; } } } diff --git a/src/Bicep.Core.IntegrationTests/DynamicAzTypesTests.cs b/src/Bicep.Core.IntegrationTests/DynamicAzTypesTests.cs index e4fcb919a46..b954db8c27d 100644 --- a/src/Bicep.Core.IntegrationTests/DynamicAzTypesTests.cs +++ b/src/Bicep.Core.IntegrationTests/DynamicAzTypesTests.cs @@ -80,9 +80,9 @@ public async Task Az_namespace_errors_with_configuration() "); result.Should().NotGenerateATemplate(); - result.ExcludingLinterDiagnostics().Should().HaveDiagnostics(new[] { + result.ExcludingLinterDiagnostics().Should().HaveDiagnostics([ ("BCP205", DiagnosticLevel.Error, "Provider namespace \"az\" does not support configuration."), - }); + ]); } [TestMethod] @@ -166,9 +166,9 @@ await RegistryHelper.PublishModuleToRegistryAsync( // ASSERT result.Should().NotGenerateATemplate(); result.Should().HaveDiagnostics( - new[] { + [ ("BCP192", DiagnosticLevel.Error, """Unable to restore the artifact with reference "br:mcr.microsoft.com/bicep/providers/az:0.2.661": The OCI artifact is not a valid Bicep artifact. Expected a provider, but retrieved a module."""), - }); + ]); } [TestMethod] 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/EvaluationTests.cs b/src/Bicep.Core.IntegrationTests/EvaluationTests.cs index 77cc02fb04c..ab3c704aea5 100644 --- a/src/Bicep.Core.IntegrationTests/EvaluationTests.cs +++ b/src/Bicep.Core.IntegrationTests/EvaluationTests.cs @@ -998,11 +998,11 @@ param param2 object var result = CompilationHelper.CompileParams(("parameters.bicepparam", bicepparamText), ("main.bicep", bicepTemplateText)); - result.Should().HaveDiagnostics(new[] - { + result.Should().HaveDiagnostics( + [ ("BCP368", DiagnosticLevel.Error, "The value of the \"param1\" parameter cannot be known until the template deployment has started because it uses a reference to a secret value in Azure Key Vault. Expressions that refer to the \"param1\" parameter may be used in .bicep files but not in .bicepparam files."), ("BCP368", DiagnosticLevel.Error, "The value of the \"param1\" parameter cannot be known until the template deployment has started because it uses a reference to a secret value in Azure Key Vault. Expressions that refer to the \"param1\" parameter may be used in .bicep files but not in .bicepparam files."), - }); + ]); } [TestMethod] @@ -1025,11 +1025,11 @@ param param2 object var result = CompilationHelper.CompileParams(("parameters.bicepparam", bicepparamText), ("main.bicep", bicepTemplateText)); - result.Should().HaveDiagnostics(new[] - { + result.Should().HaveDiagnostics( + [ ("BCP369", DiagnosticLevel.Error, "The value of the \"param1\" parameter cannot be known until the template deployment has started because it uses the default value defined in the template. Expressions that refer to the \"param1\" parameter may be used in .bicep files but not in .bicepparam files."), ("BCP369", DiagnosticLevel.Error, "The value of the \"param1\" parameter cannot be known until the template deployment has started because it uses the default value defined in the template. Expressions that refer to the \"param1\" parameter may be used in .bicep files but not in .bicepparam files."), - }); + ]); } [TestMethod] diff --git a/src/Bicep.Core.IntegrationTests/Extensibility/BarNamespaceType.cs b/src/Bicep.Core.IntegrationTests/Extensibility/BarNamespaceType.cs index 68cd27c7537..04bf03fd032 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, @@ -28,10 +28,10 @@ public static class BarNamespaceType private static ObjectType GetConfigurationType() { - return new ObjectType("configuration", TypeSymbolValidationFlags.Default, new[] - { + return new ObjectType("configuration", TypeSymbolValidationFlags.Default, + [ new TypeProperty("connectionString", LanguageConstants.String, TypePropertyFlags.Required), - }, null); + ], null); } private class BarTypeProvider : ResourceTypeProviderBase, IResourceTypeProvider @@ -42,32 +42,32 @@ private class BarTypeProvider : ResourceTypeProviderBase, IResourceTypeProvider ResourceScope.Tenant | ResourceScope.ManagementGroup | ResourceScope.Subscription | ResourceScope.ResourceGroup, ResourceScope.None, ResourceFlags.None, - new ObjectType("Service properties", TypeSymbolValidationFlags.Default, new[] - { + new ObjectType("Service properties", TypeSymbolValidationFlags.Default, + [ new TypeProperty("staticWebsiteEnabled", LanguageConstants.Bool), new TypeProperty("staticWebsiteIndexDocument", LanguageConstants.String), new TypeProperty("staticWebsiteErrorDocument404Path", LanguageConstants.String), - }, null)), + ], null)), new ResourceTypeComponents( ResourceTypeReference.Parse("container"), ResourceScope.Tenant | ResourceScope.ManagementGroup | ResourceScope.Subscription | ResourceScope.ResourceGroup, ResourceScope.None, ResourceFlags.None, - new ObjectType("Container properties", TypeSymbolValidationFlags.Default, new[] - { + new ObjectType("Container properties", TypeSymbolValidationFlags.Default, + [ new TypeProperty("name", LanguageConstants.String, TypePropertyFlags.Required), - }, null)), + ], null)), new ResourceTypeComponents( ResourceTypeReference.Parse("blob"), ResourceScope.Tenant | ResourceScope.ManagementGroup | ResourceScope.Subscription | ResourceScope.ResourceGroup, ResourceScope.None, ResourceFlags.None, - new ObjectType("Blob properties", TypeSymbolValidationFlags.Default, new[] - { + new ObjectType("Blob properties", TypeSymbolValidationFlags.Default, + [ new TypeProperty("containerName", LanguageConstants.String, TypePropertyFlags.Required), new TypeProperty("name", LanguageConstants.String, TypePropertyFlags.Required), new TypeProperty("base64Content", LanguageConstants.String, TypePropertyFlags.Required), - }, null)), + ], null)), }.ToImmutableDictionary(x => x.TypeReference); public BarTypeProvider() @@ -109,10 +109,10 @@ public static NamespaceType Create(string aliasName) return new NamespaceType( aliasName, Settings, - ImmutableArray.Empty, - ImmutableArray.Empty, - ImmutableArray.Empty, - ImmutableArray.Empty, + [], + [], + [], + [], new BarTypeProvider()); } } diff --git a/src/Bicep.Core.IntegrationTests/Extensibility/FooNamespaceType.cs b/src/Bicep.Core.IntegrationTests/Extensibility/FooNamespaceType.cs index 7d0d0c45dcf..ee68a3f2b8e 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, @@ -34,11 +34,11 @@ private class FooTypeProvider : ResourceTypeProviderBase, IResourceTypeProvider ResourceScope.Tenant | ResourceScope.ManagementGroup | ResourceScope.Subscription | ResourceScope.ResourceGroup, ResourceScope.None, ResourceFlags.None, - new ObjectType("application", TypeSymbolValidationFlags.Default, new[] - { + new ObjectType("application", TypeSymbolValidationFlags.Default, + [ new TypeProperty("uniqueName", LanguageConstants.String, TypePropertyFlags.Required | TypePropertyFlags.SystemProperty), new TypeProperty("appId", LanguageConstants.String, TypePropertyFlags.ReadOnly), - }, null)), + ], null)), }.ToImmutableDictionary(x => x.TypeReference); public FooTypeProvider() @@ -80,10 +80,10 @@ public static NamespaceType Create(string aliasName) return new NamespaceType( aliasName, Settings, - ImmutableArray.Empty, - ImmutableArray.Empty, - ImmutableArray.Empty, - ImmutableArray.Empty, + [], + [], + [], + [], new FooTypeProvider()); } } diff --git a/src/Bicep.Core.IntegrationTests/ExtensibilityTests.cs b/src/Bicep.Core.IntegrationTests/ExtensibilityTests.cs index 8c22c00fb59..079c352094c 100644 --- a/src/Bicep.Core.IntegrationTests/ExtensibilityTests.cs +++ b/src/Bicep.Core.IntegrationTests/ExtensibilityTests.cs @@ -38,10 +38,10 @@ provider bar with { madeUpProperty: 'asdf' } as stg "); - result.ExcludingLinterDiagnostics().Should().HaveDiagnostics(new[] { + result.ExcludingLinterDiagnostics().Should().HaveDiagnostics([ ("BCP035", DiagnosticLevel.Error, "The specified \"object\" declaration is missing the following required properties: \"connectionString\"."), ("BCP037", DiagnosticLevel.Error, "The property \"madeUpProperty\" is not allowed on objects of type \"configuration\". Permissible properties include \"connectionString\".") - }); + ]); } [TestMethod] @@ -96,9 +96,9 @@ provider bar with { name: 'myblob' } """); - result.ExcludingLinterDiagnostics().Should().HaveDiagnostics(new[] { + result.ExcludingLinterDiagnostics().Should().HaveDiagnostics([ ("BCP264", DiagnosticLevel.Error, "Resource type \"container\" is declared in multiple imported namespaces (\"stg\", \"stg2\"), and must be fully-qualified."), - }); + ]); result = CompilationHelper.Compile(Services, """ provider bar with { @@ -198,11 +198,11 @@ provider foo """); result.Should().NotGenerateATemplate(); - result.Should().HaveDiagnostics(new[] { + result.Should().HaveDiagnostics([ ("BCP035", DiagnosticLevel.Error, "The specified \"resource\" declaration is missing the following required properties: \"uniqueName\"."), ("no-unused-existing-resources", DiagnosticLevel.Warning, "Existing resource \"myApp\" is declared but never used."), ("BCP037", DiagnosticLevel.Error, "The property \"name\" is not allowed on objects of type \"application\". Permissible properties include \"uniqueName\". If this is an inaccuracy in the documentation, please report it to the Bicep Team."), - }); + ]); // oops! let's change it to 'uniqueName' result = CompilationHelper.Compile(Services, """ @@ -214,9 +214,9 @@ provider foo as foo """); result.Should().GenerateATemplate(); - result.Should().HaveDiagnostics(new[] { + result.Should().HaveDiagnostics([ ("no-unused-existing-resources", DiagnosticLevel.Warning, "Existing resource \"myApp\" is declared but never used."), - }); + ]); } [TestMethod] @@ -242,11 +242,11 @@ provider kubernetes with { """); result.Should().GenerateATemplate(); - result.Should().HaveDiagnostics(new[] { + result.Should().HaveDiagnostics([ ("no-unused-existing-resources", DiagnosticLevel.Warning, "Existing resource \"service\" is declared but never used."), ("BCP073", DiagnosticLevel.Warning, "The property \"labels\" is read-only. Expressions cannot be assigned to read-only properties. If this is an inaccuracy in the documentation, please report it to the Bicep Team."), ("BCP073", DiagnosticLevel.Warning, "The property \"annotations\" is read-only. Expressions cannot be assigned to read-only properties. If this is an inaccuracy in the documentation, please report it to the Bicep Team."), - }); + ]); } [TestMethod] @@ -265,12 +265,12 @@ provider kubernetes with { "); result.Should().NotGenerateATemplate(); - result.Should().HaveDiagnostics(new[] { + result.Should().HaveDiagnostics([ ("BCP028", DiagnosticLevel.Error, "Identifier \"kubernetes\" is declared multiple times. Remove or rename the duplicates."), ("BCP207", DiagnosticLevel.Error, "Namespace \"kubernetes\" is declared multiple times. Remove the duplicates."), ("BCP028", DiagnosticLevel.Error, "Identifier \"kubernetes\" is declared multiple times. Remove or rename the duplicates."), ("BCP207", DiagnosticLevel.Error, "Namespace \"kubernetes\" is declared multiple times. Remove the duplicates."), - }); + ]); } [TestMethod] @@ -302,11 +302,11 @@ provider kubernetes with { "); result.Should().GenerateATemplate(); - result.Should().HaveDiagnostics(new[] { + result.Should().HaveDiagnostics([ ("no-unused-existing-resources", DiagnosticLevel.Warning, "Existing resource \"service\" is declared but never used."), ("no-unused-existing-resources", DiagnosticLevel.Warning, "Existing resource \"secret\" is declared but never used."), ("no-unused-existing-resources", DiagnosticLevel.Warning, "Existing resource \"configmap\" is declared but never used."), - }); + ]); } [TestMethod] @@ -363,9 +363,9 @@ provider kubernetes with { """); result.Should().GenerateATemplate(); - result.Should().HaveDiagnostics(new[] { + result.Should().HaveDiagnostics([ ("BCP081", DiagnosticLevel.Warning, @"Resource type ""custom/Foo@v1"" 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] @@ -394,12 +394,12 @@ provider kubernetes with { """); result.Should().NotGenerateATemplate(); - result.Should().HaveDiagnostics(new[] { + result.Should().HaveDiagnostics([ ("BCP264", DiagnosticLevel.Error, @"Resource type ""Microsoft.Compute/availabilitySets@2023-01-01"" is declared in multiple imported namespaces (""az"", ""kubernetes""), and must be fully-qualified."), ("BCP035", DiagnosticLevel.Error, @"The specified ""resource"" declaration is missing the following required properties: ""name""."), ("BCP081", DiagnosticLevel.Warning, @"Resource type ""Microsoft.Compute/availabilitySets@2023-01-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."), ("BCP081", DiagnosticLevel.Warning, @"Resource type ""Microsoft.Foo/bar@2023-01-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] @@ -442,10 +442,10 @@ provider bar with { } """); - result.ExcludingLinterDiagnostics().Should().HaveDiagnostics(new[] { + result.ExcludingLinterDiagnostics().Should().HaveDiagnostics([ ("BCP208", DiagnosticLevel.Error, "The specified namespace \"foo\" is not recognized. Specify a resource reference using one of the following namespaces: \"az\", \"stg\", \"sys\"."), ("BCP208", DiagnosticLevel.Error, "The specified namespace \"bar\" is not recognized. Specify a resource reference using one of the following namespaces: \"az\", \"stg\", \"sys\"."), - }); + ]); } [TestMethod] @@ -465,10 +465,10 @@ provider bar with { } "); - result.ExcludingLinterDiagnostics().Should().HaveDiagnostics(new[] { + result.ExcludingLinterDiagnostics().Should().HaveDiagnostics([ ("BCP081", DiagnosticLevel.Warning, "Resource type \"Microsoft.Storage/storageAccounts@2020-01-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."), ("BCP210", DiagnosticLevel.Error, "Resource type belonging to namespace \"stg\" cannot have a parent resource type belonging to different namespace \"az\"."), - }); + ]); } [TestMethod] diff --git a/src/Bicep.Core.IntegrationTests/LambdaTests.cs b/src/Bicep.Core.IntegrationTests/LambdaTests.cs index 37273097d3b..5210996c9c5 100644 --- a/src/Bicep.Core.IntegrationTests/LambdaTests.cs +++ b/src/Bicep.Core.IntegrationTests/LambdaTests.cs @@ -19,37 +19,37 @@ public class LambdaTests public void Parentheses_without_arrow_are_not_interpreted_as_lambdas() { CompilationHelper.Compile("var noElements = ()") - .ExcludingLinterDiagnostics().Should().HaveDiagnostics(new[] { + .ExcludingLinterDiagnostics().Should().HaveDiagnostics([ ("BCP243", DiagnosticLevel.Error, "Parentheses must contain exactly one expression."), - }); + ]); CompilationHelper.Compile("var justAComma = (,)") - .ExcludingLinterDiagnostics().Should().HaveDiagnostics(new[] { + .ExcludingLinterDiagnostics().Should().HaveDiagnostics([ ("BCP009", DiagnosticLevel.Error, "Expected a literal value, an array, an object, a parenthesized expression, or a function call at this location."), ("BCP243", DiagnosticLevel.Error, "Parentheses must contain exactly one expression."), - }); + ]); CompilationHelper.Compile("var twoElements = (1, 2)") - .ExcludingLinterDiagnostics().Should().HaveDiagnostics(new[] { + .ExcludingLinterDiagnostics().Should().HaveDiagnostics([ ("BCP243", DiagnosticLevel.Error, "Parentheses must contain exactly one expression."), - }); + ]); CompilationHelper.Compile("var threeElements = (1, 2, 3)") - .ExcludingLinterDiagnostics().Should().HaveDiagnostics(new[] { + .ExcludingLinterDiagnostics().Should().HaveDiagnostics([ ("BCP243", DiagnosticLevel.Error, "Parentheses must contain exactly one expression."), - }); + ]); CompilationHelper.Compile("var unterminated1 = (") - .ExcludingLinterDiagnostics().Should().HaveDiagnostics(new[] { + .ExcludingLinterDiagnostics().Should().HaveDiagnostics([ ("BCP009", DiagnosticLevel.Error, "Expected a literal value, an array, an object, a parenthesized expression, or a function call at this location."), - }); + ]); CompilationHelper.Compile("var unterminated2 = (,") - .ExcludingLinterDiagnostics().Should().HaveDiagnostics(new[] { + .ExcludingLinterDiagnostics().Should().HaveDiagnostics([ ("BCP009", DiagnosticLevel.Error, "Expected a literal value, an array, an object, a parenthesized expression, or a function call at this location."), ("BCP243", DiagnosticLevel.Error, "Parentheses must contain exactly one expression."), ("BCP009", DiagnosticLevel.Error, "Expected a literal value, an array, an object, a parenthesized expression, or a function call at this location."), - }); + ]); } [TestMethod] @@ -65,22 +65,22 @@ public void Lambdas_can_be_placed_inside_parentheses_and_nothing_else() .ExcludingLinterDiagnostics().Should().NotHaveAnyDiagnostics(); CompilationHelper.Compile("var asfsasdf = map([1], true ? i => i + 1 : i => i)") - .ExcludingLinterDiagnostics().Should().HaveDiagnostics(new[] { + .ExcludingLinterDiagnostics().Should().HaveDiagnostics([ ("BCP242", DiagnosticLevel.Error, "Lambda functions may only be specified directly as function arguments."), ("BCP242", DiagnosticLevel.Error, "Lambda functions may only be specified directly as function arguments."), - }); + ]); CompilationHelper.Compile("var asfsasdf = map([1], true ? (i => i + 1) : (i => i))") - .ExcludingLinterDiagnostics().Should().HaveDiagnostics(new[] { + .ExcludingLinterDiagnostics().Should().HaveDiagnostics([ ("BCP242", DiagnosticLevel.Error, "Lambda functions may only be specified directly as function arguments."), ("BCP242", DiagnosticLevel.Error, "Lambda functions may only be specified directly as function arguments."), - }); + ]); CompilationHelper.Compile("var asfsasdf = map([1], [i => i])") - .ExcludingLinterDiagnostics().Should().HaveDiagnostics(new[] { + .ExcludingLinterDiagnostics().Should().HaveDiagnostics([ ("BCP070", DiagnosticLevel.Error, "Argument of type \"[any => any]\" is not assignable to parameter of type \"(any[, int]) => any\"."), ("BCP242", DiagnosticLevel.Error, "Lambda functions may only be specified directly as function arguments."), - }); + ]); } [TestMethod] @@ -153,10 +153,10 @@ public void Map_function_blocks_incorrect_args() '|'); var result = CompilationHelper.Compile(file); - result.ExcludingLinterDiagnostics().Should().HaveDiagnostics(new[] { + result.ExcludingLinterDiagnostics().Should().HaveDiagnostics([ ("BCP070", DiagnosticLevel.Error, """Argument of type "(123, int, any) => 123" is not assignable to parameter of type "(any[, int]) => any"."""), ("BCP070", DiagnosticLevel.Error, """Argument of type "() => 'Hi!'" is not assignable to parameter of type "(any[, int]) => any"."""), - }); + ]); } [TestMethod] @@ -165,10 +165,10 @@ public void Lambdas_are_blocked_in_ternary_expressions() var result = CompilationHelper.Compile(@" var ternary = map([123], true ? abc => '${abc}' : def => 'hello!') "); - result.ExcludingLinterDiagnostics().Should().HaveDiagnostics(new[] { + result.ExcludingLinterDiagnostics().Should().HaveDiagnostics([ ("BCP242", DiagnosticLevel.Error, "Lambda functions may only be specified directly as function arguments."), ("BCP242", DiagnosticLevel.Error, "Lambda functions may only be specified directly as function arguments."), - }); + ]); } [TestMethod] @@ -178,9 +178,9 @@ public void Lambdas_cannot_be_assigned_to_variables() var foo = i => 123 "); - result.ExcludingLinterDiagnostics().Should().HaveDiagnostics(new[] { + result.ExcludingLinterDiagnostics().Should().HaveDiagnostics([ ("BCP242", DiagnosticLevel.Error, "Lambda functions may only be specified directly as function arguments."), - }); + ]); } [TestMethod] @@ -304,14 +304,14 @@ param ids array output accessTiers3 array = map(ids, foo => reference('${foo}').accessTier) "); - result.ExcludingLinterDiagnostics().Should().HaveDiagnostics(new[] { + result.ExcludingLinterDiagnostics().Should().HaveDiagnostics([ ("BCP247", DiagnosticLevel.Error, "Using lambda variables inside resource or module array access is not currently supported. Found the following lambda variable(s) being accessed: \"i\"."), ("BCP247", DiagnosticLevel.Error, "Using lambda variables inside resource or module array access is not currently supported. Found the following lambda variable(s) being accessed: \"j\"."), ("BCP248", DiagnosticLevel.Error, "Using lambda variables inside the \"listKeys\" function is not currently supported. Found the following lambda variable(s) being accessed: \"id\"."), ("BCP247", DiagnosticLevel.Error, "Using lambda variables inside resource or module array access is not currently supported. Found the following lambda variable(s) being accessed: \"k\"."), ("BCP247", DiagnosticLevel.Error, "Using lambda variables inside resource or module array access is not currently supported. Found the following lambda variable(s) being accessed: \"x\", \"y\"."), ("BCP248", DiagnosticLevel.Error, "Using lambda variables inside the \"reference\" function is not currently supported. Found the following lambda variable(s) being accessed: \"foo\"."), - }); + ]); } [TestMethod] @@ -328,9 +328,9 @@ public void Lambda_functions_cannot_be_used_to_dynamically_access_module_collect output foo string = 'HELLO!' ")); - result.ExcludingLinterDiagnostics().Should().HaveDiagnostics(new[] { + result.ExcludingLinterDiagnostics().Should().HaveDiagnostics([ ("BCP247", DiagnosticLevel.Error, "Using lambda variables inside resource or module array access is not currently supported. Found the following lambda variable(s) being accessed: \"i\"."), - }); + ]); } [TestMethod] @@ -353,9 +353,9 @@ public void DeployTimeConstant_detection_works_with_lambdas() } "); - result.ExcludingLinterDiagnostics().Should().HaveDiagnostics(new[] { + result.ExcludingLinterDiagnostics().Should().HaveDiagnostics([ ("BCP120", DiagnosticLevel.Error, "This expression is being used in an assignment to the \"name\" property of the \"Microsoft.Storage/storageAccounts\" type, which requires a value that can be calculated at the start of the deployment. You are referencing a variable which cannot be calculated at the start (\"nonDtcArr\" -> \"stg\"). Properties of stg which can be calculated at the start include \"apiVersion\", \"id\", \"name\", \"type\"."), - }); + ]); } [TestMethod] @@ -368,11 +368,11 @@ func recursiveA() string => recursiveB() func recursiveB() string => recursiveA() "); - result.ExcludingLinterDiagnostics().Should().HaveDiagnostics(new[] { + result.ExcludingLinterDiagnostics().Should().HaveDiagnostics([ ("BCP079", DiagnosticLevel.Error, "This expression is referencing its own declaration, which is not allowed."), ("BCP080", DiagnosticLevel.Error, "The expression is involved in a cycle (\"recursiveB\" -> \"recursiveA\")."), ("BCP080", DiagnosticLevel.Error, "The expression is involved in a cycle (\"recursiveA\" -> \"recursiveB\")."), - }); + ]); } } } diff --git a/src/Bicep.Core.IntegrationTests/LoopInvariantTests.cs b/src/Bicep.Core.IntegrationTests/LoopInvariantTests.cs index a982e2d4370..da0e27101df 100644 --- a/src/Bicep.Core.IntegrationTests/LoopInvariantTests.cs +++ b/src/Bicep.Core.IntegrationTests/LoopInvariantTests.cs @@ -133,10 +133,10 @@ public void MissingResourceExpectedVariantPropertiesShouldProduceNoWarning() location:'s' }]"; var result = CompilationHelper.Compile(text); - result.ExcludingLinterDiagnostics().Should().HaveDiagnostics(new[] - { + result.ExcludingLinterDiagnostics().Should().HaveDiagnostics( + [ ("BCP035", DiagnosticLevel.Error, "The specified \"resource\" declaration is missing the following required properties: \"name\".") - }); + ]); } [TestMethod] @@ -152,10 +152,10 @@ public void MissingModuleExpectedVariantPropertiesShouldProduceNoWarning() var result = CompilationHelper.Compile( ("main.bicep", text), ("mod.bicep", "param foo string")); - result.ExcludingLinterDiagnostics().Should().HaveDiagnostics(new[] -{ + result.ExcludingLinterDiagnostics().Should().HaveDiagnostics( +[ ("BCP035", DiagnosticLevel.Error, "The specified \"module\" declaration is missing the following required properties: \"name\".") - }); + ]); } [TestMethod] @@ -178,11 +178,11 @@ public void InvariantModuleNameShouldProduceWarning() var result = CompilationHelper.Compile( ("main.bicep", text), ("mod.bicep", "param foo string")); - result.ExcludingLinterDiagnostics().Should().HaveDiagnostics(new[] - { + result.ExcludingLinterDiagnostics().Should().HaveDiagnostics( + [ ("BCP179", DiagnosticLevel.Warning, "Unique resource or deployment name is required when looping. The loop item variable \"a\" must be referenced in at least one of the value expressions of the following properties: \"name\", \"scope\""), ("BCP179", DiagnosticLevel.Warning, "Unique resource or deployment name is required when looping. The loop item variable \"x\" or the index variable \"i\" must be referenced in at least one of the value expressions of the following properties in the loop body: \"name\", \"scope\"") - }); + ]); } [TestMethod] @@ -201,11 +201,11 @@ public void InvariantResourceNameShouldProduceWarning() "; var result = CompilationHelper.Compile(text); - result.ExcludingLinterDiagnostics().Should().HaveDiagnostics(new[] - { + result.ExcludingLinterDiagnostics().Should().HaveDiagnostics( + [ ("BCP179", DiagnosticLevel.Warning, "Unique resource or deployment name is required when looping. The loop item variable \"item\" or the index variable \"i\" must be referenced in at least one of the value expressions of the following properties in the loop body: \"name\""), ("BCP179", DiagnosticLevel.Warning, "Unique resource or deployment name is required when looping. The loop item variable \"item\" must be referenced in at least one of the value expressions of the following properties: \"name\"") - }); + ]); } [TestMethod] @@ -227,10 +227,10 @@ public void OptionalInvariantResourcePropertiesWhenRequiredPropertyIsMissingShou }] "; var result = CompilationHelper.Compile(text); - result.ExcludingLinterDiagnostics().Should().HaveDiagnostics(new[] - { + result.ExcludingLinterDiagnostics().Should().HaveDiagnostics( + [ ("BCP035", DiagnosticLevel.Error, "The specified \"resource\" declaration is missing the following required properties: \"name\".") - }); + ]); } [TestMethod] @@ -252,10 +252,10 @@ public void OptionalInvariantModulePropertiesWhenRequiredPropertyIsMissingShould var result = CompilationHelper.Compile( ("main.bicep", text), ("mod.bicep", "param foo string")); - result.ExcludingLinterDiagnostics().Should().HaveDiagnostics(new[] -{ + result.ExcludingLinterDiagnostics().Should().HaveDiagnostics( +[ ("BCP035", DiagnosticLevel.Error, "The specified \"module\" declaration is missing the following required properties: \"name\".") - }); + ]); } [TestMethod] @@ -280,11 +280,11 @@ public void MultipleInvariantModulePropertiesShouldProduceWarning() var result = CompilationHelper.Compile( ("main.bicep", text), ("mod.bicep", "param foo string")); - result.ExcludingLinterDiagnostics().Should().HaveDiagnostics(new[] - { + result.ExcludingLinterDiagnostics().Should().HaveDiagnostics( + [ ("BCP179", DiagnosticLevel.Warning, "Unique resource or deployment name is required when looping. The loop item variable \"a\" must be referenced in at least one of the value expressions of the following properties: \"name\", \"scope\""), ("BCP179", DiagnosticLevel.Warning, "Unique resource or deployment name is required when looping. The loop item variable \"x\" or the index variable \"i\" must be referenced in at least one of the value expressions of the following properties in the loop body: \"name\", \"scope\"") - }); + ]); } [TestMethod] diff --git a/src/Bicep.Core.IntegrationTests/ModuleTests.cs b/src/Bicep.Core.IntegrationTests/ModuleTests.cs index 0cefc21923e..34c5d098887 100644 --- a/src/Bicep.Core.IntegrationTests/ModuleTests.cs +++ b/src/Bicep.Core.IntegrationTests/ModuleTests.cs @@ -113,9 +113,9 @@ param inputb string var compilation = Services.BuildCompilation(files, mainUri); var (success, diagnosticsByFile) = GetSuccessAndDiagnosticsByFile(compilation); - diagnosticsByFile[mainUri].Should().HaveDiagnostics(new[] { + diagnosticsByFile[mainUri].Should().HaveDiagnostics([ ("BCP094", DiagnosticLevel.Error, "This module references itself, which is not allowed."), - }); + ]); success.Should().BeFalse(); } @@ -167,15 +167,15 @@ param inputb string var compilation = Services.BuildCompilation(files, mainUri); var (success, diagnosticsByFile) = GetSuccessAndDiagnosticsByFile(compilation); - diagnosticsByFile[mainUri].Should().HaveDiagnostics(new[] { + diagnosticsByFile[mainUri].Should().HaveDiagnostics([ ("BCP095", DiagnosticLevel.Error, "The file is involved in a cycle (\"/modulea.bicep\" -> \"/moduleb.bicep\" -> \"/main.bicep\")."), - }); - diagnosticsByFile[moduleAUri].Should().HaveDiagnostics(new[] { + ]); + diagnosticsByFile[moduleAUri].Should().HaveDiagnostics([ ("BCP095", DiagnosticLevel.Error, "The file is involved in a cycle (\"/moduleb.bicep\" -> \"/main.bicep\" -> \"/modulea.bicep\")."), - }); - diagnosticsByFile[moduleBUri].Should().HaveDiagnostics(new[] { + ]); + diagnosticsByFile[moduleBUri].Should().HaveDiagnostics([ ("BCP095", DiagnosticLevel.Error, "The file is involved in a cycle (\"/main.bicep\" -> \"/modulea.bicep\" -> \"/moduleb.bicep\")."), - }); + ]); success.Should().BeFalse(); } @@ -226,9 +226,9 @@ param inputb string var compilation = await compiler.CreateCompilation(mainFileUri); var (success, diagnosticsByFile) = GetSuccessAndDiagnosticsByFile(compilation); - diagnosticsByFile[mainFileUri].Should().HaveDiagnostics(new[] { + diagnosticsByFile[mainFileUri].Should().HaveDiagnostics([ ("BCP093", DiagnosticLevel.Error, "File path \"modulea.bicep\" could not be resolved relative to \"/path/to/main.bicep\"."), - }); + ]); } [TestMethod] @@ -368,9 +368,9 @@ param inputb string var compilation = await compiler.CreateCompilation(mainUri); var (success, diagnosticsByFile) = GetSuccessAndDiagnosticsByFile(compilation); - diagnosticsByFile[mainUri].Should().HaveDiagnostics(new[] { + diagnosticsByFile[mainUri].Should().HaveDiagnostics([ ("BCP091", DiagnosticLevel.Error, "An error occurred reading file. Mock read failure!"), - }); + ]); } [TestMethod] @@ -379,10 +379,10 @@ public void External_module_reference_with_unknown_scheme_should_be_rejected() var services = new ServiceBuilder().WithFeatureOverrides(new(TestContext, RegistryEnabled: true)); var result = CompilationHelper.Compile(services, @"module test 'fake:totally-fake' = {}"); - result.Should().HaveDiagnostics(new[] - { + result.Should().HaveDiagnostics( + [ ("BCP189", DiagnosticLevel.Error, "The specified module reference scheme \"fake\" is not recognized. Specify a path to a local module file or a module reference using one of the following schemes: \"br\", \"ts\"") - }); + ]); } [TestMethod] @@ -407,11 +407,11 @@ param p resource 'Microsoft.Storage/storageAccounts@2019-06-01' output out string = p.properties.accessTier ")); - result.Should().HaveDiagnostics(new[] - { + result.Should().HaveDiagnostics( + [ ("BCP104", DiagnosticLevel.Error, "The referenced module has errors."), ("BCP036", DiagnosticLevel.Error, "The property \"p\" expected a value of type \"error\" but the provided value is of type \"Microsoft.Storage/storageAccounts@2019-06-01\".") - }); + ]); } [TestMethod] @@ -431,10 +431,10 @@ public void Module_cannot_use_resource_typed_output_without_feature_enabled() output storage resource = storage ")); - result.Should().HaveDiagnostics(new[] - { + result.Should().HaveDiagnostics( + [ ("BCP104", DiagnosticLevel.Error, "The referenced module has errors.") - }); + ]); } [TestMethod] @@ -655,18 +655,18 @@ param p resource 'Some.Fake/Type@2019-06-01' var diagnosticsMap = result.Compilation.GetAllDiagnosticsByBicepFile().ToDictionary(kvp => kvp.Key.FileUri, kvp => kvp.Value); using (new AssertionScope()) { - diagnosticsMap[InMemoryFileResolver.GetFileUri("/path/to/module.bicep")].Should().HaveDiagnostics(new[] - { + diagnosticsMap[InMemoryFileResolver.GetFileUri("/path/to/module.bicep")].Should().HaveDiagnostics( + [ ("BCP081", DiagnosticLevel.Warning, "Resource type \"Some.Fake/Type@2019-06-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."), ("BCP081", DiagnosticLevel.Warning, "Resource type \"Another.Fake/Type@2019-06-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."), ("BCP081", DiagnosticLevel.Warning, "Resource type \"Another.Fake/Type@2019-06-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."), - }); - diagnosticsMap[InMemoryFileResolver.GetFileUri("/path/to/main.bicep")].Should().HaveDiagnostics(new[] - { + ]); + diagnosticsMap[InMemoryFileResolver.GetFileUri("/path/to/main.bicep")].Should().HaveDiagnostics( + [ ("BCP230", DiagnosticLevel.Warning, "The referenced module uses resource type \"Some.Fake/Type@2019-06-01\" which 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."), ("BCP230", DiagnosticLevel.Warning, "The referenced module uses resource type \"Another.Fake/Type@2019-06-01\" which 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."), ("BCP036", DiagnosticLevel.Error, "The property \"p\" expected a value of type \"Some.Fake/Type\" but the provided value is of type \"'something'\"."), - }); + ]); } } @@ -693,10 +693,10 @@ param p resource 'Microsoft.Sql/servers@2021-02-01-preview' output out string = p.properties.minimalTlsVersion ")); - result.Should().HaveDiagnostics(new[] - { + result.Should().HaveDiagnostics( + [ ("BCP036", DiagnosticLevel.Error, "The property \"p\" expected a value of type \"Microsoft.Sql/servers\" but the provided value is of type \"Microsoft.Storage/storageAccounts@2019-06-01\"."), - }); + ]); } [TestMethod] diff --git a/src/Bicep.Core.IntegrationTests/NestedResourceTests.cs b/src/Bicep.Core.IntegrationTests/NestedResourceTests.cs index 908bd269d38..d530367c580 100644 --- a/src/Bicep.Core.IntegrationTests/NestedResourceTests.cs +++ b/src/Bicep.Core.IntegrationTests/NestedResourceTests.cs @@ -202,11 +202,11 @@ public void NestedResources_invalid_resource_references() var model = Services.BuildCompilation(program).GetEntrypointSemanticModel(); - model.GetAllDiagnostics().ExcludingLinterDiagnostics().ExcludingMissingTypes().Should().HaveDiagnostics(new[]{ + model.GetAllDiagnostics().ExcludingLinterDiagnostics().ExcludingMissingTypes().Should().HaveDiagnostics([ ("BCP158", DiagnosticLevel.Error, "Cannot access nested resources of type \"'hi'\". A resource type is required."), ("BCP159", DiagnosticLevel.Error, "The resource \"parent\" does not contain a nested resource named \"child2\". Known nested resources are: \"child\"."), ("BCP159", DiagnosticLevel.Error, "The resource \"child\" does not contain a nested resource named \"cousin\". Known nested resources are: \"grandchild\"."), - }); + ]); } [TestMethod] @@ -235,9 +235,9 @@ public void NestedResources_child_cannot_be_referenced_outside_of_scope() "; var diagnostics = Services.BuildCompilation(program).GetEntrypointSemanticModel().GetAllDiagnostics(); - diagnostics.ExcludingLinterDiagnostics().ExcludingMissingTypes().Should().HaveDiagnostics(new[] { + diagnostics.ExcludingLinterDiagnostics().ExcludingMissingTypes().Should().HaveDiagnostics([ ("BCP057", DiagnosticLevel.Error, "The name \"child\" does not exist in the current context."), - }); + ]); } [TestMethod] @@ -259,9 +259,9 @@ public void NestedResources_child_cannot_specify_qualified_type() "; var diagnostics = Services.BuildCompilation(program).GetEntrypointSemanticModel().GetAllDiagnostics(); - diagnostics.ExcludingLinterDiagnostics().ExcludingMissingTypes().Should().HaveDiagnostics(new[] { + diagnostics.ExcludingLinterDiagnostics().ExcludingMissingTypes().Should().HaveDiagnostics([ ("BCP156", DiagnosticLevel.Error, "The resource type segment \"My.RP/parentType/childType@2020-01-01\" is invalid. Nested resources must specify a single type segment, and optionally can specify an api version using the format \"@\"."), - }); + ]); } [TestMethod] @@ -283,10 +283,10 @@ public void NestedResources_error_in_base_type() "; var diagnostics = Services.BuildCompilation(program).GetEntrypointSemanticModel().GetAllDiagnostics(); - diagnostics.ExcludingLinterDiagnostics().Should().HaveDiagnostics(new[] { + diagnostics.ExcludingLinterDiagnostics().Should().HaveDiagnostics([ ("BCP029", DiagnosticLevel.Error, "The resource type is not valid. Specify a valid resource type of format \"@\"."), ("BCP157", DiagnosticLevel.Error, "The resource type cannot be determined due to an error in the containing resource."), - }); + ]); } [TestMethod] @@ -314,10 +314,10 @@ public void NestedResources_error_in_parent_type() "; var diagnostics = Services.BuildCompilation(program).GetEntrypointSemanticModel().GetAllDiagnostics(); - diagnostics.ExcludingLinterDiagnostics().ExcludingMissingTypes().Should().HaveDiagnostics(new[] { + diagnostics.ExcludingLinterDiagnostics().ExcludingMissingTypes().Should().HaveDiagnostics([ ("BCP156", DiagnosticLevel.Error, "The resource type segment \"My.RP/parentType/childType@2020-01-01\" is invalid. Nested resources must specify a single type segment, and optionally can specify an api version using the format \"@\"."), ("BCP157", DiagnosticLevel.Error, "The resource type cannot be determined due to an error in the containing resource."), - }); + ]); } [TestMethod] @@ -339,9 +339,9 @@ public void NestedResources_child_cycle_is_detected_correctly() } "; - Services.BuildCompilation(program).GetEntrypointSemanticModel().GetAllDiagnostics().ExcludingLinterDiagnostics().ExcludingMissingTypes().Should().HaveDiagnostics(new[] { + Services.BuildCompilation(program).GetEntrypointSemanticModel().GetAllDiagnostics().ExcludingLinterDiagnostics().ExcludingMissingTypes().Should().HaveDiagnostics([ ("BCP080", DiagnosticLevel.Error, "The expression is involved in a cycle (\"child\" -> \"parent\")."), - }); + ]); } [TestMethod] // With more than one level of nesting the name just isn't visible. @@ -369,9 +369,9 @@ public void NestedResources_grandchild_cycle_results_in_binding_failure() } "; - Services.BuildCompilation(program).GetEntrypointSemanticModel().GetAllDiagnostics().ExcludingLinterDiagnostics().ExcludingMissingTypes().Should().HaveDiagnostics(new[] { + Services.BuildCompilation(program).GetEntrypointSemanticModel().GetAllDiagnostics().ExcludingLinterDiagnostics().ExcludingMissingTypes().Should().HaveDiagnostics([ ("BCP057", DiagnosticLevel.Error, "The name \"grandchild\" does not exist in the current context."), - }); + ]); } [TestMethod] @@ -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. @@ -488,12 +488,12 @@ public void NestedResources_cannot_appear_inside_loops() using (new AssertionScope()) { template.Should().NotHaveValue(); - diags.ExcludingLinterDiagnostics().ExcludingMissingTypes().Should().HaveDiagnostics(new[] - { + diags.ExcludingLinterDiagnostics().ExcludingMissingTypes().Should().HaveDiagnostics( + [ ("BCP179", DiagnosticLevel.Warning,"Unique resource or deployment name is required when looping. The loop item variable \"item\" must be referenced in at least one of the value expressions of the following properties: \"name\", \"scope\""), ("BCP160", DiagnosticLevel.Error, "A nested resource cannot appear inside of a resource with a for-expression."), ("BCP157", DiagnosticLevel.Error, "The resource type cannot be determined due to an error in the containing resource."), - }); + ]); } } @@ -522,10 +522,10 @@ public void NestedResources_can_have_loops() using (new AssertionScope()) { - diags.ExcludingLinterDiagnostics().ExcludingMissingTypes().Should().HaveDiagnostics(new[] - { + diags.ExcludingLinterDiagnostics().ExcludingMissingTypes().Should().HaveDiagnostics( + [ ("BCP179",DiagnosticLevel.Warning,"Unique resource or deployment name is required when looping. The loop item variable \"item\" must be referenced in at least one of the value expressions of the following properties: \"name\", \"scope\"") - }); + ]); template.Should().NotBeNull(); } } @@ -566,10 +566,10 @@ public void NestedResources_provides_correct_error_for_resource_access_with_brok output foo string = broken::fake "); - result.ExcludingLinterDiagnostics().Should().HaveDiagnostics(new[] { + result.ExcludingLinterDiagnostics().Should().HaveDiagnostics([ ("BCP118", DiagnosticLevel.Error, "Expected the \"{\" character, the \"[\" character, or the \"if\" keyword at this location."), ("BCP159", DiagnosticLevel.Error, "The resource \"broken\" does not contain a nested resource named \"fake\". Known nested resources are: \"(none)\"."), - }); + ]); } [TestMethod] @@ -765,9 +765,9 @@ public void Nested_resource_blocks_existing_parents_at_different_scopes(string p } "); - result.Diagnostics.ExcludingLinterDiagnostics().ExcludingMissingTypes().Should().HaveDiagnostics(new[] { + result.Diagnostics.ExcludingLinterDiagnostics().ExcludingMissingTypes().Should().HaveDiagnostics([ ("BCP165", DiagnosticLevel.Error, "A resource's computed scope must match that of the Bicep file for it to be deployable. This resource's scope is computed from the \"scope\" property value assigned to ancestor resource \"res1\". You must use modules to deploy resources to a different scope."), - }); + ]); } [TestMethod] @@ -810,9 +810,9 @@ public void Nested_resource_blocks_scope_on_child_resources() using (new AssertionScope()) { template.Should().NotHaveValue(); - diags.ExcludingLinterDiagnostics().ExcludingMissingTypes().Should().HaveDiagnostics(new[] { + diags.ExcludingLinterDiagnostics().ExcludingMissingTypes().Should().HaveDiagnostics([ ("BCP164", DiagnosticLevel.Error, "A child resource's scope is computed based on the scope of its ancestor resource. This means that using the \"scope\" property on a child resource is unsupported."), - }); + ]); } } @@ -836,10 +836,10 @@ public void Nested_resource_detects_invalid_child_resource_literal_names() using (new AssertionScope()) { template.Should().NotHaveValue(); - diags.ExcludingLinterDiagnostics().ExcludingMissingTypes().Should().HaveDiagnostics(new[] { + diags.ExcludingLinterDiagnostics().ExcludingMissingTypes().Should().HaveDiagnostics([ ("BCP170", DiagnosticLevel.Error, "Expected resource name to not contain any \"/\" characters. Child resources with a parent resource reference (via the parent property or via nesting) must not contain a fully-qualified name."), ("BCP170", DiagnosticLevel.Error, "Expected resource name to not contain any \"/\" characters. Child resources with a parent resource reference (via the parent property or via nesting) must not contain a fully-qualified name."), - }); + ]); } } } diff --git a/src/Bicep.Core.IntegrationTests/NestedRuntimeMemberAccessTests.cs b/src/Bicep.Core.IntegrationTests/NestedRuntimeMemberAccessTests.cs index e94df69fa07..de6225c61aa 100644 --- a/src/Bicep.Core.IntegrationTests/NestedRuntimeMemberAccessTests.cs +++ b/src/Bicep.Core.IntegrationTests/NestedRuntimeMemberAccessTests.cs @@ -52,14 +52,14 @@ public void Nested_runtime_member_access_is_not_supported() var qux = windowsVMDsc2.properties var quux = diag.properties "); - result.ExcludingLinterDiagnostics().Should().HaveDiagnostics(new[] - { + result.ExcludingLinterDiagnostics().Should().HaveDiagnostics( + [ ("BCP307", DiagnosticLevel.Error, @"The expression cannot be evaluated, because the identifier properties of the referenced existing resource including ""name"" cannot be calculated at the start of the deployment. In this situation, the accessible properties of ""windowsVMDsc"" include ""apiVersion"", ""id"", ""name"", ""type""."), ("BCP307", DiagnosticLevel.Error, @"The expression cannot be evaluated, because the identifier properties of the referenced existing resource including ""name"" cannot be calculated at the start of the deployment. In this situation, the accessible properties of ""storage"" include ""apiVersion"", ""id"", ""name"", ""type""."), ("BCP307", DiagnosticLevel.Error, @"The expression cannot be evaluated, because the identifier properties of the referenced existing resource including ""name"" cannot be calculated at the start of the deployment. In this situation, the accessible properties of ""storage"" include ""apiVersion"", ""id"", ""name"", ""type""."), ("BCP307", DiagnosticLevel.Error, @"The expression cannot be evaluated, because the identifier properties of the referenced existing resource including ""parent"" cannot be calculated at the start of the deployment. In this situation, the accessible properties of ""windowsVMDsc2"" include ""apiVersion"", ""id"", ""name"", ""type""."), ("BCP307", DiagnosticLevel.Error, @"The expression cannot be evaluated, because the identifier properties of the referenced existing resource including ""scope"" cannot be calculated at the start of the deployment. In this situation, the accessible properties of ""diag"" include ""apiVersion"", ""id"", ""name"", ""type""."), - }); + ]); } } } diff --git a/src/Bicep.Core.IntegrationTests/NewLineSensitivityTests.cs b/src/Bicep.Core.IntegrationTests/NewLineSensitivityTests.cs index 4b7d65b5e78..1df35b2efde 100644 --- a/src/Bicep.Core.IntegrationTests/NewLineSensitivityTests.cs +++ b/src/Bicep.Core.IntegrationTests/NewLineSensitivityTests.cs @@ -74,9 +74,9 @@ public void Function_arguments_must_be_separated_by_a_comma() output test1 string = concat('foo' 'bar') "); - result.ExcludingLinterDiagnostics().Should().HaveDiagnostics(new[] { + result.ExcludingLinterDiagnostics().Should().HaveDiagnostics([ ("BCP236", DiagnosticLevel.Error, "Expected a new line or comma character at this location."), - }); + ]); } [TestMethod] @@ -86,9 +86,9 @@ public void Function_argument_should_raise_error_for_trailing_comma() output test1 string = concat('foo',) "); - result.ExcludingLinterDiagnostics().Should().HaveDiagnostics(new[] { + result.ExcludingLinterDiagnostics().Should().HaveDiagnostics([ ("BCP009", DiagnosticLevel.Error, "Expected a literal value, an array, an object, a parenthesized expression, or a function call at this location."), - }); + ]); } [TestMethod] @@ -98,9 +98,9 @@ public void Function_argument_error_recovery_works() output test1 string = concat('foo', 'bar' "); - result.ExcludingLinterDiagnostics().Should().HaveDiagnostics(new[] { + result.ExcludingLinterDiagnostics().Should().HaveDiagnostics([ ("BCP018", DiagnosticLevel.Error, "Expected the \")\" character at this location."), - }); + ]); } [TestMethod] @@ -257,11 +257,11 @@ public void Array_item_commas_are_not_permitted_on_multi_line_definition() ] "); - result.ExcludingLinterDiagnostics().Should().HaveDiagnostics(new[] { + result.ExcludingLinterDiagnostics().Should().HaveDiagnostics([ ("BCP238", DiagnosticLevel.Error, "Unexpected new line character after a comma."), ("BCP238", DiagnosticLevel.Error, "Unexpected new line character after a comma."), ("BCP238", DiagnosticLevel.Error, "Unexpected new line character after a comma."), - }); + ]); } [TestMethod] @@ -271,9 +271,9 @@ public void Array_item_error_recovery_works() output test1 array = ['foo', 'bar' "); - result.ExcludingLinterDiagnostics().Should().HaveDiagnostics(new[] { + result.ExcludingLinterDiagnostics().Should().HaveDiagnostics([ ("BCP018", DiagnosticLevel.Error, "Expected the \"]\" character at this location."), - }); + ]); } @@ -358,11 +358,11 @@ public void Object_item_commas_are_not_permitted_on_multi_line_definition() } "); - result.ExcludingLinterDiagnostics().Should().HaveDiagnostics(new[] { + result.ExcludingLinterDiagnostics().Should().HaveDiagnostics([ ("BCP238", DiagnosticLevel.Error, "Unexpected new line character after a comma."), ("BCP238", DiagnosticLevel.Error, "Unexpected new line character after a comma."), ("BCP238", DiagnosticLevel.Error, "Unexpected new line character after a comma."), - }); + ]); } [TestMethod] @@ -372,9 +372,9 @@ public void Object_item_error_recovery_works() output test1 object = { abc: 'foo', def: 'bar' "); - result.ExcludingLinterDiagnostics().Should().HaveDiagnostics(new[] { + result.ExcludingLinterDiagnostics().Should().HaveDiagnostics([ ("BCP018", DiagnosticLevel.Error, "Expected the \"}\" character at this location."), - }); + ]); } } } diff --git a/src/Bicep.Core.IntegrationTests/OutputsTests.cs b/src/Bicep.Core.IntegrationTests/OutputsTests.cs index 0e3c1cde212..ec4c0e3881b 100644 --- a/src/Bicep.Core.IntegrationTests/OutputsTests.cs +++ b/src/Bicep.Core.IntegrationTests/OutputsTests.cs @@ -203,12 +203,12 @@ public void Output_can_have_warnings_for_missing_type() output out resource 'Some.Fake/Type@2019-06-01' = resource """); - result.ExcludingLinterDiagnostics().Should().HaveDiagnostics(new[] - { + result.ExcludingLinterDiagnostics().Should().HaveDiagnostics( + [ // There are two warnings because there are two places in code to correct the missing type. ("BCP081", DiagnosticLevel.Warning, "Resource type \"Some.Fake/Type@2019-06-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."), ("BCP081", DiagnosticLevel.Warning, "Resource type \"Some.Fake/Type@2019-06-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] @@ -224,10 +224,10 @@ public void Output_can_have_warnings_for_missing_type_but_we_dont_duplicate_them output out resource = resource """); - result.ExcludingLinterDiagnostics().Should().HaveDiagnostics(new[] - { + result.ExcludingLinterDiagnostics().Should().HaveDiagnostics( + [ ("BCP081", DiagnosticLevel.Warning, "Resource type \"Some.Fake/Type@2019-06-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] @@ -246,10 +246,10 @@ provider bar with { output out resource = container """); - result.ExcludingLinterDiagnostics().Should().HaveDiagnostics(new[] - { + result.ExcludingLinterDiagnostics().Should().HaveDiagnostics( + [ ("BCP227", DiagnosticLevel.Error, "The type \"container\" cannot be used as a parameter or output type. Extensibility types are currently not supported as parameters or outputs."), - }); + ]); } } } diff --git a/src/Bicep.Core.IntegrationTests/ParameterFileTests.cs b/src/Bicep.Core.IntegrationTests/ParameterFileTests.cs index 8d32966413f..af431e134dd 100644 --- a/src/Bicep.Core.IntegrationTests/ParameterFileTests.cs +++ b/src/Bicep.Core.IntegrationTests/ParameterFileTests.cs @@ -75,10 +75,10 @@ param foo string using (new AssertionScope()) { result.Parameters.Should().BeNull(); - result.Diagnostics.Should().HaveDiagnostics(new[] - { + result.Diagnostics.Should().HaveDiagnostics( + [ ("BCP261", DiagnosticLevel.Error, "A using declaration must be present in this parameters file.") - }); + ]); } } @@ -92,9 +92,9 @@ public void Parameters_file_cannot_reference_non_existing_env_variable() "), ("foo.bicep", @"param fromEnv string")); - result.ExcludingLinterDiagnostics().Should().HaveDiagnostics(new[]{ + result.ExcludingLinterDiagnostics().Should().HaveDiagnostics([ ("BCP338", DiagnosticLevel.Error, - "Failed to evaluate parameter \"stringEnvVariable\": Environment variable does not exist, and no default value set")}); + "Failed to evaluate parameter \"stringEnvVariable\": Environment variable does not exist, and no default value set")]); } [TestMethod] @@ -151,10 +151,10 @@ param foo string ")); result.Should().NotGenerateParameters(); - result.Should().HaveDiagnostics(new[] { + result.Should().HaveDiagnostics([ ("BCP065", DiagnosticLevel.Error, """Function "utcNow" is not valid at this location. It can only be used as a parameter default value."""), ("BCP062", DiagnosticLevel.Error, """The referenced declaration with name "abc" is not valid."""), - }); + ]); } [TestMethod] diff --git a/src/Bicep.Core.IntegrationTests/ParametersTests.cs b/src/Bicep.Core.IntegrationTests/ParametersTests.cs index f39b86e9fd9..b3c8c074f76 100644 --- a/src/Bicep.Core.IntegrationTests/ParametersTests.cs +++ b/src/Bicep.Core.IntegrationTests/ParametersTests.cs @@ -167,10 +167,10 @@ param p resource 'Some.Fake/Type@2019-06-01' output id string = p.id "); - result.ExcludingLinterDiagnostics().Should().HaveDiagnostics(new[] - { + result.ExcludingLinterDiagnostics().Should().HaveDiagnostics( + [ ("BCP081", DiagnosticLevel.Warning, "Resource type \"Some.Fake/Type@2019-06-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] @@ -184,11 +184,11 @@ provider bar with { param container resource 'stg:container' output name string = container.name // silence unused params warning """); - result.ExcludingLinterDiagnostics().Should().HaveDiagnostics(new[] - { + result.ExcludingLinterDiagnostics().Should().HaveDiagnostics( + [ ("BCP227", DiagnosticLevel.Error, "The type \"container\" cannot be used as a parameter or output type. Extensibility types are currently not supported as parameters or outputs."), ("BCP062", DiagnosticLevel.Error, "The referenced declaration with name \"container\" is not valid."), - }); + ]); } [TestMethod] @@ -202,11 +202,11 @@ param p resource 'Microsoft.Storage/storageAccounts@2019-06-01' name: 'resource' }"); - result.ExcludingLinterDiagnostics().Should().HaveDiagnostics(new[] - { + result.ExcludingLinterDiagnostics().Should().HaveDiagnostics( + [ ("BCP081", DiagnosticLevel.Warning, "Resource type \"My.Rp/myResource@2020-01-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."), ("BCP229", DiagnosticLevel.Error, "The parameter \"p\" cannot be used as a resource scope or parent. Resources passed as parameters cannot be used as a scope or parent of a resource."), - }); + ]); } [TestMethod] @@ -225,12 +225,12 @@ param p resource 'Microsoft.Storage/storageAccounts@2019-06-01' } }"); - result.ExcludingLinterDiagnostics().Should().HaveDiagnostics(new[] - { + result.ExcludingLinterDiagnostics().Should().HaveDiagnostics( + [ ("BCP081", DiagnosticLevel.Warning, "Resource type \"Microsoft.Storage/storageAccounts/tableServices@2020-06-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."), ("BCP229", DiagnosticLevel.Error, "The parameter \"p\" cannot be used as a resource scope or parent. Resources passed as parameters cannot be used as a scope or parent of a resource."), ("BCP169", DiagnosticLevel.Error, "Expected resource name to contain 1 \"/\" character(s). The number of name segments must match the number of segments in the resource type."), - }); + ]); } [TestMethod] @@ -287,10 +287,10 @@ param foo string param bar string ")); - result.ExcludingLinterDiagnostics().Should().HaveDiagnostics(new[] { + result.ExcludingLinterDiagnostics().Should().HaveDiagnostics([ ("BCP065", DiagnosticLevel.Error, "Function \"utcNow\" is not valid at this location. It can only be used as a parameter default value."), ("BCP065", DiagnosticLevel.Error, "Function \"newGuid\" is not valid at this location. It can only be used as a parameter default value."), - }); + ]); } [TestMethod] @@ -308,10 +308,10 @@ param foo string param bar object ")); - result.ExcludingLinterDiagnostics().Should().HaveDiagnostics(new[] { + result.ExcludingLinterDiagnostics().Should().HaveDiagnostics([ ("BCP057", DiagnosticLevel.Error, "The name \"resourceId\" does not exist in the current context."), ("BCP057", DiagnosticLevel.Error, "The name \"deployment\" does not exist in the current context."), - }); + ]); } [TestMethod] diff --git a/src/Bicep.Core.IntegrationTests/ParentPropertyResourceTests.cs b/src/Bicep.Core.IntegrationTests/ParentPropertyResourceTests.cs index c46bff22641..eb5e35294a3 100644 --- a/src/Bicep.Core.IntegrationTests/ParentPropertyResourceTests.cs +++ b/src/Bicep.Core.IntegrationTests/ParentPropertyResourceTests.cs @@ -248,9 +248,9 @@ public void Parent_property_blocks_existing_parents_at_different_scopes(string p } "); - result.Diagnostics.ExcludingLinterDiagnostics().ExcludingMissingTypes().Should().HaveDiagnostics(new[] { + result.Diagnostics.ExcludingLinterDiagnostics().ExcludingMissingTypes().Should().HaveDiagnostics([ ("BCP165", DiagnosticLevel.Error, "A resource's computed scope must match that of the Bicep file for it to be deployable. This resource's scope is computed from the \"scope\" property value assigned to ancestor resource \"res1\". You must use modules to deploy resources to a different scope."), - }); + ]); } [TestMethod] @@ -295,9 +295,9 @@ public void Parent_property_blocks_scope_on_child_resources() using (new AssertionScope()) { template.Should().NotHaveValue(); - diags.ExcludingLinterDiagnostics().ExcludingMissingTypes().Should().HaveDiagnostics(new[] { + diags.ExcludingLinterDiagnostics().ExcludingMissingTypes().Should().HaveDiagnostics([ ("BCP164", DiagnosticLevel.Error, "A child resource's scope is computed based on the scope of its ancestor resource. This means that using the \"scope\" property on a child resource is unsupported."), - }); + ]); } } @@ -315,9 +315,9 @@ public void Parent_property_self_cycles_are_blocked() using (new AssertionScope()) { template.Should().NotHaveValue(); - diags.ExcludingLinterDiagnostics().ExcludingMissingTypes().Should().HaveDiagnostics(new[] { + diags.ExcludingLinterDiagnostics().ExcludingMissingTypes().Should().HaveDiagnostics([ ("BCP079", DiagnosticLevel.Error, "This expression is referencing its own declaration, which is not allowed.") - }); + ]); } } @@ -339,10 +339,10 @@ public void Parent_property_2_cycles_are_blocked() using (new AssertionScope()) { template.Should().NotHaveValue(); - diags.ExcludingLinterDiagnostics().ExcludingMissingTypes().Should().HaveDiagnostics(new[] { + diags.ExcludingLinterDiagnostics().ExcludingMissingTypes().Should().HaveDiagnostics([ ("BCP080", DiagnosticLevel.Error, "The expression is involved in a cycle (\"vmExt\" -> \"vm\")."), ("BCP080", DiagnosticLevel.Error, "The expression is involved in a cycle (\"vm\" -> \"vmExt\").") - }); + ]); } } @@ -363,9 +363,9 @@ public void Parent_property_blocks_invalid_child_resources() using (new AssertionScope()) { template.Should().NotHaveValue(); - diags.ExcludingLinterDiagnostics().ExcludingMissingTypes().Should().HaveDiagnostics(new[] { + diags.ExcludingLinterDiagnostics().ExcludingMissingTypes().Should().HaveDiagnostics([ ("BCP036", DiagnosticLevel.Error, "The property \"parent\" expected a value of type \"Microsoft.Rp2/resource2\" but the provided value is of type \"Microsoft.Rp1/resource1@2020-06-01\"."), - }); + ]); } } @@ -386,10 +386,10 @@ public void Parent_property_blocks_non_resource_reference() using (new AssertionScope()) { template.Should().NotHaveValue(); - diags.ExcludingLinterDiagnostics().ExcludingMissingTypes().Should().HaveDiagnostics(new[] { + diags.ExcludingLinterDiagnostics().ExcludingMissingTypes().Should().HaveDiagnostics([ ("BCP047", DiagnosticLevel.Error, "String interpolation is unsupported for specifying the resource type."), ("BCP062", DiagnosticLevel.Error, "The referenced declaration with name \"res1\" is not valid."), - }); + ]); } } @@ -415,10 +415,10 @@ public void Parent_property_detects_invalid_child_resource_literal_names() using (new AssertionScope()) { template.Should().NotHaveValue(); - diags.ExcludingLinterDiagnostics().ExcludingMissingTypes().Should().HaveDiagnostics(new[] { + diags.ExcludingLinterDiagnostics().ExcludingMissingTypes().Should().HaveDiagnostics([ ("BCP170", DiagnosticLevel.Error, "Expected resource name to not contain any \"/\" characters. Child resources with a parent resource reference (via the parent property or via nesting) must not contain a fully-qualified name."), ("BCP170", DiagnosticLevel.Error, "Expected resource name to not contain any \"/\" characters. Child resources with a parent resource reference (via the parent property or via nesting) must not contain a fully-qualified name."), - }); + ]); } } @@ -434,9 +434,9 @@ public void Top_level_resource_should_have_appropriate_number_of_slashes_in_lite using (new AssertionScope()) { template.Should().NotHaveValue(); - diags.ExcludingLinterDiagnostics().ExcludingMissingTypes().Should().HaveDiagnostics(new[] { + diags.ExcludingLinterDiagnostics().ExcludingMissingTypes().Should().HaveDiagnostics([ ("BCP169", DiagnosticLevel.Error, "Expected resource name to contain 0 \"/\" character(s). The number of name segments must match the number of segments in the resource type."), - }); + ]); } (template, diags, _) = CompilationHelper.Compile(@" @@ -448,9 +448,9 @@ public void Top_level_resource_should_have_appropriate_number_of_slashes_in_lite using (new AssertionScope()) { template.Should().NotHaveValue(); - diags.ExcludingLinterDiagnostics().ExcludingMissingTypes().Should().HaveDiagnostics(new[] { + diags.ExcludingLinterDiagnostics().ExcludingMissingTypes().Should().HaveDiagnostics([ ("BCP169", DiagnosticLevel.Error, "Expected resource name to contain 1 \"/\" character(s). The number of name segments must match the number of segments in the resource type."), - }); + ]); } } @@ -469,9 +469,9 @@ param p1 string // There are definitely too many '/' characters in the name - we should return an error. result.Should().NotGenerateATemplate(); - result.Diagnostics.ExcludingLinterDiagnostics().ExcludingMissingTypes().Should().HaveDiagnostics(new[] { + result.Diagnostics.ExcludingLinterDiagnostics().ExcludingMissingTypes().Should().HaveDiagnostics([ ("BCP169", DiagnosticLevel.Error, "Expected resource name to contain 0 \"/\" character(s). The number of name segments must match the number of segments in the resource type."), - }); + ]); result = CompilationHelper.Compile(TestTypeHelper.CreateEmptyResourceTypeLoader(), ("main.bicep", @" diff --git a/src/Bicep.Core.IntegrationTests/ProviderImportTests.cs b/src/Bicep.Core.IntegrationTests/ProviderImportTests.cs index f3e7cd11dec..48da63e89a2 100644 --- a/src/Bicep.Core.IntegrationTests/ProviderImportTests.cs +++ b/src/Bicep.Core.IntegrationTests/ProviderImportTests.cs @@ -55,9 +55,9 @@ public async Task Providers_are_disabled_unless_feature_is_enabled() var result = await CompilationHelper.RestoreAndCompile(services, """ provider az """); - result.Should().HaveDiagnostics(new[] { + result.Should().HaveDiagnostics([ ("BCP203", DiagnosticLevel.Error, "Using provider statements requires enabling EXPERIMENTAL feature \"Extensibility\"."), - }); + ]); } [TestMethod] @@ -83,9 +83,9 @@ public async Task Provider_Statement_With_Invalid_Keyword_Should_Emit_Diagnostic var result = await CompilationHelper.RestoreAndCompile(services, """ provider sys blahblah """); - result.Should().HaveDiagnostics(new[] { + result.Should().HaveDiagnostics([ ("BCP305", DiagnosticLevel.Error, "Expected the \"with\" keyword, \"as\" keyword, or a new line character at this location."), - }); + ]); } [TestMethod] @@ -95,9 +95,9 @@ public async Task Provider_Statement_Without_Brace_Should_Raise_Error() var result = await CompilationHelper.RestoreAndCompile(services, """ provider kubernetes with """); - result.Should().HaveDiagnostics(new[] { + result.Should().HaveDiagnostics([ ("BCP018", DiagnosticLevel.Error, "Expected the \"{\" character at this location."), - }); + ]); } [TestMethod] @@ -110,9 +110,9 @@ provider kubernetes with { namespace: 'bar' } something """); - result.Should().HaveDiagnostics(new[] { + result.Should().HaveDiagnostics([ ("BCP012", DiagnosticLevel.Error, "Expected the \"as\" keyword at this location."), - }); + ]); } [TestMethod] @@ -125,9 +125,9 @@ provider kubernetes with { namespace: 'bar' } as """); - result.Should().HaveDiagnostics(new[] { + result.Should().HaveDiagnostics([ ("BCP202", DiagnosticLevel.Error, "Expected a provider alias name at this location."), - }); + ]); } [TestMethod] @@ -137,9 +137,9 @@ public async Task Provider_Statement_Without_Alias_Name_For_Sys_Should_Raise_Err var result = await CompilationHelper.RestoreAndCompile(services, """ provider sys as """); - result.Should().HaveDiagnostics(new[] { + result.Should().HaveDiagnostics([ ("BCP202", DiagnosticLevel.Error, "Expected a provider alias name at this location."), - }); + ]); } [TestMethod] @@ -150,9 +150,9 @@ provider az with { foo: 'bar' } """); - result.Should().HaveDiagnostics(new[] { + result.Should().HaveDiagnostics([ ("BCP205", DiagnosticLevel.Error, "Provider namespace \"az\" does not support configuration."), - }); + ]); } [TestMethod] @@ -161,9 +161,9 @@ public async Task Imports_return_error_with_unrecognized_namespace() var result = await CompilationHelper.RestoreAndCompile(await GetServices(), @" provider madeUpNamespace "); - result.Should().HaveDiagnostics(new[] { + result.Should().HaveDiagnostics([ ("BCP204", DiagnosticLevel.Error, "Provider namespace \"madeUpNamespace\" is not recognized."), - }); + ]); } [TestMethod] @@ -225,12 +225,12 @@ provider sys as sys1 provider sys as sys2 """); - result.Should().HaveDiagnostics(new[] { + result.Should().HaveDiagnostics([ ("BCP207", DiagnosticLevel.Error, "Namespace \"az\" is declared multiple times. Remove the duplicates."), ("BCP207", DiagnosticLevel.Error, "Namespace \"az\" is declared multiple times. Remove the duplicates."), ("BCP207", DiagnosticLevel.Error, "Namespace \"sys\" is declared multiple times. Remove the duplicates."), ("BCP207", DiagnosticLevel.Error, "Namespace \"sys\" is declared multiple times. Remove the duplicates."), - }); + ]); } [TestMethod] @@ -244,10 +244,10 @@ provider kubernetes with { } as az """); - result.Should().HaveDiagnostics(new[] { + result.Should().HaveDiagnostics([ ("BCP028", DiagnosticLevel.Error, "Identifier \"az\" is declared multiple times. Remove or rename the duplicates."), ("BCP028", DiagnosticLevel.Error, "Identifier \"az\" is declared multiple times. Remove or rename the duplicates."), - }); + ]); } [TestMethod] @@ -261,13 +261,13 @@ public async Task Ambiguous_function_references_must_be_qualified() ConfigurationType: null, ArmTemplateProviderName: "Ns1-Unused", ArmTemplateProviderVersion: "1.0"), - ImmutableArray.Empty, - new[] { + [], + [ new FunctionOverloadBuilder("ns1Func").Build(), new FunctionOverloadBuilder("dupeFunc").Build(), - }, - ImmutableArray.Empty, - ImmutableArray.Empty, + ], + [], + [], new EmptyResourceTypeProvider()); var ns2 = new NamespaceType( @@ -278,13 +278,13 @@ public async Task Ambiguous_function_references_must_be_qualified() ConfigurationType: null, ArmTemplateProviderName: "Ns2-Unused", ArmTemplateProviderVersion: "1.0"), - ImmutableArray.Empty, - new[] { + [], + [ new FunctionOverloadBuilder("ns2Func").Build(), new FunctionOverloadBuilder("dupeFunc").Build(), - }, - ImmutableArray.Empty, - ImmutableArray.Empty, + ], + [], + [], new EmptyResourceTypeProvider()); var nsProvider = TestExtensibilityNamespaceProvider.Create((providerName, aliasName) => providerName switch @@ -313,9 +313,9 @@ provider ns2 output ns2Result string = ns2Func() "); - result.Should().HaveDiagnostics(new[] { + result.Should().HaveDiagnostics([ ("BCP056", DiagnosticLevel.Error, "The reference to name \"dupeFunc\" is ambiguous because it exists in namespaces \"ns1\", \"ns2\". The reference must be fully-qualified."), - }); + ]); // fix by fully-qualifying result = await CompilationHelper.RestoreAndCompile(services, @" @@ -341,17 +341,16 @@ public async Task Config_with_optional_properties_can_be_skipped() ConfigurationType: new ObjectType( "mockNs", TypeSymbolValidationFlags.Default, - new[] - { + [ new TypeProperty("optionalConfig", LanguageConstants.String, TypePropertyFlags.DeployTimeConstant), - }, + ], null), ArmTemplateProviderName: "Unused", ArmTemplateProviderVersion: "1.0.0"), - ImmutableArray.Empty, - ImmutableArray.Empty, - ImmutableArray.Empty, - ImmutableArray.Empty, + [], + [], + [], + [], new EmptyResourceTypeProvider()); var nsProvider = TestExtensibilityNamespaceProvider.Create((providerName, aliasName) => providerName switch diff --git a/src/Bicep.Core.IntegrationTests/RegistryProviderTests.cs b/src/Bicep.Core.IntegrationTests/RegistryProviderTests.cs index b04d7bb06fd..57921c575f5 100644 --- a/src/Bicep.Core.IntegrationTests/RegistryProviderTests.cs +++ b/src/Bicep.Core.IntegrationTests/RegistryProviderTests.cs @@ -121,10 +121,10 @@ public async Task Existing_resources_are_permitted_through_3p_type_registry() } """); - result.ExcludingLinterDiagnostics().Should().HaveDiagnostics(new[] - { + result.ExcludingLinterDiagnostics().Should().HaveDiagnostics( + [ ("BCP035", DiagnosticLevel.Warning, """The specified "resource" declaration is missing the following required properties: "identifier". If this is an inaccuracy in the documentation, please report it to the Bicep Team."""), - }); + ]); result = await CompilationHelper.RestoreAndCompile(services, """ provider 'br:example.azurecr.io/providers/foo:1.2.3' @@ -165,9 +165,9 @@ public async Task Third_party_namespace_errors_with_configuration() """); result.Should().NotGenerateATemplate(); - result.ExcludingLinterDiagnostics().Should().HaveDiagnostics(new[] { + result.ExcludingLinterDiagnostics().Should().HaveDiagnostics([ ("BCP205", DiagnosticLevel.Error, "Provider namespace \"http\" does not support configuration.") - }); + ]); } [TestMethod] @@ -344,9 +344,9 @@ public async Task Missing_required_provider_configuration_blocks_compilation() """); result.Should().NotGenerateATemplate(); - result.Should().HaveDiagnostics(new[]{ + result.Should().HaveDiagnostics([ ("BCP206", DiagnosticLevel.Error, "Provider namespace \"ThirdPartyProvider\" requires configuration, but none was provided.") - }); + ]); } [TestMethod] @@ -403,9 +403,9 @@ public async Task Missing_configuration_property_throws_errors() """); result.Should().NotGenerateATemplate(); - result.Should().HaveDiagnostics(new[]{ + result.Should().HaveDiagnostics([ ("BCP035", DiagnosticLevel.Error, "The specified \"object\" declaration is missing the following required properties: \"namespace\".") - }); + ]); } [TestMethod] @@ -430,10 +430,10 @@ public async Task Mispelled_required_configuration_property_throws_error() """); result.Should().NotGenerateATemplate(); - result.Should().HaveDiagnostics(new[]{ + result.Should().HaveDiagnostics([ ("BCP035", DiagnosticLevel.Error, "The specified \"object\" declaration is missing the following required properties: \"namespace\"."), ("BCP089", DiagnosticLevel.Error, "The property \"namespac\" is not allowed on objects of type \"config\". Did you mean \"namespace\"?") - }); + ]); } [TestMethod] @@ -458,9 +458,9 @@ public async Task Mispelled_optional_configuration_property_throws_error() """); result.Should().NotGenerateATemplate(); - result.Should().HaveDiagnostics(new[]{ + result.Should().HaveDiagnostics([ ("BCP089", DiagnosticLevel.Error, "The property \"contex\" is not allowed on objects of type \"config\". Did you mean \"context\"?") - }); + ]); } [TestMethod] @@ -483,9 +483,9 @@ public async Task Warning_generated_and_fallback_type_type_accepted() result.Template.Should().HaveValueAtPath("$.resources['test']['properties']['bodyProp']", "fallback body"); - result.Should().HaveDiagnostics(new[]{ + result.Should().HaveDiagnostics([ ("BCP081", DiagnosticLevel.Warning, "Resource type \"test@v1\" 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] @@ -503,9 +503,9 @@ public async Task Fallback_not_provided_in_json() """); result.Should().NotGenerateATemplate(); - result.Should().HaveDiagnostics(new[]{ + result.Should().HaveDiagnostics([ ("BCP029", DiagnosticLevel.Error, "The resource type is not valid. Specify a valid resource type of format \"@\"."), - }); + ]); } [TestMethod] @@ -531,9 +531,9 @@ provider foo """); result.Should().NotGenerateATemplate(); - result.ExcludingLinterDiagnostics().Should().HaveDiagnostics(new[] { + result.ExcludingLinterDiagnostics().Should().HaveDiagnostics([ ("BCP192", DiagnosticLevel.Error, """Unable to restore the artifact with reference "br:example.azurecr.io/providers/foo:1.2.4": The artifact does not exist in the registry.""") - }); + ]); // correct provider version fileSystem.File.WriteAllText("/bicepconfig.json", """ diff --git a/src/Bicep.Core.IntegrationTests/SafeDereferenceTests.cs b/src/Bicep.Core.IntegrationTests/SafeDereferenceTests.cs index 4bbe818d6cf..d98bca74a19 100644 --- a/src/Bicep.Core.IntegrationTests/SafeDereferenceTests.cs +++ b/src/Bicep.Core.IntegrationTests/SafeDereferenceTests.cs @@ -30,10 +30,10 @@ public void Safe_dereference_is_not_permitted_on_instance_functions() output secret string = storageaccount.?listKeys().keys[0].value "); - result.ExcludingLinterDiagnostics().Should().HaveDiagnostics(new[] - { + result.ExcludingLinterDiagnostics().Should().HaveDiagnostics( + [ ("BCP322", DiagnosticLevel.Error, "The `.?` (safe dereference) operator may not be used on instance function invocations.") - }); + ]); } [TestMethod] @@ -49,10 +49,10 @@ public void Safe_dereference_is_not_permitted_on_resource_collections() } "); - result.Should().HaveDiagnostics(new[] - { + result.Should().HaveDiagnostics( + [ ("BCP323", DiagnosticLevel.Error, "The `[?]` (safe dereference) operator may not be used on resource or module collections.") - }); + ]); } [TestMethod] @@ -74,10 +74,10 @@ public void Safe_dereference_is_not_permitted_on_module_collections() } ")); - result.Should().HaveDiagnostics(new[] - { + result.Should().HaveDiagnostics( + [ ("BCP323", DiagnosticLevel.Error, "The `[?]` (safe dereference) operator may not be used on resource or module collections.") - }); + ]); } [TestMethod] @@ -239,12 +239,12 @@ param foo (null output nestedAlt object = foo[?0].nested output deeplyNested string = foo[0].?nested.deeplyNested "); - result.Should().HaveDiagnostics(new[] { + result.Should().HaveDiagnostics([ ("BCP321", DiagnosticLevel.Warning, "Expected a value of type \"object\" but the provided value is of type \"null | { nested: { deeplyNested: 'value' } }\"."), ("BCP321", DiagnosticLevel.Warning, "Expected a value of type \"object\" but the provided value is of type \"null | { deeplyNested: 'value' }\"."), ("BCP321", DiagnosticLevel.Warning, "Expected a value of type \"object\" but the provided value is of type \"null | { deeplyNested: 'value' }\"."), ("BCP321", DiagnosticLevel.Warning, "Expected a value of type \"string\" but the provided value is of type \"'value' | null\"."), - }); + ]); } [TestMethod] @@ -261,9 +261,9 @@ public void Safe_dereference_of_unknown_property_should_be_warning_not_error() arrayAccess: foo[?baz] } "); - result.Should().HaveDiagnostics(new[] { + result.Should().HaveDiagnostics([ ("BCP083", DiagnosticLevel.Warning, @"The type ""object"" does not contain property ""baz"". Did you mean ""bar""?"), ("BCP083", DiagnosticLevel.Warning, @"The type ""object"" does not contain property ""baz"". Did you mean ""bar""?"), - }); + ]); } } diff --git a/src/Bicep.Core.IntegrationTests/ScenarioTests.cs b/src/Bicep.Core.IntegrationTests/ScenarioTests.cs index f7afa1011b3..fff194fa69e 100644 --- a/src/Bicep.Core.IntegrationTests/ScenarioTests.cs +++ b/src/Bicep.Core.IntegrationTests/ScenarioTests.cs @@ -76,13 +76,13 @@ param l "); result.Template.Should().NotHaveValue(); - result.ExcludingLinterDiagnostics().Should().HaveDiagnostics(new[] - { + result.ExcludingLinterDiagnostics().Should().HaveDiagnostics( + [ ("BCP028", DiagnosticLevel.Error, "Identifier \"l\" is declared multiple times. Remove or rename the duplicates."), ("BCP079", DiagnosticLevel.Error, "This expression is referencing its own declaration, which is not allowed."), ("BCP028", DiagnosticLevel.Error, "Identifier \"l\" is declared multiple times. Remove or rename the duplicates."), ("BCP279", DiagnosticLevel.Error, "Expected a type at this location. Please specify a valid type expression or one of the following types: \"array\", \"bool\", \"int\", \"object\", \"string\"."), - }); + ]); } [TestMethod] @@ -571,10 +571,10 @@ param location string ")); result.Template.Should().NotHaveValue(); - result.ExcludingLinterDiagnostics().Should().HaveDiagnostics(new[] - { + result.ExcludingLinterDiagnostics().Should().HaveDiagnostics( + [ ("BCP120", DiagnosticLevel.Error, "This expression is being used in an assignment to the \"scope\" property of the \"module\" type, which requires a value that can be calculated at the start of the deployment. You are referencing a variable which cannot be calculated at the start (\"appResGrp\" -> \"rg\"). Properties of rg which can be calculated at the start include \"name\"."), - }); + ]); } [TestMethod] @@ -705,12 +705,12 @@ param groupReaderId string "); result.Template.Should().NotHaveValue(); - result.ExcludingLinterDiagnostics().Should().HaveDiagnostics(new[] - { + result.ExcludingLinterDiagnostics().Should().HaveDiagnostics( + [ ("BCP139", DiagnosticLevel.Error, "A resource's scope must match the scope of the Bicep file for it to be deployable. You must use modules to deploy resources to a different scope."), ("BCP139", DiagnosticLevel.Error, "A resource's scope must match the scope of the Bicep file for it to be deployable. You must use modules to deploy resources to a different scope."), ("BCP139", DiagnosticLevel.Error, "A resource's scope must match the scope of the Bicep file for it to be deployable. You must use modules to deploy resources to a different scope."), - }); + ]); } [TestMethod] @@ -722,10 +722,10 @@ public void Test_Issue1364() "); result.Template.Should().NotHaveValue(); - result.ExcludingLinterDiagnostics().Should().HaveDiagnostics(new[] - { + result.ExcludingLinterDiagnostics().Should().HaveDiagnostics( + [ ("BCP033", DiagnosticLevel.Error, "Expected a value of type \"'managementGroup' | 'resourceGroup' | 'subscription' | 'tenant'\" but the provided value is of type \"'blablah'\"."), - }); + ]); } [TestMethod] @@ -755,11 +755,11 @@ public void Test_Issue569_duplicates() "); result.Template.Should().NotHaveValue(); - result.ExcludingLinterDiagnostics().Should().HaveDiagnostics(new[] - { + result.ExcludingLinterDiagnostics().Should().HaveDiagnostics( + [ ("BCP145", DiagnosticLevel.Error, "Output \"duplicate\" is declared multiple times. Remove or rename the duplicates."), ("BCP145", DiagnosticLevel.Error, "Output \"duplicate\" is declared multiple times. Remove or rename the duplicates."), - }); + ]); } [TestMethod] @@ -772,10 +772,10 @@ public void Test_Issue569_outputs_cannot_be_referenced() "); result.Template.Should().NotHaveValue(); - result.ExcludingLinterDiagnostics().Should().HaveDiagnostics(new[] - { + result.ExcludingLinterDiagnostics().Should().HaveDiagnostics( + [ ("BCP057", DiagnosticLevel.Error, "The name \"output1\" does not exist in the current context."), - }); + ]); } [TestMethod] @@ -788,10 +788,10 @@ public void Test_Issue1599() "); result.Template.Should().NotHaveValue(); - result.ExcludingLinterDiagnostics().Should().HaveDiagnostics(new[] - { + result.ExcludingLinterDiagnostics().Should().HaveDiagnostics( + [ ("BCP279", DiagnosticLevel.Error, "Expected a type at this location. Please specify a valid type expression or one of the following types: \"array\", \"bool\", \"int\", \"object\", \"string\"."), - }); + ]); } [TestMethod] @@ -937,11 +937,11 @@ public void Test_Issue1432() "); result.Template.Should().NotHaveValue(); - result.ExcludingLinterDiagnostics().Should().HaveDiagnostics(new[] - { + result.ExcludingLinterDiagnostics().Should().HaveDiagnostics( + [ ("BCP025", DiagnosticLevel.Error, "The property \"name\" is declared multiple times in this object. Remove or rename the duplicate properties."), ("BCP025", DiagnosticLevel.Error, "The property \"name\" is declared multiple times in this object. Remove or rename the duplicate properties."), - }); + ]); } [TestMethod] @@ -955,11 +955,11 @@ public void Test_Issue1817() "); result.Template.Should().NotHaveValue(); - result.ExcludingLinterDiagnostics().Should().HaveDiagnostics(new[] - { + result.ExcludingLinterDiagnostics().Should().HaveDiagnostics( + [ ("BCP032", DiagnosticLevel.Error, "The value must be a compile-time constant."), ("BCP057", DiagnosticLevel.Error, "The name \"w\" does not exist in the current context."), - }); + ]); } [TestMethod] @@ -1013,10 +1013,10 @@ param foo int output bar int = 42 ")); - result.ExcludingLinterDiagnostics().Should().HaveDiagnostics(new[] - { + result.ExcludingLinterDiagnostics().Should().HaveDiagnostics( + [ ("BCP104", DiagnosticLevel.Error, "The referenced module has errors."), - }); + ]); } [TestMethod] @@ -1040,10 +1040,10 @@ param location string // verify the template still compiles result.Template.Should().NotBeNull(); - result.ExcludingLinterDiagnostics().Should().HaveDiagnostics(new[] - { + result.ExcludingLinterDiagnostics().Should().HaveDiagnostics( + [ ("BCP174", DiagnosticLevel.Warning, "Type validation is not available for resource types declared containing a \"/providers/\" segment. Please instead use the \"scope\" property."), - }); + ]); result = CompilationHelper.Compile(@" resource resA 'Rp.A/providers@2020-06-01' = { @@ -1058,12 +1058,12 @@ param location string "); result.Template.Should().NotBeNull(); - result.ExcludingLinterDiagnostics().Should().HaveDiagnostics(new[] - { + result.ExcludingLinterDiagnostics().Should().HaveDiagnostics( + [ ("BCP081", DiagnosticLevel.Warning, "Resource type \"Rp.A/providers@2020-06-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."), ("BCP081", DiagnosticLevel.Warning, "Resource type \"Rp.A/providers/a/b@2020-06-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."), ("BCP081", DiagnosticLevel.Warning, "Resource type \"Rp.A/a/b/providers@2020-06-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."), - }); + ]); result = CompilationHelper.Compile(@" param eventGridTopicName string @@ -1111,15 +1111,15 @@ public void Test_Issue1985() "); result.Should().NotGenerateATemplate(); - result.ExcludingLinterDiagnostics().Should().HaveDiagnostics(new[] - { + result.ExcludingLinterDiagnostics().Should().HaveDiagnostics( + [ ("BCP029", DiagnosticLevel.Error, "The resource type is not valid. Specify a valid resource type of format \"@\"."), ("BCP062", DiagnosticLevel.Error, "The referenced declaration with name \"aksDefaultPoolSubnet\" is not valid."), ("BCP062", DiagnosticLevel.Error, "The referenced declaration with name \"aksDefaultPoolSubnet\" is not valid."), ("BCP057", DiagnosticLevel.Error, "The name \"aksServicePrincipalObjectId\" does not exist in the current context."), ("BCP057", DiagnosticLevel.Error, "The name \"virtualNetwork\" does not exist in the current context."), ("BCP057", DiagnosticLevel.Error, "The name \"userAssignedIdentities\" does not exist in the current context."), - }); + ]); } [TestMethod] @@ -1491,10 +1491,10 @@ public void Test_Issue691() "); - result.ExcludingLinterDiagnostics().Should().HaveDiagnostics(new[] - { + result.ExcludingLinterDiagnostics().Should().HaveDiagnostics( + [ ("BCP037", DiagnosticLevel.Warning, "The property \"valThatDoesNotExist\" from source declaration \"vmNotWorkingProps\" is not allowed on objects of type \"VirtualMachineProperties\". Permissible properties include \"additionalCapabilities\", \"availabilitySet\", \"billingProfile\", \"diagnosticsProfile\", \"evictionPolicy\", \"extensionsTimeBudget\", \"hardwareProfile\", \"host\", \"hostGroup\", \"licenseType\", \"networkProfile\", \"osProfile\", \"priority\", \"proximityPlacementGroup\", \"securityProfile\", \"storageProfile\", \"virtualMachineScaleSet\". If this is an inaccuracy in the documentation, please report it to the Bicep Team."), - }); + ]); } [TestMethod] @@ -1560,10 +1560,10 @@ public void Test_Issue1988() } "); - result.ExcludingLinterDiagnostics().Should().HaveDiagnostics(new[] - { + result.ExcludingLinterDiagnostics().Should().HaveDiagnostics( + [ ("BCP120", DiagnosticLevel.Error, "This expression is being used in an assignment to the \"location\" property of the \"Microsoft.Network/networkInterfaces\" type, which requires a value that can be calculated at the start of the deployment. Properties of vnet which can be calculated at the start include \"apiVersion\", \"id\", \"name\", \"type\"."), - }); + ]); } [TestMethod] @@ -1625,13 +1625,13 @@ public void Test_Issue2289() }] } "); - result.ExcludingLinterDiagnostics().Should().HaveDiagnostics(new[] - { + result.ExcludingLinterDiagnostics().Should().HaveDiagnostics( + [ ("BCP179", DiagnosticLevel.Warning, "Unique resource or deployment name is required when looping. The loop item variable \"thing\" must be referenced in at least one of the value expressions of the following properties: \"name\", \"parent\""), ("BCP170", DiagnosticLevel.Error, "Expected resource name to not contain any \"/\" characters. Child resources with a parent resource reference (via the parent property or via nesting) must not contain a fully-qualified name."), ("BCP179", DiagnosticLevel.Warning, "Unique resource or deployment name is required when looping. The loop item variable \"thing2\" must be referenced in at least one of the value expressions of the following properties: \"name\""), ("BCP170", DiagnosticLevel.Error, "Expected resource name to not contain any \"/\" characters. Child resources with a parent resource reference (via the parent property or via nesting) must not contain a fully-qualified name."), - }); + ]); result.Template.Should().BeNull(); } @@ -1712,14 +1712,14 @@ public void Test_Issue1809() } ")); - result.ExcludingLinterDiagnostics().Should().HaveDiagnostics(new[] - { + result.ExcludingLinterDiagnostics().Should().HaveDiagnostics( + [ ("BCP120", DiagnosticLevel.Error, "This expression is being used in an assignment to the \"tags\" property of the \"Microsoft.Network/virtualWans\" type, which requires a value that can be calculated at the start of the deployment. Properties of tags which can be calculated at the start include \"name\"."), ("BCP120", DiagnosticLevel.Error, "This expression is being used in an assignment to the \"tags\" property of the \"Microsoft.Network/virtualWans\" type, which requires a value that can be calculated at the start of the deployment. Properties of tags which can be calculated at the start include \"name\"."), ("BCP120", DiagnosticLevel.Error, "This expression is being used in an assignment to the \"tags\" property of the \"Microsoft.Network/networkSecurityGroups\" type, which requires a value that can be calculated at the start of the deployment. Properties of tags which can be calculated at the start include \"name\"."), ("BCP120", DiagnosticLevel.Error, "This expression is being used in an assignment to the \"tags\" property of the \"Microsoft.Network/networkSecurityGroups\" type, which requires a value that can be calculated at the start of the deployment. Properties of tags which can be calculated at the start include \"name\"."), ("BCP120", DiagnosticLevel.Error, "This expression is being used in an assignment to the \"zones\" property of the \"Microsoft.Network/publicIPAddresses\" type, which requires a value that can be calculated at the start of the deployment. Properties of vwan which can be calculated at the start include \"apiVersion\", \"id\", \"name\", \"type\"."), - }); + ]); } [TestMethod] @@ -1742,10 +1742,10 @@ public void Test_Issue2391() }] "); - result.ExcludingLinterDiagnostics().Should().HaveDiagnostics(new[] - { + result.ExcludingLinterDiagnostics().Should().HaveDiagnostics( + [ ("BCP144", DiagnosticLevel.Error, "Directly referencing a resource or module collection is not currently supported here. Apply an array indexer to the expression.") - }); + ]); } [TestMethod] @@ -1763,10 +1763,10 @@ public void Test_Issue2090() }] "); - result.ExcludingLinterDiagnostics().Should().HaveDiagnostics(new[] - { + result.ExcludingLinterDiagnostics().Should().HaveDiagnostics( + [ ("BCP178", DiagnosticLevel.Error, "This expression is being used in the for-expression, which requires a value that can be calculated at the start of the deployment. Properties of vnet which can be calculated at the start include \"apiVersion\", \"id\", \"name\", \"type\".") - }); + ]); } [TestMethod] @@ -1799,12 +1799,12 @@ public void Test_Issue1699() } "); - result.ExcludingLinterDiagnostics().Should().HaveDiagnostics(new[] - { + result.ExcludingLinterDiagnostics().Should().HaveDiagnostics( + [ ("BCP179", DiagnosticLevel.Warning, "Unique resource or deployment name is required when looping. The loop item variable \"item\" must be referenced in at least one of the value expressions of the following properties: \"name\""), ("BCP178", DiagnosticLevel.Error, "This expression is being used in the for-expression, which requires a value that can be calculated at the start of the deployment. You are referencing a variable which cannot be calculated at the start (\"test\" -> \"rg\"). Properties of rg which can be calculated at the start include \"apiVersion\", \"id\", \"name\", \"type\"."), ("BCP177", DiagnosticLevel.Error, "This expression is being used in the if-condition expression, which requires a value that can be calculated at the start of the deployment. Properties of rg2 which can be calculated at the start include \"apiVersion\", \"id\", \"name\", \"type\".") - }); + ]); } [TestMethod] @@ -1819,10 +1819,10 @@ public void Test_Issue2484() param foo string = 'peach' "); - result.ExcludingLinterDiagnostics().Should().HaveDiagnostics(new[] - { + result.ExcludingLinterDiagnostics().Should().HaveDiagnostics( + [ ("BCP033", DiagnosticLevel.Error, "Expected a value of type \"'apple' | 'banana'\" but the provided value is of type \"'peach'\"."), - }); + ]); } [TestMethod] @@ -1862,13 +1862,13 @@ public void Test_Issue2547() } ")); - result.ExcludingLinterDiagnostics().Should().HaveDiagnostics(new[] - { + result.ExcludingLinterDiagnostics().Should().HaveDiagnostics( + [ ("BCP181", DiagnosticLevel.Error, "This expression is being used in an argument of the function \"listSecrets\", which requires a value that can be calculated at the start of the deployment. Properties of stgModule which can be calculated at the start include \"name\"."), ("BCP181", DiagnosticLevel.Error, "This expression is being used in an argument of the function \"listSecrets\", which requires a value that can be calculated at the start of the deployment. Properties of stgModule which can be calculated at the start include \"name\"."), ("BCP181", DiagnosticLevel.Error, "This expression is being used in an argument of the function \"listKeys\", which requires a value that can be calculated at the start of the deployment. Properties of stgModule which can be calculated at the start include \"name\"."), ("BCP181", DiagnosticLevel.Error, "This expression is being used in an argument of the function \"listKeys\", which requires a value that can be calculated at the start of the deployment. Properties of stgModule which can be calculated at the start include \"name\"."), - }); + ]); } [TestMethod] @@ -1889,12 +1889,12 @@ public void Test_Issue2494() } "); - result.ExcludingLinterDiagnostics().Should().HaveDiagnostics(new[] - { + result.ExcludingLinterDiagnostics().Should().HaveDiagnostics( + [ ("BCP080", DiagnosticLevel.Error, "The expression is involved in a cycle (\"nameCopy\" -> \"name\")."), ("BCP080", DiagnosticLevel.Error, "The expression is involved in a cycle (\"name\" -> \"nameCopy\")."), ("BCP062", DiagnosticLevel.Error, "The referenced declaration with name \"name\" is not valid.") - }); + ]); } [TestMethod] @@ -1951,14 +1951,14 @@ param zonesEnabled bool parent: null } "); - result.ExcludingLinterDiagnostics().Should().HaveDiagnostics(new[] - { + result.ExcludingLinterDiagnostics().Should().HaveDiagnostics( + [ ("BCP036", DiagnosticLevel.Error, "The property \"name\" expected a value of type \"string\" but the provided value is of type \"null\"."), ("BCP036", DiagnosticLevel.Error, "The property \"scope\" expected a value of type \"resource | tenant\" but the provided value is of type \"null\"."), ("BCP036", DiagnosticLevel.Error, "The property \"name\" expected a value of type \"string\" but the provided value is of type \"null\"."), ("BCP036", DiagnosticLevel.Error, "The property \"parent\" expected a value of type \"Microsoft.Network/dnsZones\" but the provided value is of type \"null\"."), ("BCP240", DiagnosticLevel.Error, "The \"parent\" property only permits direct references to resources. Expressions are not supported."), - }); + ]); } [TestMethod] @@ -1989,10 +1989,10 @@ public void Test_Issue2248_UnionTypeInArrayAccessBaseExpression_NegativeCase() var foos = true ? true : [] var primaryFoo = foos[0] "); - result.ExcludingLinterDiagnostics().Should().HaveDiagnostics(new[] - { + result.ExcludingLinterDiagnostics().Should().HaveDiagnostics( + [ ("BCP076", DiagnosticLevel.Error, "Cannot index over expression of type \" | true\". Arrays or objects are required.") - }); + ]); } [TestMethod] @@ -2063,10 +2063,10 @@ public void Test_Issue2622() } } "); - result.ExcludingLinterDiagnostics().Should().HaveDiagnostics(new[] - { + result.ExcludingLinterDiagnostics().Should().HaveDiagnostics( + [ ("BCP120", DiagnosticLevel.Error, "This expression is being used in an assignment to the \"name\" property of the \"Microsoft.Network/publicIPAddresses\" type, which requires a value that can be calculated at the start of the deployment.") - }); + ]); } [TestMethod] @@ -2098,10 +2098,10 @@ public void Test_Issue2291() } }] "); - result.ExcludingLinterDiagnostics().Should().HaveDiagnostics(new[] - { + result.ExcludingLinterDiagnostics().Should().HaveDiagnostics( + [ ("BCP177", DiagnosticLevel.Error, "This expression is being used in the if-condition expression, which requires a value that can be calculated at the start of the deployment. Properties of importPipeline which can be calculated at the start include \"apiVersion\", \"id\", \"name\", \"type\".") - }); + ]); } [TestMethod] @@ -2122,10 +2122,10 @@ param hello string params: v } ")); - result.ExcludingLinterDiagnostics().Should().HaveDiagnostics(new[] - { + result.ExcludingLinterDiagnostics().Should().HaveDiagnostics( + [ ("BCP183", DiagnosticLevel.Error, "The value of the module \"params\" property must be an object literal.") - }); + ]); } [TestMethod] @@ -2148,12 +2148,12 @@ param hello string output v object = v ")); - result.ExcludingLinterDiagnostics().Should().HaveDiagnostics(new[] - { + result.ExcludingLinterDiagnostics().Should().HaveDiagnostics( + [ ("BCP009", DiagnosticLevel.Error, "Expected a literal value, an array, an object, a parenthesized expression, or a function call at this location.") - }); + ]); - result.ExcludingLinterDiagnostics().Should().NotHaveDiagnosticsWithCodes(new[] { "BCP183" }); + result.ExcludingLinterDiagnostics().Should().NotHaveDiagnosticsWithCodes(["BCP183"]); } [TestMethod] @@ -2170,10 +2170,10 @@ param vnetResourceGroupName string scope: resourceGroup(vnetResourceGroupName) } "); - result.ExcludingLinterDiagnostics().Should().HaveDiagnostics(new[] - { + result.ExcludingLinterDiagnostics().Should().HaveDiagnostics( + [ ("BCP169", DiagnosticLevel.Error, "Expected resource name to contain 1 \"/\" character(s). The number of name segments must match the number of segments in the resource type."), - }); + ]); } [TestMethod] @@ -2240,10 +2240,10 @@ param tags object } "); - result.ExcludingLinterDiagnostics().Should().HaveDiagnostics(new[] - { + result.ExcludingLinterDiagnostics().Should().HaveDiagnostics( + [ ("BCP138", DiagnosticLevel.Error, "For-expressions are not supported in this context. For-expressions may be used as values of resource, module, variable, and output declarations, or values of resource and module properties.") - }); + ]); } /// @@ -2425,14 +2425,14 @@ public void Test_Issue4212() "), ("mod.bicep", "")); - result.Should().HaveDiagnostics(new[] - { + result.Should().HaveDiagnostics( + [ ("BCP036", DiagnosticLevel.Error, "The property \"parent\" expected a value of type \"Microsoft.Network/virtualNetworks\" but the provided value is of type \"module\"."), ("BCP240", DiagnosticLevel.Error, "The \"parent\" property only permits direct references to resources. Expressions are not supported."), ("no-unused-existing-resources", DiagnosticLevel.Warning, "Existing resource \"res2\" is declared but never used."), ("BCP036", DiagnosticLevel.Error, "The property \"parent\" expected a value of type \"Microsoft.Network/virtualNetworks\" but the provided value is of type \"tenant\"."), ("BCP240", DiagnosticLevel.Error, "The \"parent\" property only permits direct references to resources. Expressions are not supported."), - }); + ]); } // https://github.com/Azure/bicep/issues/4542 @@ -2527,13 +2527,13 @@ public void Test_Issue4542() "); result.Template.Should().NotHaveValue(); - result.ExcludingLinterDiagnostics().Should().HaveDiagnostics(new[] - { + result.ExcludingLinterDiagnostics().Should().HaveDiagnostics( + [ ("BCP080", DiagnosticLevel.Error, "The expression is involved in a cycle (\"secret\" -> \"ap\" -> \"importPipeline\")."), ("BCP080", DiagnosticLevel.Error, "The expression is involved in a cycle (\"importPipeline\" -> \"secret\" -> \"ap\")."), ("BCP080", DiagnosticLevel.Error, "The expression is involved in a cycle (\"importPipeline\" -> \"secret\" -> \"ap\")."), ("BCP080", DiagnosticLevel.Error, "The expression is involved in a cycle (\"ap\" -> \"importPipeline\" -> \"secret\")."), - }); + ]); } /// @@ -2659,13 +2659,13 @@ param paramString string output out4 string = 'hello' + 'world' "); - result.Should().HaveDiagnostics(new[] - { + result.Should().HaveDiagnostics( + [ ("BCP045", DiagnosticLevel.Error, "Cannot apply operator \"+\" to operands of type \"string\" and \"string\". Use string interpolation instead."), ("BCP045", DiagnosticLevel.Error, "Cannot apply operator \"+\" to operands of type \"string\" and \"'world'\". Use string interpolation instead."), ("BCP045", DiagnosticLevel.Error, "Cannot apply operator \"+\" to operands of type \"string\" and \"string\". Use string interpolation instead."), ("BCP045", DiagnosticLevel.Error, "Cannot apply operator \"+\" to operands of type \"'hello'\" and \"'world'\". Use string interpolation instead.") - }); + ]); } // https://github.com/Azure/bicep/issues/3749 @@ -2782,10 +2782,10 @@ public void Test_Issue5371_negative_tests(string fileContents) { var result = CompilationHelper.Compile(fileContents); - result.ExcludingLinterDiagnostics().Should().HaveDiagnostics(new[] - { + result.ExcludingLinterDiagnostics().Should().HaveDiagnostics( + [ ("BCP010", DiagnosticLevel.Error, "Expected a valid 64-bit signed integer.") - }); + ]); } /// @@ -2795,18 +2795,18 @@ public void Test_Issue5371_negative_tests(string fileContents) public void Test_Issue5456_1() { var typeReference = ResourceTypeReference.Parse("My.Rp/myResource@2020-01-01"); - var typeLoader = TestTypeHelper.CreateResourceTypeLoaderWithTypes(new[] - { - new ResourceTypeComponents(typeReference, ResourceScope.ResourceGroup, ResourceScope.None, ResourceFlags.None, new ObjectType(typeReference.FormatName(), TypeSymbolValidationFlags.Default, new[] - { + var typeLoader = TestTypeHelper.CreateResourceTypeLoaderWithTypes( + [ + new ResourceTypeComponents(typeReference, ResourceScope.ResourceGroup, ResourceScope.None, ResourceFlags.None, new ObjectType(typeReference.FormatName(), TypeSymbolValidationFlags.Default, + [ new TypeProperty("name", LanguageConstants.String, TypePropertyFlags.DeployTimeConstant, "name property"), new TypeProperty("tags", LanguageConstants.Array, TypePropertyFlags.ReadOnly, "tags property"), - new TypeProperty("properties", new ObjectType("properties", TypeSymbolValidationFlags.Default, new[] - { + new TypeProperty("properties", new ObjectType("properties", TypeSymbolValidationFlags.Default, + [ new TypeProperty("prop1", LanguageConstants.String, TypePropertyFlags.ReadOnly, "prop1") - }, null), TypePropertyFlags.ReadOnly, "properties property"), - }, null)) - }); + ], null), TypePropertyFlags.ReadOnly, "properties property"), + ], null)) + ]); // explicitly pass a valid scope var result = CompilationHelper.Compile(typeLoader, ("main.bicep", @" @@ -2820,11 +2820,11 @@ public void Test_Issue5456_1() } } ")); - result.Should().GenerateATemplate().And.HaveDiagnostics(new[] - { + result.Should().GenerateATemplate().And.HaveDiagnostics( + [ ("BCP073", DiagnosticLevel.Warning, "The property \"tags\" is read-only. Expressions cannot be assigned to read-only properties. If this is an inaccuracy in the documentation, please report it to the Bicep Team."), ("BCP073", DiagnosticLevel.Warning, "The property \"properties\" is read-only. Expressions cannot be assigned to read-only properties. If this is an inaccuracy in the documentation, please report it to the Bicep Team.") - }); + ]); } /// @@ -2841,10 +2841,10 @@ public void Test_Issue5456_2() outputs: {} } ")); - result.Should().NotGenerateATemplate().And.HaveDiagnostics(new[] - { + result.Should().NotGenerateATemplate().And.HaveDiagnostics( + [ ("BCP073", DiagnosticLevel.Error, "The property \"outputs\" is read-only. Expressions cannot be assigned to read-only properties.") - }); + ]); } /// @@ -2968,10 +2968,10 @@ public void Test_Issue_5530() resource resourceGroup 'Microsoft.Resources/resourceGroups@2021-04-01' "); - result.ExcludingLinterDiagnostics().Should().HaveDiagnostics(new[] - { + result.ExcludingLinterDiagnostics().Should().HaveDiagnostics( + [ ("BCP018", DiagnosticLevel.Error, "Expected the \"=\" character at this location.") - }); + ]); } /// @@ -2990,10 +2990,10 @@ public void Test_Issue_5530_2() resource managementGroup 'Microsoft.Management/managementGroups@2021-04-01' "); - result.ExcludingLinterDiagnostics().Should().HaveDiagnostics(new[] - { + result.ExcludingLinterDiagnostics().Should().HaveDiagnostics( + [ ("BCP018", DiagnosticLevel.Error, "Expected the \"=\" character at this location.") - }); + ]); } /// @@ -3071,10 +3071,10 @@ public void Test_Issue_3169_2() } } "); - result.ExcludingLinterDiagnostics().Should().HaveDiagnostics(new[] - { + result.ExcludingLinterDiagnostics().Should().HaveDiagnostics( + [ ("BCP120", DiagnosticLevel.Error, "This expression is being used in an assignment to the \"name\" property of the \"Microsoft.Storage/storageAccounts\" type, which requires a value that can be calculated at the start of the deployment. Properties of existingStg which can be calculated at the start include \"apiVersion\", \"id\", \"type\".") - }); + ]); } /// @@ -3208,10 +3208,10 @@ public void Test_Issue6423() "); // verify we have diagnostics for 'properties' - result.ExcludingLinterDiagnostics().Should().HaveDiagnostics(new[] - { + result.ExcludingLinterDiagnostics().Should().HaveDiagnostics( + [ ("BCP037", DiagnosticLevel.Warning, "The property \"madeUpProperty\" is not allowed on objects of type \"SiteAuthSettingsV2Properties\". Permissible properties include \"globalValidation\", \"httpSettings\", \"identityProviders\", \"login\", \"platform\". If this is an inaccuracy in the documentation, please report it to the Bicep Team.") - }); + ]); result.Template.Should().HaveValueAtPath("$.resources[1].name", "[format('{0}/{1}', variables('configs')[copyIndex()].name, 'authsettingsV2')]"); result.Template.Should().HaveValueAtPath("$.resources[1].dependsOn", new JArray @@ -3303,8 +3303,8 @@ public void Test_Issue_3356_Warn_On_Bad_Type_Definitions() clientId: foo.identity.userAssignedIdentities['blah'].hello } "); - result.ExcludingLinterDiagnostics().Should().HaveDiagnostics(new[] - { + result.ExcludingLinterDiagnostics().Should().HaveDiagnostics( + [ ("BCP081", DiagnosticLevel.Warning, "Resource type \"Microsoft.Storage/storageAccounts@2021-09-00\" 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."), ("BCP036", DiagnosticLevel.Warning, "The property \"name\" expected a value of type \"string\" but the provided value is of type \"123\". If this is an inaccuracy in the documentation, please report it to the Bicep Team."), ("BCP036", DiagnosticLevel.Warning, "The property \"capacity\" expected a value of type \"int\" but the provided value is of type \"'1'\". If this is an inaccuracy in the documentation, please report it to the Bicep Team."), @@ -3314,7 +3314,7 @@ public void Test_Issue_3356_Warn_On_Bad_Type_Definitions() ("BCP036", DiagnosticLevel.Warning, "The property \"clientId\" expected a value of type \"string\" but the provided value is of type \"1\". If this is an inaccuracy in the documentation, please report it to the Bicep Team."), ("BCP036", DiagnosticLevel.Warning, "The property \"principalId\" expected a value of type \"string\" but the provided value is of type \"2\". If this is an inaccuracy in the documentation, please report it to the Bicep Team."), ("BCP053", DiagnosticLevel.Error, "The type \"userAssignedIdentityProperties\" does not contain property \"hello\". Available properties include \"clientId\", \"principalId\"."), - }); + ]); } // https://github.com/Azure/bicep/issues/9736 @@ -3382,10 +3382,10 @@ param userAssignedManagedIdentityName string } }] "); - result.ExcludingLinterDiagnostics().Should().HaveDiagnostics(new[] - { + result.ExcludingLinterDiagnostics().Should().HaveDiagnostics( + [ ("BCP179", DiagnosticLevel.Warning, "Unique resource or deployment name is required when looping. The loop item variable \"roleId\" must be referenced in at least one of the value expressions of the following properties: \"name\", \"scope\"") - }); + ]); } /// @@ -3425,10 +3425,10 @@ param userAssignedManagedIdentityName string } }] "); - result.ExcludingLinterDiagnostics().Should().HaveDiagnostics(new[] - { + result.ExcludingLinterDiagnostics().Should().HaveDiagnostics( + [ ("BCP179", DiagnosticLevel.Warning, "Unique resource or deployment name is required when looping. The loop item variable \"roleId\" or the index variable \"index\" must be referenced in at least one of the value expressions of the following properties in the loop body: \"name\", \"scope\"") - }); + ]); } /// @@ -3484,10 +3484,10 @@ public void Test_Issue_7241_2(string copy) using (new AssertionScope()) { - result.ExcludingLinterDiagnostics().Should().HaveDiagnostics(new[] - { + result.ExcludingLinterDiagnostics().Should().HaveDiagnostics( + [ ("BCP239", DiagnosticLevel.Error, "Identifier \"copy\" is a reserved Bicep symbol name and cannot be used in this context.") - }); + ]); result.Template.Should().BeNull(); } } @@ -3565,9 +3565,9 @@ public void Test_Issue_7154_Ternary_Syntax_Produces_Error() } } "); - result.ExcludingLinterDiagnostics().Should().HaveDiagnostics(new[] { + result.ExcludingLinterDiagnostics().Should().HaveDiagnostics([ ("BCP240", DiagnosticLevel.Error, "The \"parent\" property only permits direct references to resources. Expressions are not supported.") - }); + ]); } /// @@ -3643,9 +3643,9 @@ public void Test_Issue_7154_2_Ternary_Syntax_With_Parentheses_Produces_Error() } } "); - result.ExcludingLinterDiagnostics().Should().HaveDiagnostics(new[] { + result.ExcludingLinterDiagnostics().Should().HaveDiagnostics([ ("BCP240", DiagnosticLevel.Error, "The \"parent\" property only permits direct references to resources. Expressions are not supported.") - }); + ]); } /// @@ -3717,10 +3717,10 @@ public void Test_Issue2017() var providersTest2 = providers('Microsoft.Resources', 'deployments').locations ").ExcludingLinterDiagnostics(); - result.Should().HaveDiagnostics(new[] { + result.Should().HaveDiagnostics([ ("BCP241", DiagnosticLevel.Warning, "The \"providers\" function is deprecated and will be removed in a future release of Bicep. Please add a comment to https://github.com/Azure/bicep/issues/2017 if you believe this will impact your workflow."), ("BCP241", DiagnosticLevel.Warning, "The \"providers\" function is deprecated and will be removed in a future release of Bicep. Please add a comment to https://github.com/Azure/bicep/issues/2017 if you believe this will impact your workflow."), - }); + ]); result.Diagnostics.Should().OnlyContain(x => x.Styling == DiagnosticStyling.ShowCodeDeprecated); } @@ -4231,10 +4231,10 @@ public void Test_Issue6065() output sql resource = sql ")); - result.ExcludingLinterDiagnostics().Should().HaveDiagnostics(new[] - { + result.ExcludingLinterDiagnostics().Should().HaveDiagnostics( + [ ("BCP320", DiagnosticLevel.Error, "The properties of module output resources cannot be accessed directly. To use the properties of this resource, pass it as a resource-typed parameter to another module and access the parameter's properties therein."), - }); + ]); } [TestMethod] @@ -4256,10 +4256,10 @@ public void Test_Issue6065_ResourceFunctions() output sa resource = sa """)); - result.ExcludingLinterDiagnostics().Should().HaveDiagnostics(new[] - { + result.ExcludingLinterDiagnostics().Should().HaveDiagnostics( + [ ("BCP320", DiagnosticLevel.Error, "The properties of module output resources cannot be accessed directly. To use the properties of this resource, pass it as a resource-typed parameter to another module and access the parameter's properties therein."), - }); + ]); } [TestMethod] @@ -4494,11 +4494,11 @@ public void Test_Issue9978() } "); - result.Should().HaveDiagnostics(new[] - { + result.Should().HaveDiagnostics( + [ ("BCP079", DiagnosticLevel.Error, "This expression is referencing its own declaration, which is not allowed."), ("BCP062", DiagnosticLevel.Error, "The referenced declaration with name \"foo\" is not valid."), - }); + ]); } // https://github.com/Azure/bicep/issues/6010 @@ -4672,12 +4672,12 @@ public void Test_Issue10403() param foo = 'foo' ")); - result.Should().HaveDiagnostics(new[] - { + result.Should().HaveDiagnostics( + [ ("BCP261", DiagnosticLevel.Error, "A using declaration must be present in this parameters file."), ("BCP028", DiagnosticLevel.Error, "Identifier \"foo\" is declared multiple times. Remove or rename the duplicates."), ("BCP028", DiagnosticLevel.Error, "Identifier \"foo\" is declared multiple times. Remove or rename the duplicates."), - }); + ]); } // https://github.com/Azure/bicep/issues/9973 @@ -4786,10 +4786,10 @@ public void For_loop_scoped_variables_should_overwrite_globally_scoped_functions }] "); - result.ExcludingLinterDiagnostics().Should().HaveDiagnostics(new[] - { + result.ExcludingLinterDiagnostics().Should().HaveDiagnostics( + [ ("BCP265", DiagnosticLevel.Error, "The name \"resourceGroup\" is not a function. Did you mean \"az.resourceGroup\"?"), - }); + ]); } // https://github.com/Azure/bicep/issues/10657 @@ -4803,10 +4803,10 @@ public void Variable_declarations_should_overwrite_globally_scoped_functions() }] "); - result.ExcludingLinterDiagnostics().Should().HaveDiagnostics(new[] - { + result.ExcludingLinterDiagnostics().Should().HaveDiagnostics( + [ ("BCP265", DiagnosticLevel.Error, "The name \"resourceGroup\" is not a function. Did you mean \"az.resourceGroup\"?"), - }); + ]); } // https://github.com/Azure/bicep/issues/10657 @@ -4831,10 +4831,10 @@ public void Typed_lambda_variable_declarations_should_overwrite_globally_scoped_ func foo(resourceGroup string) string => resourceGroup('test') "); - result.ExcludingLinterDiagnostics().Should().HaveDiagnostics(new[] - { + result.ExcludingLinterDiagnostics().Should().HaveDiagnostics( + [ ("BCP265", DiagnosticLevel.Error, "The name \"resourceGroup\" is not a function. Did you mean \"az.resourceGroup\"?"), - }); + ]); } // https://github.com/Azure/bicep/issues/10884 @@ -4868,10 +4868,10 @@ public void Test_Issue10884() param resourceGroups resourceGroup[] ")); - result.ExcludingLinterDiagnostics().Should().HaveDiagnostics(new[] - { + result.ExcludingLinterDiagnostics().Should().HaveDiagnostics( + [ ("BCP035", DiagnosticLevel.Error, "The specified \"object\" declaration is missing the following required properties: \"bar\", \"foo\"."), - }); + ]); } // https://github.com/Azure/bicep/issues/10098 @@ -4914,11 +4914,11 @@ public void Test_Issue11437() """), ("main.bicep", """param foo string""")); - result.Should().HaveDiagnostics(new[] - { + result.Should().HaveDiagnostics( + [ ("BCP028", DiagnosticLevel.Error, """Identifier "foo" is declared multiple times. Remove or rename the duplicates."""), ("BCP028", DiagnosticLevel.Error, """Identifier "foo" is declared multiple times. Remove or rename the duplicates."""), - }); + ]); } // https://github.com/Azure/bicep/issues/8187 @@ -4968,44 +4968,44 @@ public void Test_Issue502() var FoO = 2 """); - result.ExcludingLinterDiagnostics().Should().HaveDiagnostics(new[] - { + result.ExcludingLinterDiagnostics().Should().HaveDiagnostics( + [ ("BCP353", DiagnosticLevel.Error, "The variables \"foo\", \"FoO\" differ only in casing. The ARM deployments engine is not case sensitive and will not be able to distinguish between them."), ("BCP353", DiagnosticLevel.Error, "The variables \"foo\", \"FoO\" differ only in casing. The ARM deployments engine is not case sensitive and will not be able to distinguish between them."), - }); + ]); result = CompilationHelper.Compile(""" param foo int = 1 param FoO int = 2 """); - result.ExcludingLinterDiagnostics().Should().HaveDiagnostics(new[] - { + result.ExcludingLinterDiagnostics().Should().HaveDiagnostics( + [ ("BCP353", DiagnosticLevel.Error, "The parameters \"foo\", \"FoO\" differ only in casing. The ARM deployments engine is not case sensitive and will not be able to distinguish between them."), ("BCP353", DiagnosticLevel.Error, "The parameters \"foo\", \"FoO\" differ only in casing. The ARM deployments engine is not case sensitive and will not be able to distinguish between them."), - }); + ]); result = CompilationHelper.Compile(""" output foo int = 1 output FoO int = 2 """); - result.ExcludingLinterDiagnostics().Should().HaveDiagnostics(new[] - { + result.ExcludingLinterDiagnostics().Should().HaveDiagnostics( + [ ("BCP353", DiagnosticLevel.Error, "The outputs \"foo\", \"FoO\" differ only in casing. The ARM deployments engine is not case sensitive and will not be able to distinguish between them."), ("BCP353", DiagnosticLevel.Error, "The outputs \"foo\", \"FoO\" differ only in casing. The ARM deployments engine is not case sensitive and will not be able to distinguish between them."), - }); + ]); result = CompilationHelper.Compile(""" type foo = string type FoO = int """); - result.ExcludingLinterDiagnostics().Should().HaveDiagnostics(new[] - { + result.ExcludingLinterDiagnostics().Should().HaveDiagnostics( + [ ("BCP353", DiagnosticLevel.Error, "The types \"foo\", \"FoO\" differ only in casing. The ARM deployments engine is not case sensitive and will not be able to distinguish between them."), ("BCP353", DiagnosticLevel.Error, "The types \"foo\", \"FoO\" differ only in casing. The ARM deployments engine is not case sensitive and will not be able to distinguish between them."), - }); + ]); result = CompilationHelper.Compile(""" param x { @@ -5014,22 +5014,22 @@ param x { } """); - result.ExcludingLinterDiagnostics().Should().HaveDiagnostics(new[] - { + result.ExcludingLinterDiagnostics().Should().HaveDiagnostics( + [ ("BCP353", DiagnosticLevel.Error, "The type properties \"foo\", \"FoO\" differ only in casing. The ARM deployments engine is not case sensitive and will not be able to distinguish between them."), ("BCP353", DiagnosticLevel.Error, "The type properties \"foo\", \"FoO\" differ only in casing. The ARM deployments engine is not case sensitive and will not be able to distinguish between them."), - }); + ]); result = CompilationHelper.Compile(Services.WithFeatureOverrides(new(AssertsEnabled: true)), """ assert foo = true assert FoO = true """); - result.ExcludingLinterDiagnostics().Should().HaveDiagnostics(new[] - { + result.ExcludingLinterDiagnostics().Should().HaveDiagnostics( + [ ("BCP353", DiagnosticLevel.Error, "The asserts \"foo\", \"FoO\" differ only in casing. The ARM deployments engine is not case sensitive and will not be able to distinguish between them."), ("BCP353", DiagnosticLevel.Error, "The asserts \"foo\", \"FoO\" differ only in casing. The ARM deployments engine is not case sensitive and will not be able to distinguish between them."), - }); + ]); // if the two symbols are of different types, ARM will be able to distinguish between them result = CompilationHelper.Compile(""" @@ -5076,10 +5076,10 @@ param baz int """); result.Template.Should().NotHaveValue(); - result.ExcludingLinterDiagnostics().Should().HaveDiagnostics(new[] - { + result.ExcludingLinterDiagnostics().Should().HaveDiagnostics( + [ ("BCP032", DiagnosticLevel.Error, "The value must be a compile-time constant."), - }); + ]); } // https://github.com/Azure/bicep/issues/11742 @@ -5121,11 +5121,11 @@ param location string """); result.Template.Should().NotBeNull(); - result.ExcludingLinterDiagnostics().Should().HaveDiagnostics(new[] - { + result.ExcludingLinterDiagnostics().Should().HaveDiagnostics( + [ ("BCP333", DiagnosticLevel.Warning, "The provided value (whose length will always be less than or equal to 8) is too short to assign to a target for which the minimum allowable length is 36."), ("BCP333", DiagnosticLevel.Warning, "The provided value (whose length will always be less than or equal to 8) is too short to assign to a target for which the minimum allowable length is 36."), - }); + ]); } // https://github.com/Azure/bicep/issues/11846 @@ -5223,21 +5223,21 @@ param tag1 string using (new AssertionScope()) { var result = CompilationHelper.Compile(withOuterScopeEvaluation); - result.Should().HaveDiagnostics(new[] - { + result.Should().HaveDiagnostics( + [ ("no-deployments-resources", DiagnosticLevel.Warning, "Resource 'nestedDeployment' of type 'Microsoft.Resources/deployments@2020-10-01' should instead be declared as a Bicep module."), - }); + ]); foreach (var innerScoped in new[] { withExplicitInnerScopeEvaluation, withImplicitInnerScopeEvaluation }) { result = CompilationHelper.Compile(innerScoped); - result.Should().HaveDiagnostics(new[] - { + result.Should().HaveDiagnostics( + [ ("no-deployments-resources", DiagnosticLevel.Warning, "Resource 'nestedDeployment' of type 'Microsoft.Resources/deployments@2020-10-01' should instead be declared as a Bicep module."), ("nested-deployment-template-scoping", DiagnosticLevel.Error, "The symbol \"tags\" is declared in the context of the outer deployment and cannot be accessed by expressions within a nested deployment template that uses inner scoping for expression evaluation."), ("nested-deployment-template-scoping", DiagnosticLevel.Error, "The symbol \"tag1\" is declared in the context of the outer deployment and cannot be accessed by expressions within a nested deployment template that uses inner scoping for expression evaluation."), ("nested-deployment-template-scoping", DiagnosticLevel.Error, "The symbol \"tag2\" is declared in the context of the outer deployment and cannot be accessed by expressions within a nested deployment template that uses inner scoping for expression evaluation."), - }); + ]); } } } @@ -5284,11 +5284,11 @@ param rgName string param rgName = rg """)); - result.Should().HaveDiagnostics(new[] - { + result.Should().HaveDiagnostics( + [ ("BCP057", DiagnosticLevel.Error, "The name \"resourceGroup\" does not exist in the current context."), ("BCP062", DiagnosticLevel.Error, "The referenced declaration with name \"rg\" is not valid."), - }); + ]); } // https://github.com/Azure/bicep/issues/11902 @@ -5317,12 +5317,12 @@ param rgName string param rgName = rg """)); - result.Should().HaveDiagnostics(new[] - { + result.Should().HaveDiagnostics( + [ ("BCP138", DiagnosticLevel.Error, "For-expressions are not supported in this context. For-expressions may be used as values of resource, module, variable, and output declarations, or values of resource and module properties."), ("BCP057", DiagnosticLevel.Error, "The name \"resourceGroup\" does not exist in the current context."), ("BCP062", DiagnosticLevel.Error, "The referenced declaration with name \"rg\" is not valid."), - }); + ]); } // https://github.com/Azure/bicep/issues/11981 @@ -5345,10 +5345,10 @@ param foo { } """)); - result.Should().HaveDiagnostics(new[] - { + result.Should().HaveDiagnostics( + [ ("BCP037", DiagnosticLevel.Error, "The property \"baz\" is not allowed on objects of type \"{ bar: string }\". No other properties are allowed."), - }); + ]); } // https://github.com/Azure/bicep/issues/12417 @@ -5411,11 +5411,11 @@ param azureEnvironments param azureEnvironments AzureEnvironmentType ")); - result.Should().HaveDiagnostics(new[] { + result.Should().HaveDiagnostics([ ("BCP018", DiagnosticLevel.Error, "Expected the \"=\" character at this location."), ("BCP259", DiagnosticLevel.Error, "The parameter \"region\" is assigned in the params file without being declared in the Bicep file."), ("BCP062", DiagnosticLevel.Error, "The referenced declaration with name \"azureEnvironments\" is not valid."), - }); + ]); } // https://github.com/Azure/bicep/issues/12640 @@ -5464,11 +5464,11 @@ public void Test_Issue12640() } """)); - result.Should().HaveDiagnostics(new[] - { + result.Should().HaveDiagnostics( + [ ("BCP022", DiagnosticLevel.Error, """Expected a property name at this location."""), ("BCP022", DiagnosticLevel.Error, """Expected a property name at this location."""), - }); + ]); } // https://github.com/Azure/bicep/issues/12912 @@ -5615,10 +5615,10 @@ param resource Resource? param subResource keyVault? """)); - result.Should().HaveDiagnostics(new[] - { + result.Should().HaveDiagnostics( + [ ("BCP037", DiagnosticLevel.Error, """The property "extraProperty" is not allowed on objects of type "{ type: 'keyvault', name: string, secrets: string[] }". No other properties are allowed."""), - }); + ]); } // https://github.com/Azure/bicep/issues/12657 @@ -5642,10 +5642,10 @@ param foo { } """)); - result.Should().HaveDiagnostics(new[] - { + result.Should().HaveDiagnostics( + [ ("BCP035", DiagnosticLevel.Error, """The specified "param" declaration is missing the following required properties: "bar"."""), - }); + ]); } // https://github.com/Azure/bicep/issues/12908 @@ -5670,11 +5670,11 @@ public void Test_Issue12908() } """)); - result.ExcludingLinterDiagnostics().Should().HaveDiagnostics(new[] - { + result.ExcludingLinterDiagnostics().Should().HaveDiagnostics( + [ ("BCP308", DiagnosticLevel.Error, """The decorator "secure" may not be used on statements whose declared type is a reference to a user-defined type."""), ("BCP308", DiagnosticLevel.Error, """The decorator "secure" may not be used on statements whose declared type is a reference to a user-defined type."""), - }); + ]); } // https://github.com/Azure/bicep/issues/13531 @@ -5692,10 +5692,10 @@ public void Test_Issue13531() param location string """)); - result.Should().HaveDiagnostics(new[] - { + result.Should().HaveDiagnostics( + [ ("BCP079", DiagnosticLevel.Error, """This expression is referencing its own declaration, which is not allowed."""), - }); + ]); } [TestMethod] @@ -5964,11 +5964,11 @@ public void Test_Issue13534() } """); - result.ExcludingLinterDiagnostics().Should().HaveDiagnostics(new[] - { + result.ExcludingLinterDiagnostics().Should().HaveDiagnostics( + [ ("BCP187", DiagnosticLevel.Warning, """The property "kind" does not exist in the resource or type definition, although it might still be valid. If this is an inaccuracy in the documentation, please report it to the Bicep Team."""), ("BCP036", DiagnosticLevel.Warning, """The property "gateway" expected a value of type "string" but the provided value is of type "object"."""), - }); + ]); } // https://github.com/Azure/bicep/issues/13556 @@ -5999,11 +5999,11 @@ public void Distinction_between_empty_and_untyped_objects_should_survive_compila param d fromJson.untypedObject = {wishy: 'washy'} """)); - result.ExcludingLinterDiagnostics().Should().HaveDiagnostics(new[] - { + result.ExcludingLinterDiagnostics().Should().HaveDiagnostics( + [ ("BCP037", DiagnosticLevel.Warning, """The property "fizz" is not allowed on objects of type "{ }". No other properties are allowed."""), ("BCP037", DiagnosticLevel.Warning, """The property "snap" is not allowed on objects of type "{ }". No other properties are allowed."""), - }); + ]); } // https://github.com/Azure/bicep/issues/13656 diff --git a/src/Bicep.Core.IntegrationTests/Scenarios/DiscriminatedObjectsTests.cs b/src/Bicep.Core.IntegrationTests/Scenarios/DiscriminatedObjectsTests.cs index 81640ebdf91..2e59dcc5c7b 100644 --- a/src/Bicep.Core.IntegrationTests/Scenarios/DiscriminatedObjectsTests.cs +++ b/src/Bicep.Core.IntegrationTests/Scenarios/DiscriminatedObjectsTests.cs @@ -114,10 +114,10 @@ public void Test_Issue657_discriminators() } ")); - failedResult.ExcludingLinterDiagnostics().Should().HaveDiagnostics(new[] { + failedResult.ExcludingLinterDiagnostics().Should().HaveDiagnostics([ ("BCP036", DiagnosticLevel.Warning, "The property \"name\" expected a value of type \"'val1' | 'val2'\" but the provided value is of type \"'notAValidVal'\". If this is an inaccuracy in the documentation, please report it to the Bicep Team."), ("BCP036", DiagnosticLevel.Warning, "The property \"name\" expected a value of type \"'val1' | 'val2'\" but the provided value is of type \"'notAValidVal'\". If this is an inaccuracy in the documentation, please report it to the Bicep Team."), - }); + ]); } [TestMethod] @@ -207,10 +207,10 @@ public void Test_Issue657_enum() } ")); - failedResult.ExcludingLinterDiagnostics().Should().HaveDiagnostics(new[] { + failedResult.ExcludingLinterDiagnostics().Should().HaveDiagnostics([ ("BCP036", DiagnosticLevel.Error, "The property \"name\" expected a value of type \"'val1' | 'val2'\" but the provided value is of type \"'notAValidVal'\"."), ("BCP036", DiagnosticLevel.Error, "The property \"name\" expected a value of type \"'val1' | 'val2'\" but the provided value is of type \"'notAValidVal'\"."), - }); + ]); } @@ -235,10 +235,10 @@ public void Test_Issue2262() } "); - result.ExcludingLinterDiagnostics().Should().HaveDiagnostics(new[] { + result.ExcludingLinterDiagnostics().Should().HaveDiagnostics([ ("BCP078", DiagnosticLevel.Warning, "The property \"partitionScheme\" requires a value of type \"'Named' | 'Singleton' | 'UniformInt64Range'\", but none was supplied."), ("BCP089", DiagnosticLevel.Warning, "The property \"PartitionScheme\" is not allowed on objects of type \"'Named' | 'Singleton' | 'UniformInt64Range'\". Did you mean \"partitionScheme\"?"), - }); + ]); var diagnosticWithCodeFix = result.Diagnostics.OfType().Single(); var codeFix = diagnosticWithCodeFix.Fixes.Single(); @@ -276,10 +276,10 @@ param properties object properties: properties } "); - result.ExcludingLinterDiagnostics().Should().HaveDiagnostics(new[] - { + result.ExcludingLinterDiagnostics().Should().HaveDiagnostics( + [ ("BCP225", DiagnosticLevel.Warning, "The discriminator property \"kind\" value cannot be determined at compilation time. Type checking for this object is disabled.") - }).And.GenerateATemplate(); + ]).And.GenerateATemplate(); } /// @@ -321,10 +321,10 @@ param values object } } "); - result.ExcludingLinterDiagnostics().Should().HaveDiagnostics(new[] - { + result.ExcludingLinterDiagnostics().Should().HaveDiagnostics( + [ ("BCP225", DiagnosticLevel.Warning, "The discriminator property \"propType\" value cannot be determined at compilation time. Type checking for this object is disabled.") - }).And.GenerateATemplate(); + ]).And.GenerateATemplate(); } /// @@ -345,10 +345,10 @@ param values object } } "); - result.ExcludingLinterDiagnostics().Should().HaveDiagnostics(new[] - { + result.ExcludingLinterDiagnostics().Should().HaveDiagnostics( + [ ("BCP225", DiagnosticLevel.Warning, "The discriminator property \"propType\" value cannot be determined at compilation time. Type checking for this object is disabled.") - }).And.GenerateATemplate(); + ]).And.GenerateATemplate(); } } diff --git a/src/Bicep.Core.IntegrationTests/Scenarios/InliningResourcesAndModulesTests.cs b/src/Bicep.Core.IntegrationTests/Scenarios/InliningResourcesAndModulesTests.cs index 37872a60171..adbf20d2bd1 100644 --- a/src/Bicep.Core.IntegrationTests/Scenarios/InliningResourcesAndModulesTests.cs +++ b/src/Bicep.Core.IntegrationTests/Scenarios/InliningResourcesAndModulesTests.cs @@ -490,10 +490,10 @@ public void ObjectVariablesWithUnknownTypeResourceReference_ShouldBeInlined() } ")); - result.ExcludingLinterDiagnostics().Should().GenerateATemplate().And.HaveDiagnostics(new[] { + result.ExcludingLinterDiagnostics().Should().GenerateATemplate().And.HaveDiagnostics([ ("BCP081", DiagnosticLevel.Warning, "Resource type \"My.Rp/myResourceType@2020-01-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."), ("BCP081", DiagnosticLevel.Warning, "Resource type \"My.Rp/myResourceType@2020-01-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.") - }); + ]); using (new AssertionScope()) { result.Template.Should().NotHaveValueAtPath("$.variables", "variable should not be generated"); diff --git a/src/Bicep.Core.IntegrationTests/Scenarios/LoadFunctionsTests.cs b/src/Bicep.Core.IntegrationTests/Scenarios/LoadFunctionsTests.cs index 8309d96f147..2d9dd1d3278 100644 --- a/src/Bicep.Core.IntegrationTests/Scenarios/LoadFunctionsTests.cs +++ b/src/Bicep.Core.IntegrationTests/Scenarios/LoadFunctionsTests.cs @@ -640,7 +640,7 @@ public void LoadJsonFunction_withPath_errorWhenPathInvalidOrDoesNotExist(string using (new AssertionScope()) { template!.Should().BeNull(); - diags.ExcludingLinterDiagnostics().Should().HaveDiagnostics(new[] { ("BCP235", DiagnosticLevel.Error, "Specified JSONPath does not exist in the given file or is invalid.") }); + diags.ExcludingLinterDiagnostics().Should().HaveDiagnostics([("BCP235", DiagnosticLevel.Error, "Specified JSONPath does not exist in the given file or is invalid.")]); } } @@ -963,7 +963,7 @@ public void LoadYamlFunction_withPath_errorWhenPathInvalidOrDoesNotExist(string using (new AssertionScope()) { template!.Should().BeNull(); - diags.ExcludingLinterDiagnostics().Should().HaveDiagnostics(new[] { ("BCP235", DiagnosticLevel.Error, "Specified JSONPath does not exist in the given file or is invalid.") }); + diags.ExcludingLinterDiagnostics().Should().HaveDiagnostics([("BCP235", DiagnosticLevel.Error, "Specified JSONPath does not exist in the given file or is invalid.")]); } } diff --git a/src/Bicep.Core.IntegrationTests/Scenarios/LocalJsonModuleTests.cs b/src/Bicep.Core.IntegrationTests/Scenarios/LocalJsonModuleTests.cs index 3c445dc6ccd..8e078fee11a 100644 --- a/src/Bicep.Core.IntegrationTests/Scenarios/LocalJsonModuleTests.cs +++ b/src/Bicep.Core.IntegrationTests/Scenarios/LocalJsonModuleTests.cs @@ -52,10 +52,10 @@ public void CompileWithLocalJsonModule_InvalidTemplate_FailsWithBCP188(string js { template.Should().BeNull(); diagnosticsByFileName.Should().NotContainKey("module.json"); - diagnosticsByFileName["main.bicep"].ExcludingLinterDiagnostics().Should().HaveDiagnostics(new[] - { + diagnosticsByFileName["main.bicep"].ExcludingLinterDiagnostics().Should().HaveDiagnostics( + [ ("BCP188", DiagnosticLevel.Error, "The referenced ARM template has errors. Please see https://aka.ms/arm-template for information on how to diagnose and fix the template."), - }); + ]); } } diff --git a/src/Bicep.Core.IntegrationTests/Scenarios/NullabilityTests.cs b/src/Bicep.Core.IntegrationTests/Scenarios/NullabilityTests.cs index 8149380f9f9..c9340537d61 100644 --- a/src/Bicep.Core.IntegrationTests/Scenarios/NullabilityTests.cs +++ b/src/Bicep.Core.IntegrationTests/Scenarios/NullabilityTests.cs @@ -23,10 +23,10 @@ public class NullabilityTests public void Unexpectedly_nullable_types_raise_fixable_warning(string templateWithNullablyTypedValue, string templateWithNonNullAssertion, TypeSymbol expectedType, TypeSymbol actualType) { var result = CompilationHelper.Compile(templateWithNullablyTypedValue); - result.ExcludingLinterDiagnostics().Should().HaveDiagnostics(new[] - { + result.ExcludingLinterDiagnostics().Should().HaveDiagnostics( + [ ("BCP321", DiagnosticLevel.Warning, $@"Expected a value of type ""{expectedType}"" but the provided value is of type ""{actualType}""."), - }); + ]); result.Template.Should().NotBeNull(); result.ExcludingLinterDiagnostics().Diagnostics.Single().Should().BeAssignableTo(); @@ -37,16 +37,16 @@ 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[] - { + return + [ // nullably typed property assignment Case( @" @@ -208,7 +208,7 @@ param csv string LanguageConstants.String, TypeHelper.CreateTypeUnion(LanguageConstants.Null, LanguageConstants.String) ), - }; + ]; } [TestMethod] @@ -221,11 +221,11 @@ param input string[] "); result.Template.Should().NotBeNull(); - result.ExcludingLinterDiagnostics().Should().HaveDiagnostics(new[] - { + result.ExcludingLinterDiagnostics().Should().HaveDiagnostics( + [ ("BCP321", DiagnosticLevel.Warning, @"Expected a value of type ""string"" but the provided value is of type ""null | string""."), ("BCP321", DiagnosticLevel.Warning, @"Expected a value of type ""array | string"" but the provided value is of type ""null | string""."), - }); + ]); } [TestMethod] @@ -237,9 +237,9 @@ param input string[] output out array = split(first(input), 21) "); - result.ExcludingLinterDiagnostics().Should().HaveDiagnostics(new[] - { + result.ExcludingLinterDiagnostics().Should().HaveDiagnostics( + [ ("BCP070", DiagnosticLevel.Error, @"Argument of type ""21"" is not assignable to parameter of type ""array | string""."), - }); + ]); } } diff --git a/src/Bicep.Core.IntegrationTests/Scenarios/ParamKeyVaultSecretReferenceTests.cs b/src/Bicep.Core.IntegrationTests/Scenarios/ParamKeyVaultSecretReferenceTests.cs index 7a79b53addf..d0e9a32df60 100644 --- a/src/Bicep.Core.IntegrationTests/Scenarios/ParamKeyVaultSecretReferenceTests.cs +++ b/src/Bicep.Core.IntegrationTests/Scenarios/ParamKeyVaultSecretReferenceTests.cs @@ -378,7 +378,7 @@ public void NoDiagnosticsForModuleWithABadPath() ")); result.Should().NotGenerateATemplate(); - result.Should().NotHaveDiagnosticsWithCodes(new[] { "BCP180" }, "Function placement should not be evaluated on a module that couldn't be read."); + result.Should().NotHaveDiagnosticsWithCodes(["BCP180"], "Function placement should not be evaluated on a module that couldn't be read."); } diff --git a/src/Bicep.Core.IntegrationTests/Scenarios/ResourceListFunctionTests.cs b/src/Bicep.Core.IntegrationTests/Scenarios/ResourceListFunctionTests.cs index 439abfc4914..031ec205758 100644 --- a/src/Bicep.Core.IntegrationTests/Scenarios/ResourceListFunctionTests.cs +++ b/src/Bicep.Core.IntegrationTests/Scenarios/ResourceListFunctionTests.cs @@ -91,11 +91,11 @@ public void Only_list_methods_are_permitted() c: stg.totallyMadeUpMethod() } "); - result.ExcludingLinterDiagnostics().Should().HaveDiagnostics(new[] { + result.ExcludingLinterDiagnostics().Should().HaveDiagnostics([ ("BCP109", DiagnosticLevel.Error, "The type \"Microsoft.Storage/storageAccounts\" does not contain function \"lis\"."), ("BCP109", DiagnosticLevel.Error, "The type \"Microsoft.Storage/storageAccounts\" does not contain function \"lsit\"."), ("BCP109", DiagnosticLevel.Error, "The type \"Microsoft.Storage/storageAccounts\" does not contain function \"totallyMadeUpMethod\"."), - }); + ]); } } } diff --git a/src/Bicep.Core.IntegrationTests/Scenarios/TopLevelResourcePropertiesTests.cs b/src/Bicep.Core.IntegrationTests/Scenarios/TopLevelResourcePropertiesTests.cs index 7efe98315c0..1c439af52cb 100644 --- a/src/Bicep.Core.IntegrationTests/Scenarios/TopLevelResourcePropertiesTests.cs +++ b/src/Bicep.Core.IntegrationTests/Scenarios/TopLevelResourcePropertiesTests.cs @@ -53,9 +53,9 @@ public void FallbackProperty_ShouldShowWarningDiagnostics1_WhenNotDefinedInType( " + $"{property}: {value}" + @" } "); - compilation.Should().HaveDiagnostics(new[] { + compilation.Should().HaveDiagnostics([ ("BCP187", DiagnosticLevel.Warning, $"The property \"{property}\" does not exist in the resource or type definition, although it might still be valid. If this is an inaccuracy in the documentation, please report it to the Bicep Team."), - }); + ]); } [DynamicData(nameof(FallbackProperties))] @@ -73,9 +73,9 @@ public void FallbackProperty_ShouldShowWarningDiagnostics2_WhenNotDefinedInType( } } "); - compilation.Should().HaveDiagnostics(new[] { + compilation.Should().HaveDiagnostics([ ("BCP037", DiagnosticLevel.Warning, $"The property \"{property}\" is not allowed on objects of type \"Properties\". Permissible properties include \"readwrite\", \"writeonly\". If this is an inaccuracy in the documentation, please report it to the Bicep Team."), - }); + ]); } [DynamicData(nameof(FallbackProperties))] @@ -95,9 +95,9 @@ public void FallbackProperty_ShouldShowWarningDiagnostics3_WhenNotDefinedInType( properties: props } "); - compilation.Should().HaveDiagnostics(new[] { + compilation.Should().HaveDiagnostics([ ("BCP037", DiagnosticLevel.Warning, $"The property \"{property}\" from source declaration \"props\" is not allowed on objects of type \"Properties\". Permissible properties include \"readwrite\", \"writeonly\". If this is an inaccuracy in the documentation, please report it to the Bicep Team."), - }); + ]); } [DynamicData(nameof(FallbackProperties))] @@ -116,9 +116,9 @@ public void FallbackProperty_ShouldShowWarning_WhenIsRead(string property, strin var value = fallbackProperty." + property + @" "); - compilation.Should().HaveDiagnostics(new[] { + compilation.Should().HaveDiagnostics([ ("BCP187", DiagnosticLevel.Warning, $"The property \"{property}\" does not exist in the resource or type definition, although it might still be valid. If this is an inaccuracy in the documentation, please report it to the Bicep Team."), - }); + ]); } [DynamicData(nameof(FallbackProperties))] @@ -174,9 +174,9 @@ param inputb string var compilation = Services.WithAzResources(BuiltInTestTypes.Types).BuildCompilation(files, mainUri); - compilation.Should().HaveDiagnostics(new[] { + compilation.Should().HaveDiagnostics([ ("BCP037", DiagnosticLevel.Error, $"The property \"{property}\" is not allowed on objects of type \"module\". Permissible properties include \"dependsOn\", \"scope\".") - }); + ]); } [DynamicData(nameof(FallbackProperties))] @@ -215,9 +215,9 @@ param inputb string var compilation = Services.WithAzResources(BuiltInTestTypes.Types).BuildCompilation(files, mainUri); - compilation.Should().HaveDiagnostics(new[] { + compilation.Should().HaveDiagnostics([ ("BCP037", DiagnosticLevel.Error, $"The property \"{property}\" is not allowed on objects of type \"params\". Permissible properties include \"inputc\".") - }); + ]); } [DynamicData(nameof(FallbackProperties))] @@ -258,10 +258,10 @@ param inputb string var compilation = Services.WithAzResources(BuiltInTestTypes.Types).BuildCompilation(files, mainUri); - compilation.Should().HaveDiagnostics(new[] { + compilation.Should().HaveDiagnostics([ ("BCP037", DiagnosticLevel.Error, $"The property \"{property}\" from source declaration \"inputs\" is not allowed on objects of type \"params\". Permissible properties include \"inputc\"."), ("BCP183", DiagnosticLevel.Error, "The value of the module \"params\" property must be an object literal."), - }); + ]); } [DynamicData(nameof(FallbackProperties))] @@ -297,9 +297,9 @@ param inputb string var compilation = Services.WithAzResources(BuiltInTestTypes.Types).BuildCompilation(files, mainUri); - compilation.Should().HaveDiagnostics(new[] { + compilation.Should().HaveDiagnostics([ ("BCP053", DiagnosticLevel.Error, $"The type \"module\" does not contain property \"{property}\". Available properties include \"name\", \"outputs\".") - }); + ]); } /// @@ -309,13 +309,13 @@ param inputb string public void Test_Issue5960_case1() { var typeReference = ResourceTypeReference.Parse("My.Rp/myResource@2020-01-01"); - var typeLoader = TestTypeHelper.CreateResourceTypeLoaderWithTypes(new[] { - new ResourceTypeComponents(typeReference, ResourceScope.ResourceGroup, ResourceScope.None, ResourceFlags.None, new ObjectType(typeReference.FormatName(), TypeSymbolValidationFlags.Default, new [] { + var typeLoader = TestTypeHelper.CreateResourceTypeLoaderWithTypes([ + new ResourceTypeComponents(typeReference, ResourceScope.ResourceGroup, ResourceScope.None, ResourceFlags.None, new ObjectType(typeReference.FormatName(), TypeSymbolValidationFlags.Default, [ new TypeProperty("name", LanguageConstants.String, TypePropertyFlags.DeployTimeConstant | TypePropertyFlags.SystemProperty, "name property"), new TypeProperty("required", LanguageConstants.String, TypePropertyFlags.Required, "required property"), new TypeProperty("systemRequired", LanguageConstants.String, TypePropertyFlags.SystemProperty | TypePropertyFlags.Required, "system required property") - }, null)) - }); + ], null)) + ]); // explicitly pass a valid scope var result = CompilationHelper.Compile(typeLoader, ("main.bicep", @" @@ -324,10 +324,10 @@ public void Test_Issue5960_case1() systemRequired: 'value' } ")); - result.Should().GenerateATemplate().And.HaveDiagnostics(new[] - { + result.Should().GenerateATemplate().And.HaveDiagnostics( + [ ("BCP035", DiagnosticLevel.Warning, "The specified \"resource\" declaration is missing the following required properties: \"required\". If this is an inaccuracy in the documentation, please report it to the Bicep Team.") - }); + ]); } /// @@ -337,13 +337,13 @@ public void Test_Issue5960_case1() public void Test_Issue5960_case2() { var typeReference = ResourceTypeReference.Parse("My.Rp/myResource@2020-01-01"); - var typeLoader = TestTypeHelper.CreateResourceTypeLoaderWithTypes(new[] { - new ResourceTypeComponents(typeReference, ResourceScope.ResourceGroup, ResourceScope.None, ResourceFlags.None, new ObjectType(typeReference.FormatName(), TypeSymbolValidationFlags.Default, new [] { + var typeLoader = TestTypeHelper.CreateResourceTypeLoaderWithTypes([ + new ResourceTypeComponents(typeReference, ResourceScope.ResourceGroup, ResourceScope.None, ResourceFlags.None, new ObjectType(typeReference.FormatName(), TypeSymbolValidationFlags.Default, [ new TypeProperty("name", LanguageConstants.String, TypePropertyFlags.DeployTimeConstant | TypePropertyFlags.SystemProperty, "name property"), new TypeProperty("required", LanguageConstants.String, TypePropertyFlags.Required, "required property"), new TypeProperty("systemRequired", LanguageConstants.String, TypePropertyFlags.SystemProperty | TypePropertyFlags.Required, "system required property") - }, null)) - }); + ], null)) + ]); // explicitly pass a valid scope var result = CompilationHelper.Compile(typeLoader, ("main.bicep", @" @@ -352,10 +352,10 @@ public void Test_Issue5960_case2() required: 'value' } ")); - result.Should().NotGenerateATemplate().And.HaveDiagnostics(new[] - { + result.Should().NotGenerateATemplate().And.HaveDiagnostics( + [ ("BCP035", DiagnosticLevel.Error, "The specified \"resource\" declaration is missing the following required properties: \"systemRequired\".") - }); + ]); } /// @@ -365,13 +365,13 @@ public void Test_Issue5960_case2() public void Test_Issue5960_case3() { var typeReference = ResourceTypeReference.Parse("My.Rp/myResource@2020-01-01"); - var typeLoader = TestTypeHelper.CreateResourceTypeLoaderWithTypes(new[] { - new ResourceTypeComponents(typeReference, ResourceScope.ResourceGroup, ResourceScope.None, ResourceFlags.None, new ObjectType(typeReference.FormatName(), TypeSymbolValidationFlags.Default, new [] { + var typeLoader = TestTypeHelper.CreateResourceTypeLoaderWithTypes([ + new ResourceTypeComponents(typeReference, ResourceScope.ResourceGroup, ResourceScope.None, ResourceFlags.None, new ObjectType(typeReference.FormatName(), TypeSymbolValidationFlags.Default, [ new TypeProperty("name", LanguageConstants.String, TypePropertyFlags.DeployTimeConstant | TypePropertyFlags.SystemProperty, "name property"), new TypeProperty("required", LanguageConstants.String, TypePropertyFlags.Required, "required property"), new TypeProperty("systemRequired", LanguageConstants.String, TypePropertyFlags.SystemProperty | TypePropertyFlags.Required, "system required property") - }, null)) - }); + ], null)) + ]); // explicitly pass a valid scope var result = CompilationHelper.Compile(typeLoader, ("main.bicep", @" @@ -379,10 +379,10 @@ public void Test_Issue5960_case3() name: 'resourceA' } ")); - result.Should().NotGenerateATemplate().And.HaveDiagnostics(new[] - { + result.Should().NotGenerateATemplate().And.HaveDiagnostics( + [ ("BCP035", DiagnosticLevel.Error, "The specified \"resource\" declaration is missing the following required properties: \"required\", \"systemRequired\". If this is an inaccuracy in the documentation, please report it to the Bicep Team.") - }); + ]); } /// @@ -392,12 +392,12 @@ public void Test_Issue5960_case3() public void Test_Issue5960_case4() { var typeReference = ResourceTypeReference.Parse("My.Rp/myResource@2020-01-01"); - var typeLoader = TestTypeHelper.CreateResourceTypeLoaderWithTypes(new[] { - new ResourceTypeComponents(typeReference, ResourceScope.ResourceGroup, ResourceScope.None, ResourceFlags.None, new ObjectType(typeReference.FormatName(), TypeSymbolValidationFlags.Default, new [] { + var typeLoader = TestTypeHelper.CreateResourceTypeLoaderWithTypes([ + new ResourceTypeComponents(typeReference, ResourceScope.ResourceGroup, ResourceScope.None, ResourceFlags.None, new ObjectType(typeReference.FormatName(), TypeSymbolValidationFlags.Default, [ new TypeProperty("name", LanguageConstants.String, TypePropertyFlags.DeployTimeConstant | TypePropertyFlags.SystemProperty, "name property"), new TypeProperty("systemRequired", LanguageConstants.String, TypePropertyFlags.SystemProperty | TypePropertyFlags.Required, "system required property") - }, null)) - }); + ], null)) + ]); // explicitly pass a valid scope var result = CompilationHelper.Compile(typeLoader, ("main.bicep", @" @@ -405,10 +405,10 @@ public void Test_Issue5960_case4() name: 'name' } ")); - result.Should().NotGenerateATemplate().And.HaveDiagnostics(new[] - { + result.Should().NotGenerateATemplate().And.HaveDiagnostics( + [ ("BCP035", DiagnosticLevel.Error, "The specified \"resource\" declaration is missing the following required properties: \"systemRequired\".") - }); + ]); } /// @@ -422,10 +422,10 @@ public void Test_Issue5960_case5() module mod 'mod.bicep' = { } "), ("mod.bicep", "")); - result.Should().NotGenerateATemplate().And.HaveDiagnostics(new[] - { + result.Should().NotGenerateATemplate().And.HaveDiagnostics( + [ ("BCP035", DiagnosticLevel.Error, "The specified \"module\" declaration is missing the following required properties: \"name\".") - }); + ]); } /// @@ -435,12 +435,12 @@ public void Test_Issue5960_case5() public void Test_Issue5960_case6() { var typeReference = ResourceTypeReference.Parse("My.Rp/myResource@2020-01-01"); - var typeLoader = TestTypeHelper.CreateResourceTypeLoaderWithTypes(new[] { - new ResourceTypeComponents(typeReference, ResourceScope.ResourceGroup, ResourceScope.None, ResourceFlags.None, new ObjectType(typeReference.FormatName(), TypeSymbolValidationFlags.Default, new [] { + var typeLoader = TestTypeHelper.CreateResourceTypeLoaderWithTypes([ + new ResourceTypeComponents(typeReference, ResourceScope.ResourceGroup, ResourceScope.None, ResourceFlags.None, new ObjectType(typeReference.FormatName(), TypeSymbolValidationFlags.Default, [ new TypeProperty("name", LanguageConstants.String, TypePropertyFlags.DeployTimeConstant | TypePropertyFlags.SystemProperty, "name property"), new TypeProperty("required", LanguageConstants.Object, TypePropertyFlags.Required, "required property"), - }, null)) - }); + ], null)) + ]); // explicitly pass a valid scope var result = CompilationHelper.Compile(typeLoader, ("main.bicep", @" @@ -450,10 +450,10 @@ param str string required: str } ")); - result.Should().GenerateATemplate().And.HaveDiagnostics(new[] - { + result.Should().GenerateATemplate().And.HaveDiagnostics( + [ ("BCP036", DiagnosticLevel.Warning, "The property \"required\" expected a value of type \"object\" but the provided value is of type \"string\". If this is an inaccuracy in the documentation, please report it to the Bicep Team.") - }); + ]); } /// /// https://github.com/Azure/bicep/issues/5960 @@ -462,12 +462,12 @@ param str string public void Test_Issue5960_case7() { var typeReference = ResourceTypeReference.Parse("My.Rp/myResource@2020-01-01"); - var typeLoader = TestTypeHelper.CreateResourceTypeLoaderWithTypes(new[] { - new ResourceTypeComponents(typeReference, ResourceScope.ResourceGroup, ResourceScope.None, ResourceFlags.None, new ObjectType(typeReference.FormatName(), TypeSymbolValidationFlags.Default, new [] { + var typeLoader = TestTypeHelper.CreateResourceTypeLoaderWithTypes([ + new ResourceTypeComponents(typeReference, ResourceScope.ResourceGroup, ResourceScope.None, ResourceFlags.None, new ObjectType(typeReference.FormatName(), TypeSymbolValidationFlags.Default, [ new TypeProperty("name", LanguageConstants.String, TypePropertyFlags.DeployTimeConstant | TypePropertyFlags.SystemProperty, "name property"), new TypeProperty("systemRequired", LanguageConstants.Object, TypePropertyFlags.Required | TypePropertyFlags.SystemProperty, "system required property"), - }, null)) - }); + ], null)) + ]); // explicitly pass a valid scope var result = CompilationHelper.Compile(typeLoader, ("main.bicep", @" @@ -477,10 +477,10 @@ param str string systemRequired: str } ")); - result.Should().NotGenerateATemplate().And.HaveDiagnostics(new[] - { + result.Should().NotGenerateATemplate().And.HaveDiagnostics( + [ ("BCP036", DiagnosticLevel.Error, "The property \"systemRequired\" expected a value of type \"object\" but the provided value is of type \"string\".") - }); + ]); } /// /// https://github.com/Azure/bicep/issues/5960 @@ -489,13 +489,13 @@ param str string public void Test_Issue5960_case8() { var typeReference = ResourceTypeReference.Parse("My.Rp/myResource@2020-01-01"); - var typeLoader = TestTypeHelper.CreateResourceTypeLoaderWithTypes(new[] { - new ResourceTypeComponents(typeReference, ResourceScope.ResourceGroup, ResourceScope.None, ResourceFlags.None, new ObjectType(typeReference.FormatName(), TypeSymbolValidationFlags.Default, new [] { + var typeLoader = TestTypeHelper.CreateResourceTypeLoaderWithTypes([ + new ResourceTypeComponents(typeReference, ResourceScope.ResourceGroup, ResourceScope.None, ResourceFlags.None, new ObjectType(typeReference.FormatName(), TypeSymbolValidationFlags.Default, [ new TypeProperty("name", LanguageConstants.String, TypePropertyFlags.DeployTimeConstant | TypePropertyFlags.SystemProperty, "name property"), new TypeProperty("systemRequired", LanguageConstants.Object, TypePropertyFlags.Required | TypePropertyFlags.SystemProperty, "system required property"), new TypeProperty("required", LanguageConstants.Object, TypePropertyFlags.Required, "required property"), - }, null)) - }); + ], null)) + ]); // explicitly pass a valid scope var result = CompilationHelper.Compile(typeLoader, ("main.bicep", @" @@ -506,11 +506,11 @@ param str string required: str } ")); - result.Should().NotGenerateATemplate().And.HaveDiagnostics(new[] - { + result.Should().NotGenerateATemplate().And.HaveDiagnostics( + [ ("BCP036", DiagnosticLevel.Error, "The property \"systemRequired\" expected a value of type \"object\" but the provided value is of type \"string\"."), ("BCP036", DiagnosticLevel.Warning, "The property \"required\" expected a value of type \"object\" but the provided value is of type \"string\". If this is an inaccuracy in the documentation, please report it to the Bicep Team.") - }); + ]); } /// @@ -553,10 +553,10 @@ public void Test_Issue5960_case9() kind: 'otherValue' } ")); - result.Should().GenerateATemplate().And.HaveDiagnostics(new[] - { + result.Should().GenerateATemplate().And.HaveDiagnostics( + [ ("BCP036", DiagnosticLevel.Warning, "The property \"kind\" expected a value of type \"'val1' | 'val2'\" but the provided value is of type \"'otherValue'\". If this is an inaccuracy in the documentation, please report it to the Bicep Team.") - }); + ]); } } } diff --git a/src/Bicep.Core.IntegrationTests/ScopeTests.cs b/src/Bicep.Core.IntegrationTests/ScopeTests.cs index 67f377f124c..92aa605b76d 100644 --- a/src/Bicep.Core.IntegrationTests/ScopeTests.cs +++ b/src/Bicep.Core.IntegrationTests/ScopeTests.cs @@ -183,12 +183,12 @@ public void Emitter_should_generate_correct_references_for_existing_resources(st public void Existing_resources_can_be_referenced_at_other_scopes() { var typeReference = ResourceTypeReference.Parse("My.Rp/myResource@2020-01-01"); - var typeLoader = TestTypeHelper.CreateResourceTypeLoaderWithTypes(new[] { - new ResourceTypeComponents(typeReference, ResourceScope.ResourceGroup, ResourceScope.None, ResourceFlags.None, new ObjectType(typeReference.FormatName(), TypeSymbolValidationFlags.Default, new [] { + var typeLoader = TestTypeHelper.CreateResourceTypeLoaderWithTypes([ + new ResourceTypeComponents(typeReference, ResourceScope.ResourceGroup, ResourceScope.None, ResourceFlags.None, new ObjectType(typeReference.FormatName(), TypeSymbolValidationFlags.Default, [ new TypeProperty("name", LanguageConstants.String, TypePropertyFlags.DeployTimeConstant, "name property"), new TypeProperty("kind", LanguageConstants.String, TypePropertyFlags.ReadOnly, "kind property"), - }, null)) - }); + ], null)) + ]); // explicitly pass a valid scope var (template, _, _) = CompilationHelper.Compile(typeLoader, ("main.bicep", @" @@ -226,11 +226,11 @@ public void Existing_resources_can_be_referenced_at_other_scopes() public void Errors_are_raised_for_existing_resources_at_invalid_scopes() { var typeReference = ResourceTypeReference.Parse("My.Rp/myResource@2020-01-01"); - var typeLoader = TestTypeHelper.CreateResourceTypeLoaderWithTypes(new[] { - new ResourceTypeComponents(typeReference, ResourceScope.ResourceGroup, ResourceScope.None, ResourceFlags.None, new ObjectType(typeReference.FormatName(), TypeSymbolValidationFlags.Default, new [] { + var typeLoader = TestTypeHelper.CreateResourceTypeLoaderWithTypes([ + new ResourceTypeComponents(typeReference, ResourceScope.ResourceGroup, ResourceScope.None, ResourceFlags.None, new ObjectType(typeReference.FormatName(), TypeSymbolValidationFlags.Default, [ new TypeProperty("name", LanguageConstants.String, TypePropertyFlags.DeployTimeConstant, "name property"), - }, null)) - }); + ], null)) + ]); // explicitly pass an invalid scope var (_, diags, _) = CompilationHelper.Compile(typeLoader, ("main.bicep", @" @@ -240,10 +240,10 @@ public void Errors_are_raised_for_existing_resources_at_invalid_scopes() } ")); - diags.Should().HaveDiagnostics(new[] { + diags.Should().HaveDiagnostics([ ("no-unused-existing-resources", DiagnosticLevel.Warning, "Existing resource \"resourceA\" is declared but never used."), ("BCP135", DiagnosticLevel.Error, "Scope \"subscription\" is not valid for this resource type. Permitted scopes: \"resourceGroup\"."), - }); + ]); // use an invalid targetScope without setting the scope property (_, diags, _) = CompilationHelper.Compile(typeLoader, ("main.bicep", @" @@ -254,21 +254,21 @@ public void Errors_are_raised_for_existing_resources_at_invalid_scopes() } ")); - diags.Should().HaveDiagnostics(new[] { + diags.Should().HaveDiagnostics([ ("no-unused-existing-resources", DiagnosticLevel.Warning, "Existing resource \"resourceA\" is declared but never used."), ("BCP135", DiagnosticLevel.Error, "Scope \"subscription\" is not valid for this resource type. Permitted scopes: \"resourceGroup\"."), - }); + ]); } [TestMethod] public void Errors_are_raised_for_extensions_of_existing_resources_at_invalid_scopes() { var typeReference = ResourceTypeReference.Parse("My.Rp/myResource@2020-01-01"); - var typeLoader = TestTypeHelper.CreateResourceTypeLoaderWithTypes(new[] { - new ResourceTypeComponents(typeReference, ResourceScope.ResourceGroup | ResourceScope.Resource, ResourceScope.None, ResourceFlags.None, new ObjectType(typeReference.FormatName(), TypeSymbolValidationFlags.Default, new [] { + var typeLoader = TestTypeHelper.CreateResourceTypeLoaderWithTypes([ + new ResourceTypeComponents(typeReference, ResourceScope.ResourceGroup | ResourceScope.Resource, ResourceScope.None, ResourceFlags.None, new ObjectType(typeReference.FormatName(), TypeSymbolValidationFlags.Default, [ new TypeProperty("name", LanguageConstants.String, TypePropertyFlags.DeployTimeConstant, "name property"), - }, null)) - }); + ], null)) + ]); // extension resource of an existing resource at an invalid scope var (_, diags, _) = CompilationHelper.Compile(typeLoader, ("main.bicep", @" @@ -283,20 +283,20 @@ public void Errors_are_raised_for_extensions_of_existing_resources_at_invalid_sc } ")); - diags.Should().HaveDiagnostics(new[] { + diags.Should().HaveDiagnostics([ ("BCP139", DiagnosticLevel.Error, "A resource's scope must match the scope of the Bicep file for it to be deployable. You must use modules to deploy resources to a different scope."), - }); + ]); } [TestMethod] public void Extensions_of_existing_resources_are_permitted() { var typeReference = ResourceTypeReference.Parse("My.Rp/myResource@2020-01-01"); - var typeLoader = TestTypeHelper.CreateResourceTypeLoaderWithTypes(new[] { - new ResourceTypeComponents(typeReference, ResourceScope.ResourceGroup | ResourceScope.Resource, ResourceScope.None, ResourceFlags.None, new ObjectType(typeReference.FormatName(), TypeSymbolValidationFlags.Default, new [] { + var typeLoader = TestTypeHelper.CreateResourceTypeLoaderWithTypes([ + new ResourceTypeComponents(typeReference, ResourceScope.ResourceGroup | ResourceScope.Resource, ResourceScope.None, ResourceFlags.None, new ObjectType(typeReference.FormatName(), TypeSymbolValidationFlags.Default, [ new TypeProperty("name", LanguageConstants.String, TypePropertyFlags.DeployTimeConstant, "name property"), - }, null)) - }); + ], null)) + ]); // extension resource of an existing resource at an invalid scope var (template, diags, _) = CompilationHelper.Compile(typeLoader, ("main.bicep", @" @@ -326,11 +326,11 @@ public void Extensions_of_existing_resources_are_permitted() public void Tenant_scope_resources_can_be_deployed_from_anywhere(string targetScope, bool tenantScopeExpected) { var typeReference = ResourceTypeReference.Parse("My.Rp/myResource@2020-01-01"); - var typeLoader = TestTypeHelper.CreateResourceTypeLoaderWithTypes(new[] { - new ResourceTypeComponents(typeReference, ResourceScope.Tenant, ResourceScope.None, ResourceFlags.None, new ObjectType(typeReference.FormatName(), TypeSymbolValidationFlags.Default, new [] { + var typeLoader = TestTypeHelper.CreateResourceTypeLoaderWithTypes([ + new ResourceTypeComponents(typeReference, ResourceScope.Tenant, ResourceScope.None, ResourceFlags.None, new ObjectType(typeReference.FormatName(), TypeSymbolValidationFlags.Default, [ new TypeProperty("name", LanguageConstants.String, TypePropertyFlags.DeployTimeConstant, "name property"), - }, null)) - }); + ], null)) + ]); var (template, diags, _) = CompilationHelper.Compile(typeLoader, ("main.bicep", @" targetScope = 'TARGET_SCOPE' 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/TestFrameworkTests.cs b/src/Bicep.Core.IntegrationTests/TestFrameworkTests.cs index 58d3c1d9280..45a49183dd9 100644 --- a/src/Bicep.Core.IntegrationTests/TestFrameworkTests.cs +++ b/src/Bicep.Core.IntegrationTests/TestFrameworkTests.cs @@ -25,42 +25,42 @@ public void TestFramework_is_disabled_unless_feature_is_enabled() var result = CompilationHelper.Compile(@" test test1 '' = {} "); - result.Should().HaveDiagnostics(new[] { + result.Should().HaveDiagnostics([ ("BCP348", DiagnosticLevel.Error, "Using a test declaration statement requires enabling EXPERIMENTAL feature \"TestFramework\"."), ("BCP050", DiagnosticLevel.Error, @"The specified path is empty."), - }); + ]); result = CompilationHelper.Compile(@" test test1 '' = "); - result.Should().HaveDiagnostics(new[] { + result.Should().HaveDiagnostics([ ("BCP348", DiagnosticLevel.Error, "Using a test declaration statement requires enabling EXPERIMENTAL feature \"TestFramework\"."), ("BCP050", DiagnosticLevel.Error, @"The specified path is empty."), ("BCP018", DiagnosticLevel.Error, "Expected the \"{\" character at this location."), - }); + ]); result = CompilationHelper.Compile(@" test test1 '' "); - result.Should().HaveDiagnostics(new[] { + result.Should().HaveDiagnostics([ ("BCP348", DiagnosticLevel.Error, "Using a test declaration statement requires enabling EXPERIMENTAL feature \"TestFramework\"."), ("BCP050", DiagnosticLevel.Error, @"The specified path is empty."), ("BCP018", DiagnosticLevel.Error, "Expected the \"=\" character at this location."), - }); + ]); result = CompilationHelper.Compile(@" test test1 "); - result.Should().HaveDiagnostics(new[] { + result.Should().HaveDiagnostics([ ("BCP348", DiagnosticLevel.Error, "Using a test declaration statement requires enabling EXPERIMENTAL feature \"TestFramework\"."), ("BCP0347", DiagnosticLevel.Error, "Expected a test path string at this location."), ("BCP358", DiagnosticLevel.Error, "This declaration is missing a template file path reference.") - }); + ]); result = CompilationHelper.Compile(@" test "); - result.Should().HaveDiagnostics(new[] { + result.Should().HaveDiagnostics([ ("BCP348", DiagnosticLevel.Error, "Using a test declaration statement requires enabling EXPERIMENTAL feature \"TestFramework\"."), ("BCP0346", DiagnosticLevel.Error, "Expected a test identifier at this location."), ("BCP358", DiagnosticLevel.Error, "This declaration is missing a template file path reference.") - }); + ]); } [TestMethod] @@ -69,27 +69,27 @@ public void TestFramework_statement_parse_diagnostics_are_guiding() var result = CompilationHelper.Compile(ServicesWithTestFramework, @" test "); - result.Should().HaveDiagnostics(new[] { + result.Should().HaveDiagnostics([ ("BCP0346", DiagnosticLevel.Error, "Expected a test identifier at this location."), ("BCP358", DiagnosticLevel.Error, "This declaration is missing a template file path reference.") - }); + ]); result = CompilationHelper.Compile(ServicesWithTestFramework, @" test test1 "); - result.Should().HaveDiagnostics(new[] { + result.Should().HaveDiagnostics([ ("BCP0347", DiagnosticLevel.Error, "Expected a test path string at this location."), ("BCP358", DiagnosticLevel.Error, "This declaration is missing a template file path reference.") - }); + ]); result = CompilationHelper.Compile(ServicesWithTestFramework, @" test test1 '' "); - result.Should().HaveDiagnostics(new[] { + result.Should().HaveDiagnostics([ ("BCP050", DiagnosticLevel.Error, @"The specified path is empty."), ("BCP018", DiagnosticLevel.Error, "Expected the \"=\" character at this location."), - }); + ]); } [TestMethod] @@ -123,9 +123,9 @@ public void TestFramework_should_have_diagnostics_on_wrong_parameter_type() param name string ")); - result.Should().HaveDiagnostics(new[] { + result.Should().HaveDiagnostics([ ("BCP036", DiagnosticLevel.Error, "The property \"name\" expected a value of type \"string\" but the provided value is of type \"1\"."), - }); + ]); } [TestMethod] @@ -141,9 +141,9 @@ public void TestFramework_should_have_diagnostics_when_missing_parameters() param name string ")); - result.Should().HaveDiagnostics(new[] { + result.Should().HaveDiagnostics([ ("BCP035", DiagnosticLevel.Error, "The specified \"object\" declaration is missing the following required properties: \"name\"."), - }); + ]); } [TestMethod] @@ -157,9 +157,9 @@ public void TestFramework_should_have_diagnostics_when_missing_parameters_proper param name string ")); - result.Should().HaveDiagnostics(new[] { + result.Should().HaveDiagnostics([ ("BCP035", DiagnosticLevel.Error, "The specified \"test\" declaration is missing the following required properties: \"params\"."), - }); + ]); } } diff --git a/src/Bicep.Core.IntegrationTests/TypeSystem/TypeValidationTests.cs b/src/Bicep.Core.IntegrationTests/TypeSystem/TypeValidationTests.cs index 5c9c0afa66c..86e18f2ae68 100644 --- a/src/Bicep.Core.IntegrationTests/TypeSystem/TypeValidationTests.cs +++ b/src/Bicep.Core.IntegrationTests/TypeSystem/TypeValidationTests.cs @@ -54,27 +54,27 @@ public void Type_validation_runs_on_compilation_common_failures(TypeSymbolValida { var customTypes = new[] { TestTypeHelper.CreateCustomResourceTypeWithTopLevelProperties("My.Rp/myType", "2020-01-01", validationFlags, - new [] { new TypeProperty("readOnlyTopLevelProp", LanguageConstants.String, TypePropertyFlags.ReadOnly) }, + [new TypeProperty("readOnlyTopLevelProp", LanguageConstants.String, TypePropertyFlags.ReadOnly)], new TypeProperty("readOnlyProp", LanguageConstants.String, TypePropertyFlags.ReadOnly), new TypeProperty("writeOnlyProp", LanguageConstants.String, TypePropertyFlags.WriteOnly | TypePropertyFlags.AllowImplicitNull), new TypeProperty("requiredProp", LanguageConstants.String, TypePropertyFlags.Required), new TypeProperty("additionalProps", new ObjectType( "additionalProps", validationFlags, - new [] { + [ new TypeProperty("propA", LanguageConstants.String, TypePropertyFlags.Required), new TypeProperty("propB", LanguageConstants.String, TypePropertyFlags.AllowImplicitNull), - }, + ], LanguageConstants.Int )), new TypeProperty("nestedObj", new ObjectType( "nestedObj", validationFlags, - new [] { + [ new TypeProperty("readOnlyNestedProp", LanguageConstants.String, TypePropertyFlags.ReadOnly), new TypeProperty("writeOnlyNestedProp", LanguageConstants.String, TypePropertyFlags.WriteOnly | TypePropertyFlags.AllowImplicitNull), new TypeProperty("requiredNestedProp", LanguageConstants.String, TypePropertyFlags.Required), - }, + ], null ))), }; @@ -181,16 +181,16 @@ public void Type_validation_narrowing_on_discriminated_object_types(TypeSymbolVa { var customTypes = new[] { TestTypeHelper.CreateCustomResourceType("My.Rp/myType", "2020-01-01", validationFlags, - new TypeProperty("myDisc1", new DiscriminatedObjectType("myDisc1", validationFlags, "discKey", new [] { - new ObjectType("choiceA", validationFlags, new [] { + new TypeProperty("myDisc1", new DiscriminatedObjectType("myDisc1", validationFlags, "discKey", [ + new ObjectType("choiceA", validationFlags, [ new TypeProperty("discKey", TypeFactory.CreateStringLiteralType("choiceA"), TypePropertyFlags.Required), new TypeProperty("valueA", LanguageConstants.String, TypePropertyFlags.Required), - }, null), - new ObjectType("choiceB", validationFlags, new [] { + ], null), + new ObjectType("choiceB", validationFlags, [ new TypeProperty("discKey", TypeFactory.CreateStringLiteralType("choiceB"), TypePropertyFlags.Required), new TypeProperty("valueB", LanguageConstants.String, TypePropertyFlags.Required), - }, null), - } + ], null), + ] ))), }; @@ -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.IntegrationTests/UserDefinedFunctionTests.cs b/src/Bicep.Core.IntegrationTests/UserDefinedFunctionTests.cs index 64f78378e36..3ddb1b72427 100644 --- a/src/Bicep.Core.IntegrationTests/UserDefinedFunctionTests.cs +++ b/src/Bicep.Core.IntegrationTests/UserDefinedFunctionTests.cs @@ -39,10 +39,10 @@ func getBaz() string => 'baz' func testFunc(baz string) string => '${foo}-${bar}-${baz}-${getBaz()}' "); - result.ExcludingLinterDiagnostics().Should().HaveDiagnostics(new[] { + result.ExcludingLinterDiagnostics().Should().HaveDiagnostics([ ("BCP057", DiagnosticLevel.Error, """The name "foo" does not exist in the current context."""), ("BCP057", DiagnosticLevel.Error, """The name "bar" does not exist in the current context."""), - }); + ]); } [TestMethod] @@ -84,8 +84,8 @@ public void User_defined_functions_unsupported_runtime_functions() func useRuntimeFunction() string => reference('foo').bar "); - result.Should().HaveDiagnostics(new[] { + result.Should().HaveDiagnostics([ ("BCP341", DiagnosticLevel.Error, "This expression is being used inside a function declaration, which requires a value that can be calculated at the start of the deployment."), - }); + ]); } } diff --git a/src/Bicep.Core.IntegrationTests/UserDefinedTypeTests.cs b/src/Bicep.Core.IntegrationTests/UserDefinedTypeTests.cs index db805d1d18e..3750f3badbe 100644 --- a/src/Bicep.Core.IntegrationTests/UserDefinedTypeTests.cs +++ b/src/Bicep.Core.IntegrationTests/UserDefinedTypeTests.cs @@ -93,10 +93,10 @@ public void Masked_types_still_accessible_via_qualified_reference() param stringParam string = 'foo' "); - result.Should().HaveDiagnostics(new[] { + result.Should().HaveDiagnostics([ ("no-unused-params", DiagnosticLevel.Warning, "Parameter \"stringParam\" is declared but never used."), ("BCP033", DiagnosticLevel.Error, "Expected a value of type \"int\" but the provided value is of type \"'foo'\"."), - }); + ]); // fix by fully-qualifying result = CompilationHelper.Compile(@" @@ -105,9 +105,9 @@ public void Masked_types_still_accessible_via_qualified_reference() param stringParam sys.string = 'foo' "); - result.Should().HaveDiagnostics(new[] { + result.Should().HaveDiagnostics([ ("no-unused-params", DiagnosticLevel.Warning, "Parameter \"stringParam\" is declared but never used."), - }); + ]); } [TestMethod] @@ -148,7 +148,7 @@ param stringParam constrainedString param intParam constrainedInt "); - result.Should().HaveDiagnostics(new[] { + result.Should().HaveDiagnostics([ ("BCP308", DiagnosticLevel.Error, "The decorator \"minLength\" may not be used on statements whose declared type is a reference to a user-defined type."), ("BCP308", DiagnosticLevel.Error, "The decorator \"maxLength\" may not be used on statements whose declared type is a reference to a user-defined type."), ("BCP308", DiagnosticLevel.Error, "The decorator \"minValue\" may not be used on statements whose declared type is a reference to a user-defined type."), @@ -162,7 +162,7 @@ param intParam constrainedInt ("BCP308", DiagnosticLevel.Error, "The decorator \"maxValue\" may not be used on statements whose declared type is a reference to a user-defined type."), ("BCP308", DiagnosticLevel.Error, "The decorator \"allowed\" may not be used on statements whose declared type is a reference to a user-defined type."), ("no-unused-params", DiagnosticLevel.Warning, "Parameter \"intParam\" is declared but never used."), - }); + ]); } [TestMethod] @@ -191,7 +191,7 @@ param fizzParam 'fizz' param fizzBuzzPopParam 'fizz'|'buzz'|'pop' "); - result.Should().HaveDiagnostics(new[] { + result.Should().HaveDiagnostics([ ("BCP295", DiagnosticLevel.Error, "The 'allowed' decorator may not be used on targets of a union or literal type. The allowed values for this parameter or type definition will be derived from the union or literal type automatically."), ("no-unused-params", DiagnosticLevel.Warning, "Parameter \"trueParam\" is declared but never used."), ("BCP295", DiagnosticLevel.Error, "The 'allowed' decorator may not be used on targets of a union or literal type. The allowed values for this parameter or type definition will be derived from the union or literal type automatically."), @@ -206,7 +206,7 @@ param fizzBuzzPopParam 'fizz'|'buzz'|'pop' ("no-unused-params", DiagnosticLevel.Warning, "Parameter \"fizzParam\" is declared but never used."), ("BCP295", DiagnosticLevel.Error, "The 'allowed' decorator may not be used on targets of a union or literal type. The allowed values for this parameter or type definition will be derived from the union or literal type automatically."), ("no-unused-params", DiagnosticLevel.Warning, "Parameter \"fizzBuzzPopParam\" is declared but never used."), - }); + ]); } [TestMethod] @@ -218,10 +218,10 @@ public void Unions_that_incorporate_their_parent_object_do_not_blow_the_stack() } "); - blockedBecauseOfCycle.Should().HaveDiagnostics(new[] { + blockedBecauseOfCycle.Should().HaveDiagnostics([ ("BCP298", DiagnosticLevel.Error, "This type definition includes itself as required component, which creates a constraint that cannot be fulfilled."), ("BCP293", DiagnosticLevel.Error, "All members of a union type declaration must be literal values."), - }); + ]); var blockedBecauseOfUnionSemantics = CompilationHelper.Compile(@" type anObject = { @@ -229,9 +229,9 @@ public void Unions_that_incorporate_their_parent_object_do_not_blow_the_stack() } "); - blockedBecauseOfUnionSemantics.Should().HaveDiagnostics(new[] { + blockedBecauseOfUnionSemantics.Should().HaveDiagnostics([ ("BCP293", DiagnosticLevel.Error, "All members of a union type declaration must be literal values."), - }); + ]); } [TestMethod] @@ -243,9 +243,9 @@ public void Unary_operations_that_incorporate_their_parent_object_do_not_blow_th } "); - blockedBecauseOfCycle.Should().HaveDiagnostics(new[] { + blockedBecauseOfCycle.Should().HaveDiagnostics([ ("BCP285", DiagnosticLevel.Error, "The type expression could not be reduced to a literal value."), - }); + ]); } [TestMethod] @@ -257,9 +257,9 @@ public void Arrays_that_incorporate_their_parent_object_do_not_blow_the_stack() } "); - blockedBecauseOfCycle.Should().HaveDiagnostics(new[] { + blockedBecauseOfCycle.Should().HaveDiagnostics([ ("BCP298", DiagnosticLevel.Error, "This type definition includes itself as required component, which creates a constraint that cannot be fulfilled."), - }); + ]); var permitted = CompilationHelper.Compile(@" type anObject = { @@ -289,9 +289,9 @@ public void Cyclic_nullables_do_not_blow_the_stack() type nullable = nullable? "); - blockedBecauseOfCycle.Should().HaveDiagnostics(new[] { + blockedBecauseOfCycle.Should().HaveDiagnostics([ ("BCP298", DiagnosticLevel.Error, "This type definition includes itself as required component, which creates a constraint that cannot be fulfilled."), - }); + ]); } [TestMethod] @@ -303,9 +303,9 @@ public void Tuples_that_incorporate_their_parent_object_do_not_blow_the_stack() } "); - blockedBecauseOfCycle.Should().HaveDiagnostics(new[] { + blockedBecauseOfCycle.Should().HaveDiagnostics([ ("BCP298", DiagnosticLevel.Error, "This type definition includes itself as required component, which creates a constraint that cannot be fulfilled."), - }); + ]); var permitted = CompilationHelper.Compile(@" type anObject = { @@ -347,9 +347,9 @@ public void Objects_that_incorporate_their_parent_object_do_not_blow_the_stack() } "); - blockedBecauseOfCycle.Should().HaveDiagnostics(new[] { + blockedBecauseOfCycle.Should().HaveDiagnostics([ ("BCP298", DiagnosticLevel.Error, "This type definition includes itself as required component, which creates a constraint that cannot be fulfilled."), - }); + ]); var permitted = CompilationHelper.Compile(@" type anObject = { @@ -393,9 +393,9 @@ public void Cyclic_check_understands_nullability_modifiers() }? "); - blockedBecauseOfCycle.Should().HaveDiagnostics(new[] { + blockedBecauseOfCycle.Should().HaveDiagnostics([ ("BCP298", DiagnosticLevel.Error, "This type definition includes itself as required component, which creates a constraint that cannot be fulfilled."), - }); + ]); blockedBecauseOfCycle = CompilationHelper.Compile(@" type anObject = { @@ -405,9 +405,9 @@ public void Cyclic_check_understands_nullability_modifiers() }?! "); - blockedBecauseOfCycle.Should().HaveDiagnostics(new[] { + blockedBecauseOfCycle.Should().HaveDiagnostics([ ("BCP298", DiagnosticLevel.Error, "This type definition includes itself as required component, which creates a constraint that cannot be fulfilled."), - }); + ]); var permitted = CompilationHelper.Compile(@" type anObject = { @@ -429,9 +429,9 @@ param anObject {} output prop string = anObject.prop "); - result.Should().HaveDiagnostics(new[] { + result.Should().HaveDiagnostics([ ("BCP187", DiagnosticLevel.Warning, "The property \"prop\" does not exist in the resource or type definition, although it might still be valid. If this is an inaccuracy in the documentation, please report it to the Bicep Team."), - }); + ]); } [TestMethod] @@ -445,9 +445,9 @@ public void Warning_should_be_shown_when_setting_unknown_properties_on_unsealed_ param anotherObject object = {prop: 'someVal'} "); - result.Should().HaveDiagnostics(new[] { + result.Should().HaveDiagnostics([ ("BCP037", DiagnosticLevel.Warning, "The property \"prop\" is not allowed on objects of type \"{ }\". No other properties are allowed."), - }); + ]); } [TestMethod] @@ -472,9 +472,9 @@ param aDict { } = {prop: 'someVal'} "); - result.Should().HaveDiagnostics(new[] { + result.Should().HaveDiagnostics([ ("BCP036", DiagnosticLevel.Error, @"The property ""prop"" expected a value of type ""int"" but the provided value is of type ""'someVal'""."), - }); + ]); result = CompilationHelper.Compile(@" #disable-next-line no-unused-params @@ -550,10 +550,10 @@ param foos (null | { bar: { baz: { quux: 'quux' } } })[] "; var result = CompilationHelper.Compile(templateWithPossiblyNullDeref); - result.Should().HaveDiagnostics(new[] - { + result.Should().HaveDiagnostics( + [ ("BCP318", DiagnosticLevel.Warning, @"The value of type ""null | { bar: { baz: { quux: 'quux' } } }"" may be null at the start of the deployment, which would cause this access expression (and the overall deployment with it) to fail."), - }); + ]); result.Diagnostics.Single().Should().BeAssignableTo(); var fixAlternatives = new HashSet { templateWithNonNullAssertion, templateWithSafeDeref }; @@ -583,9 +583,9 @@ public void Error_should_be_emitted_when_setting_a_default_value_on_a_nullable_p param myParam string? = 'foo' "); - result.Should().HaveDiagnostics(new[] { + result.Should().HaveDiagnostics([ ("BCP326", DiagnosticLevel.Error, "Nullable-typed parameters may not be assigned default values. They have an implicit default of 'null' that cannot be overridden."), - }); + ]); } [TestMethod] @@ -670,10 +670,10 @@ public void Type_aliases_incorporate_modifiers_into_type() param myString shortString = 'foo' "); - result.ExcludingLinterDiagnostics().Should().HaveDiagnostics(new[] - { + result.ExcludingLinterDiagnostics().Should().HaveDiagnostics( + [ ("BCP332", DiagnosticLevel.Error, "The provided value (whose length will always be greater than or equal to 3) is too long to assign to a target for which the maximum allowable length is 2."), - }); + ]); } [TestMethod] @@ -685,10 +685,10 @@ public void Impossible_integer_domains_raise_descriptive_error() param myParam int "); - result.ExcludingLinterDiagnostics().Should().HaveDiagnostics(new[] - { + result.ExcludingLinterDiagnostics().Should().HaveDiagnostics( + [ ("BCP331", DiagnosticLevel.Error, "A type's \"minValue\" must be less than or equal to its \"maxValue\", but a minimum of 1 and a maximum of 0 were specified."), - }); + ]); } [TestMethod] @@ -700,10 +700,10 @@ public void Impossible_array_length_domains_raise_descriptive_error() param myParam array "); - result.ExcludingLinterDiagnostics().Should().HaveDiagnostics(new[] - { + result.ExcludingLinterDiagnostics().Should().HaveDiagnostics( + [ ("BCP331", DiagnosticLevel.Error, "A type's \"minLength\" must be less than or equal to its \"maxLength\", but a minimum of 1 and a maximum of 0 were specified."), - }); + ]); } [TestMethod] @@ -715,10 +715,10 @@ public void Impossible_string_length_domains_raise_descriptive_error() param myParam string "); - result.ExcludingLinterDiagnostics().Should().HaveDiagnostics(new[] - { + result.ExcludingLinterDiagnostics().Should().HaveDiagnostics( + [ ("BCP331", DiagnosticLevel.Error, "A type's \"minLength\" must be less than or equal to its \"maxLength\", but a minimum of 1 and a maximum of 0 were specified."), - }); + ]); } [TestMethod] @@ -731,10 +731,10 @@ public void Duplicate_property_names_should_raise_descriptive_diagnostic() } """); - result.ExcludingLinterDiagnostics().Should().HaveDiagnostics(new[] - { + result.ExcludingLinterDiagnostics().Should().HaveDiagnostics( + [ ("BCP025", DiagnosticLevel.Error, "The property \"bar\" is declared multiple times in this object. Remove or rename the duplicate properties.") - }); + ]); } [TestMethod] @@ -837,11 +837,11 @@ public void Self_property_deref_does_not_blow_the_stack() } """); - result.ExcludingLinterDiagnostics().Should().HaveDiagnostics(new[] - { + result.ExcludingLinterDiagnostics().Should().HaveDiagnostics( + [ ("BCP298", DiagnosticLevel.Error, "This type definition includes itself as required component, which creates a constraint that cannot be fulfilled."), ("BCP062", DiagnosticLevel.Error, "The referenced declaration with name \"anObject\" is not valid."), - }); + ]); } // https://github.com/azure/bicep/issues/12070 @@ -854,11 +854,11 @@ public void Self_array_access_does_not_blow_the_stack() } """); - result.ExcludingLinterDiagnostics().Should().HaveDiagnostics(new[] - { + result.ExcludingLinterDiagnostics().Should().HaveDiagnostics( + [ ("BCP298", DiagnosticLevel.Error, "This type definition includes itself as required component, which creates a constraint that cannot be fulfilled."), ("BCP062", DiagnosticLevel.Error, "The referenced declaration with name \"anObject\" is not valid."), - }); + ]); } [TestMethod] @@ -962,10 +962,10 @@ public void Param_with_resource_derived_type_can_be_loaded() """)); result.Should().NotHaveAnyCompilationBlockingDiagnostics(); - result.Should().HaveDiagnostics(new[] - { + result.Should().HaveDiagnostics( + [ ("BCP037", DiagnosticLevel.Warning, """The property "unknownProperty" is not allowed on objects of type "StorageAccountPropertiesCreateParametersOrStorageAccountProperties". Permissible properties include "accessTier", "allowBlobPublicAccess", "allowCrossTenantReplication", "allowedCopyScope", "allowSharedKeyAccess", "azureFilesIdentityBasedAuthentication", "customDomain", "defaultToOAuthAuthentication", "dnsEndpointType", "encryption", "immutableStorageWithVersioning", "isHnsEnabled", "isLocalUserEnabled", "isNfsV3Enabled", "isSftpEnabled", "keyPolicy", "largeFileSharesState", "minimumTlsVersion", "networkAcls", "publicNetworkAccess", "routingPreference", "sasPolicy", "supportsHttpsTrafficOnly"."""), - }); + ]); } [TestMethod] @@ -1015,12 +1015,12 @@ param saName string """)); result.Should().NotHaveAnyCompilationBlockingDiagnostics(); - result.Should().HaveDiagnostics(new[] - { + result.Should().HaveDiagnostics( + [ ("BCP334", DiagnosticLevel.Warning, "The provided value can have a length as small as 2 and may be too short to assign to a target with a configured minimum length of 3."), ("BCP088", DiagnosticLevel.Warning, """The property "connectionParameterType" expected a value of type "'array' | 'bool' | 'connection' | 'int' | 'oauthSetting' | 'object' | 'secureobject' | 'securestring' | 'string'" but the provided value is of type "'sting'". Did you mean "'string'"?"""), ("BCP036", DiagnosticLevel.Warning, """The property "ipRuleAction" expected a value of type "'Allow'" but the provided value is of type "'Deny'"."""), - }); + ]); } @@ -1057,10 +1057,10 @@ public void Output_with_resource_derived_type_can_be_loaded() """)); result.Should().NotHaveAnyCompilationBlockingDiagnostics(); - result.Should().HaveDiagnostics(new[] - { + result.Should().HaveDiagnostics( + [ ("BCP053", DiagnosticLevel.Warning, """The type "StorageAccountPropertiesCreateParametersOrStorageAccountProperties" does not contain property "unknownProperty". Available properties include "accessTier", "allowBlobPublicAccess", "allowCrossTenantReplication", "allowedCopyScope", "allowSharedKeyAccess", "azureFilesIdentityBasedAuthentication", "blobRestoreStatus", "creationTime", "customDomain", "defaultToOAuthAuthentication", "dnsEndpointType", "encryption", "failoverInProgress", "geoReplicationStats", "immutableStorageWithVersioning", "isHnsEnabled", "isLocalUserEnabled", "isNfsV3Enabled", "isSftpEnabled", "keyCreationTime", "keyPolicy", "largeFileSharesState", "lastGeoFailoverTime", "minimumTlsVersion", "networkAcls", "primaryEndpoints", "primaryLocation", "privateEndpointConnections", "provisioningState", "publicNetworkAccess", "routingPreference", "sasPolicy", "secondaryEndpoints", "secondaryLocation", "statusOfPrimary", "statusOfSecondary", "storageAccountSkuConversionStatus", "supportsHttpsTrafficOnly"."""), - }); + ]); } // https://github.com/azure/bicep/issues/12920 @@ -1195,10 +1195,10 @@ public void Invalid_type_property_access_raises_diagnostic(string accessExpressi type test2 = {{accessExpression}} """); - result.Should().HaveDiagnostics(new[] - { + result.Should().HaveDiagnostics( + [ (expectedErrorCode, DiagnosticLevel.Error, expectedErrorMessage), - }); + ]); } [TestMethod] @@ -1298,10 +1298,10 @@ public void Invalid_type_index_access_raises_diagnostic(string accessExpression, type test2 = {{accessExpression}} """); - result.Should().HaveDiagnostics(new[] - { + result.Should().HaveDiagnostics( + [ (expectedErrorCode, DiagnosticLevel.Error, expectedErrorMessage), - }); + ]); } [TestMethod] @@ -1367,10 +1367,10 @@ public void Invalid_additional_properties_access_raises_diagnostic(string access type test2 = {{accessExpression}} """); - result.Should().HaveDiagnostics(new[] - { + result.Should().HaveDiagnostics( + [ (expectedErrorCode, DiagnosticLevel.Error, expectedErrorMessage), - }); + ]); } [TestMethod] @@ -1473,10 +1473,10 @@ public void Invalid_type_items_access_raises_diagnostic(string accessExpression, type test2 = {{accessExpression}} """); - result.Should().HaveDiagnostics(new[] - { + result.Should().HaveDiagnostics( + [ (expectedErrorCode, DiagnosticLevel.Error, expectedErrorMessage), - }); + ]); } [TestMethod] @@ -1557,10 +1557,10 @@ param subnets resource<'Microsoft.Network/virtualNetworks/subnets@2023-09-01'>[] """)); result.Template.Should().BeNull(); - result.ExcludingLinterDiagnostics().Should().HaveDiagnostics(new[] - { + result.ExcludingLinterDiagnostics().Should().HaveDiagnostics( + [ ("BCP394", DiagnosticLevel.Error, "Resource-derived type expressions must derefence a property within the resource body. Using the entire resource body type is not permitted."), - }); + ]); } [TestMethod] 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..f403a33d695 100644 --- a/src/Bicep.Core.UnitTests/ApiVersion/ApiVersionProviderTests.cs +++ b/src/Bicep.Core.UnitTests/ApiVersion/ApiVersionProviderTests.cs @@ -67,10 +67,10 @@ public void GetResourceTypeNames_SeparateScopes() apiVersionProvider.InjectTypeReferences(ResourceScope.Tenant, FakeResourceTypes.GetFakeResourceTypeReferences("fake.tenant/whatever@2002-01-01")); var rgTypes = apiVersionProvider.GetResourceTypeNames(ResourceScope.ResourceGroup); - rgTypes.Should().Contain(new string[] { "Fake.Network/dnszones", "Fake.Network/publicIPAddresses", "Fake.Network/ddosProtectionPlans" }); + rgTypes.Should().Contain(["Fake.Network/dnszones", "Fake.Network/publicIPAddresses", "Fake.Network/ddosProtectionPlans"]); var subTypes = apiVersionProvider.GetResourceTypeNames(ResourceScope.Subscription); - subTypes.Should().Contain(new String[] { "Fake.Web/publishingCredentials", "Fake.Security/deviceSecurityGroups" }); + subTypes.Should().Contain(["Fake.Web/publishingCredentials", "Fake.Security/deviceSecurityGroups"]); var mgTypes = apiVersionProvider.GetResourceTypeNames(ResourceScope.ManagementGroup); mgTypes.Should().Contain("fake.mg/whatever"); @@ -83,6 +83,6 @@ private ApiVersionProvider CreateDefaultApiVersionProvider(IEnumerable new( new FeatureProvider( IConfigurationManager.GetBuiltInConfiguration()), - resourceTypeReferences ?? Enumerable.Empty()); + resourceTypeReferences ?? []); } } diff --git a/src/Bicep.Core.UnitTests/Assertions/CachedModuleExtensions.cs b/src/Bicep.Core.UnitTests/Assertions/CachedModuleExtensions.cs index aa95429cc90..1493fba4b7b 100644 --- a/src/Bicep.Core.UnitTests/Assertions/CachedModuleExtensions.cs +++ b/src/Bicep.Core.UnitTests/Assertions/CachedModuleExtensions.cs @@ -51,10 +51,10 @@ public AndConstraint NotHaveSource() public AndConstraint BeValid() { - var expectedFiles = new List(new string[] - { + var expectedFiles = new List( + [ "lock", "main.json", "manifest", "metadata", - }); + ]); if (Subject.HasSourceLayer) { diff --git a/src/Bicep.Core.UnitTests/Assertions/JTokenAssertionsExtensions.cs b/src/Bicep.Core.UnitTests/Assertions/JTokenAssertionsExtensions.cs index b131fca3550..86f7df555e1 100644 --- a/src/Bicep.Core.UnitTests/Assertions/JTokenAssertionsExtensions.cs +++ b/src/Bicep.Core.UnitTests/Assertions/JTokenAssertionsExtensions.cs @@ -30,7 +30,7 @@ public static JTokenAssertions Should(this JToken? instance) if (lineLogs.Count() >= truncate) { - lineLogs = lineLogs.Concat(new[] { "...truncated..." }); + lineLogs = lineLogs.Concat(["...truncated..."]); } return string.Join('\n', lineLogs); diff --git a/src/Bicep.Core.UnitTests/Assertions/StringAssertionsExtensions.cs b/src/Bicep.Core.UnitTests/Assertions/StringAssertionsExtensions.cs index 07151035182..a0c541b190c 100644 --- a/src/Bicep.Core.UnitTests/Assertions/StringAssertionsExtensions.cs +++ b/src/Bicep.Core.UnitTests/Assertions/StringAssertionsExtensions.cs @@ -44,7 +44,7 @@ private static string GetDiffMarker(ChangeType type) if (lineLogs.Count() >= truncate) { - lineLogs = lineLogs.Concat(new[] { "...truncated..." }); + lineLogs = lineLogs.Concat(["...truncated..."]); } if (!diff.HasDifferences) diff --git a/src/Bicep.Core.UnitTests/Configuration/BicepConfigSchemaTests.cs b/src/Bicep.Core.UnitTests/Configuration/BicepConfigSchemaTests.cs index f0a0b31fee8..b243c8027d0 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() @@ -259,7 +259,7 @@ public void RuleConfigs_RuleDescriptionsShouldBeConsistent() string description = new Regex("^(.+) See https://.+").Match(descriptionWithLink)?.Groups[1].Value ?? ""; description.Should().MatchRegex("^[A-Z]", "all rule descriptions should start with a capital letter"); description.Should().EndWith(".", "all rule descriptions should end with a period"); - description.Should().NotContainAny(new[] { "don't", "do not" }, StringComparison.InvariantCultureIgnoreCase, "Use \"Should\" type of language generally (less impolite)"); + description.Should().NotContainAny(["don't", "do not"], StringComparison.InvariantCultureIgnoreCase, "Use \"Should\" type of language generally (less impolite)"); description.Should().NotContain("\"", "use single quotes instead of double quotes in rule descriptions"); } } @@ -339,7 +339,7 @@ public void ExperimentalFeatures_ShouldHaveDescription() description.Should().MatchRegex($"^[A-Z]", "all feature descriptions should start with a capital letter: {featureName}"); description.Should().NotContain($"\"", "use single quotes instead of double quotes in feature descriptions: {featureName}"); - description.Should().NotContainAny(new[] { "don't", "do not" }, "Use \"Should\" type of language generally (less impolite)"); + description.Should().NotContainAny(["don't", "do not"], "Use \"Should\" type of language generally (less impolite)"); } } diff --git a/src/Bicep.Core.UnitTests/Configuration/RootConfigurationTests.cs b/src/Bicep.Core.UnitTests/Configuration/RootConfigurationTests.cs index 9e60ad343c9..2ffbb8d6571 100644 --- a/src/Bicep.Core.UnitTests/Configuration/RootConfigurationTests.cs +++ b/src/Bicep.Core.UnitTests/Configuration/RootConfigurationTests.cs @@ -34,14 +34,14 @@ private static IEnumerable GetTestData() { var homeDirectory = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile); - 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" }, - }; + return + [ + ["~", homeDirectory], + ["~/", $"{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..32a85833611 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?)) @@ -170,7 +170,7 @@ private static object CreateMockParameter(ParameterInfo parameter, int index) if (parameter.ParameterType == typeof(ObjectSyntax)) { - return TestSyntaxFactory.CreateObject(Array.Empty()); + return TestSyntaxFactory.CreateObject([]); } if (parameter.ParameterType == typeof(SyntaxBase)) @@ -305,7 +305,7 @@ private static void ExpectDiagnosticWithFixedText(string text, string expectedTe name: 'D1' } - + location: name:// comment }" diff --git a/src/Bicep.Core.UnitTests/Diagnostics/LinterRuleTests/ArtifactsParametersRuleTests.cs b/src/Bicep.Core.UnitTests/Diagnostics/LinterRuleTests/ArtifactsParametersRuleTests.cs index d8ebc678786..7c81abfe9c3 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[] - { - } + [] ); } @@ -107,9 +99,9 @@ param _artifactsLocSasToken string public void ArmTtk_MissingDefaults_Both_Pass() { /* TTK result: - [-] artifacts parameter (24 ms) - The _artifactsLocation parameter in "mainTemplate.json" must have a defaultValue in the main template - The _artifactsLocationSasToken in "mainTemplate.json" has an incorrect defaultValue, must be an empty string + [-] artifacts parameter (24 ms) + The _artifactsLocation parameter in "mainTemplate.json" must have a defaultValue in the main template + The _artifactsLocationSasToken in "mainTemplate.json" has an incorrect defaultValue, must be an empty string */ CompileAndTest( @" @@ -118,37 +110,31 @@ 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 - } + [] ); } [TestMethod] public void ArmTtk_MissingDefaults_ArtifactsLocation_EmptyString_Fail() { - /* TTK result: - [-] artifacts parameter (2 ms) - The _artifactsLocation parameter in "mainTemplate.json" must have a defaultValue in the main template + /* TTK result: + [-] artifacts parameter (2 ms) + The _artifactsLocation parameter in "mainTemplate.json" must have a defaultValue in the main template */ CompileAndTest( @" - @secure() + @secure() param _artifactsLocation string = '' @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 - } + [] ); } @@ -175,21 +156,20 @@ public void ArmTtk_MissingDefaults_SasToken_Pass() public void ArmTtk_MissingSas_Fail() { /* TTK result: - [-] artifacts parameter (3 ms) - Template "mainTemplate.json" is missing _artifactsLocationSasToken parameter - The _artifactsLocationSasToken in "mainTemplate.json" has an incorrect defaultValue, must be an empty string + [-] artifacts parameter (3 ms) + Template "mainTemplate.json" is missing _artifactsLocationSasToken parameter + The _artifactsLocationSasToken in "mainTemplate.json" has an incorrect defaultValue, must be an empty string */ CompileAndTest( @" 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." - } + ] ); } @@ -214,14 +193,14 @@ param _artifactsLocationSasToken string public void ArmTtk_WrongDefaults_Fail() { /* TTK result: - [-] artifacts parameter (3 ms) - ENV:SAMPLE_NAME is empty - using placeholder for manual verification: 100-blank-template - The _artifactsLocation in ""mainTemplate.json"" has an incorrect defaultValue, found: http://myweb.com/ - Must be one of: https://raw.githubusercontent.com/Azure/azure-quickstart-templates/master/100-blank-template/ or deployment().properties.templateLink.uri + [-] artifacts parameter (3 ms) + ENV:SAMPLE_NAME is empty - using placeholder for manual verification: 100-blank-template + The _artifactsLocation in ""mainTemplate.json"" has an incorrect defaultValue, found: http://myweb.com/ + Must be one of: https://raw.githubusercontent.com/Azure/azure-quickstart-templates/master/100-blank-template/ or deployment().properties.templateLink.uri */ - /* - [-] Secure String Parameters Cannot Have Default (3 ms) + /* + [-] Secure String Parameters Cannot Have Default (3 ms) Parameter _artifactsLocationSasToken is a SecureString and must not have a default value unless it is an expression that contains the newGuid() function. */ CompileAndTest( @@ -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); } @@ -272,23 +247,22 @@ public void WrongDefaults3_Fail() public void ArmTtk_WrongType_Fail() { /* TTK result: - [-] artifacts parameter (2 ms) + [-] artifacts parameter (2 ms) The _artifactsLocation in "mainTemplate.json" parameter must be a 'string' type in the parameter declaration "array" - The _artifactsLocationSasToken in "mainTemplate.json" parameter must be of type 'securestring'. - The _artifactsLocation parameter in "mainTemplate.json" must have a defaultValue in the main template - The _artifactsLocationSasToken in "mainTemplate.json" has an incorrect defaultValue, must be an empty string + The _artifactsLocationSasToken in "mainTemplate.json" parameter must be of type 'securestring'. + The _artifactsLocation parameter in "mainTemplate.json" must have a defaultValue in the main template + The _artifactsLocationSasToken in "mainTemplate.json" has an incorrect defaultValue, must be an empty string */ CompileAndTest( @" 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", - } + ] ); } @@ -296,21 +270,20 @@ param _artifactsLocationSasToken int //wrong type public void ArmTtk_WrongType_NotSecure_Fail() { /* TTK result: - [-] artifacts parameter (2 ms) + [-] artifacts parameter (2 ms) The _artifactsLocation in "mainTemplate.json" parameter must be a 'string' type in the parameter declaration "array" - The _artifactsLocationSasToken in "mainTemplate.json" parameter must be of type 'securestring'. - The _artifactsLocation parameter in "mainTemplate.json" must have a defaultValue in the main template - The _artifactsLocationSasToken in "mainTemplate.json" has an incorrect defaultValue, must be an empty string + The _artifactsLocationSasToken in "mainTemplate.json" parameter must be of type 'securestring'. + The _artifactsLocation parameter in "mainTemplate.json" must have a defaultValue in the main template + The _artifactsLocationSasToken in "mainTemplate.json" has an incorrect defaultValue, must be an empty string */ CompileAndTest( @" 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/ExplicitValuesForLocationParamsRuleTests.cs b/src/Bicep.Core.UnitTests/Diagnostics/LinterRuleTests/ExplicitValuesForLocationParamsRuleTests.cs index a94e65c2872..980aab41cf3 100644 --- a/src/Bicep.Core.UnitTests/Diagnostics/LinterRuleTests/ExplicitValuesForLocationParamsRuleTests.cs +++ b/src/Bicep.Core.UnitTests/Diagnostics/LinterRuleTests/ExplicitValuesForLocationParamsRuleTests.cs @@ -84,10 +84,10 @@ param location string output o string = location ") ); - result.Diagnostics.Should().HaveDiagnostics(new[] - { + result.Diagnostics.Should().HaveDiagnostics( + [ ("BCP035", DiagnosticLevel.Error, "The specified \"object\" declaration is missing the following required properties: \"location\"."), - }); + ]); } [TestMethod] @@ -165,10 +165,10 @@ param location string output o string = p1 ") ); - result.Diagnostics.Should().HaveDiagnostics(new[] - { + result.Diagnostics.Should().HaveDiagnostics( + [ (ExplicitValuesForLocationParamsRule.Code, DiagnosticLevel.Warning, "Parameter 'p1' of module 'm3' isn't assigned an explicit value, and its default value may not give the intended behavior for a location-related parameter. You should assign an explicit value to the parameter."), - }); + ]); } [TestMethod] @@ -203,13 +203,13 @@ param location string output o string = p1 ") ); - result.Diagnostics.Should().HaveDiagnostics(new[] - { + result.Diagnostics.Should().HaveDiagnostics( + [ (ExplicitValuesForLocationParamsRule.Code, DiagnosticLevel.Warning, "Parameter 'p1' of module 'm1' isn't assigned an explicit value, and its default value may not give the intended behavior for a location-related parameter. You should assign an explicit value to the parameter."), (ExplicitValuesForLocationParamsRule.Code, DiagnosticLevel.Warning, "Parameter 'p2' of module 'm1' isn't assigned an explicit value, and its default value may not give the intended behavior for a location-related parameter. You should assign an explicit value to the parameter."), (ExplicitValuesForLocationParamsRule.Code, DiagnosticLevel.Warning, "Parameter 'p1' of module 'm2' isn't assigned an explicit value, and its default value may not give the intended behavior for a location-related parameter. You should assign an explicit value to the parameter."), (ExplicitValuesForLocationParamsRule.Code, DiagnosticLevel.Warning, "Parameter 'p2' of module 'm2' isn't assigned an explicit value, and its default value may not give the intended behavior for a location-related parameter. You should assign an explicit value to the parameter."), - }); + ]); } [TestMethod] @@ -235,11 +235,11 @@ param location string output o string = '${p1}${p2}' ") ); - result.Diagnostics.Should().HaveDiagnostics(new[] - { + result.Diagnostics.Should().HaveDiagnostics( + [ ("BCP104", DiagnosticLevel.Error, "The referenced module has errors."), (ExplicitValuesForLocationParamsRule.Code, DiagnosticLevel.Warning, "Parameter 'p1' of module 'm3' isn't assigned an explicit value, and its default value may not give the intended behavior for a location-related parameter. You should assign an explicit value to the parameter."), - (ExplicitValuesForLocationParamsRule.Code, DiagnosticLevel.Warning, "Parameter 'p2' of module 'm3' isn't assigned an explicit value, and its default value may not give the intended behavior for a location-related parameter. You should assign an explicit value to the parameter."),}); + (ExplicitValuesForLocationParamsRule.Code, DiagnosticLevel.Warning, "Parameter 'p2' of module 'm3' isn't assigned an explicit value, and its default value may not give the intended behavior for a location-related parameter. You should assign an explicit value to the parameter."),]); } [TestMethod] @@ -290,14 +290,14 @@ param pWithNoDefault string ") ); - result.Diagnostics.Should().HaveDiagnostics(new[] - { + result.Diagnostics.Should().HaveDiagnostics( + [ ("BCP035", DiagnosticLevel.Error, "The specified \"object\" declaration is missing the following required properties: \"pWithNoDefault\"."), (ExplicitValuesForLocationParamsRule.Code, DiagnosticLevel.Warning, "Parameter 'p1' of module 'm' isn't assigned an explicit value, and its default value may not give the intended behavior for a location-related parameter. You should assign an explicit value to the parameter."), (ExplicitValuesForLocationParamsRule.Code, DiagnosticLevel.Warning, "Parameter 'p2' of module 'm' isn't assigned an explicit value, and its default value may not give the intended behavior for a location-related parameter. You should assign an explicit value to the parameter."), (ExplicitValuesForLocationParamsRule.Code, DiagnosticLevel.Warning, "Parameter 'p3' of module 'm' isn't assigned an explicit value, and its default value may not give the intended behavior for a location-related parameter. You should assign an explicit value to the parameter."), (ExplicitValuesForLocationParamsRule.Code, DiagnosticLevel.Warning, "Parameter 'p4' of module 'm' isn't assigned an explicit value, and its default value may not give the intended behavior for a location-related parameter. You should assign an explicit value to the parameter."), - }); + ]); } [TestMethod] @@ -324,11 +324,11 @@ param location string output o string = myParam ") ); - result.Diagnostics.Should().HaveDiagnostics(new[] - { + result.Diagnostics.Should().HaveDiagnostics( + [ (ExplicitValuesForLocationParamsRule.Code, DiagnosticLevel.Warning, "Parameter 'myParam' of module 'm1' isn't assigned an explicit value, and its default value may not give the intended behavior for a location-related parameter. You should assign an explicit value to the parameter."), - }); + ]); } [TestMethod] @@ -353,10 +353,10 @@ param LOCATION string output o string = whoops // error ") ); - result.Diagnostics.Should().HaveDiagnostics(new[] - { + result.Diagnostics.Should().HaveDiagnostics( + [ ("BCP104", DiagnosticLevel.Error, "The referenced module has errors.") - }); + ]); } [TestMethod] @@ -374,10 +374,10 @@ public void ForLoop3_Module() ") ); - result.Diagnostics.Should().HaveDiagnostics(new[] - { + result.Diagnostics.Should().HaveDiagnostics( + [ (ExplicitValuesForLocationParamsRule.Code, DiagnosticLevel.Warning, "Parameter 'location' of module 'm2' isn't assigned an explicit value, and its default value may not give the intended behavior for a location-related parameter. You should assign an explicit value to the parameter."), - }); + ]); } [TestMethod] @@ -397,10 +397,10 @@ param deploy bool ") ); - result.Diagnostics.Should().HaveDiagnostics(new[] - { + result.Diagnostics.Should().HaveDiagnostics( + [ (ExplicitValuesForLocationParamsRule.Code, DiagnosticLevel.Warning, "Parameter 'location' of module 'm3' isn't assigned an explicit value, and its default value may not give the intended behavior for a location-related parameter. You should assign an explicit value to the parameter."), - }); + ]); } [TestMethod] diff --git a/src/Bicep.Core.UnitTests/Diagnostics/LinterRuleTests/NoHardcodedLocationRuleTests.cs b/src/Bicep.Core.UnitTests/Diagnostics/LinterRuleTests/NoHardcodedLocationRuleTests.cs index 84fbbd4f3b8..39b53858ec9 100644 --- a/src/Bicep.Core.UnitTests/Diagnostics/LinterRuleTests/NoHardcodedLocationRuleTests.cs +++ b/src/Bicep.Core.UnitTests/Diagnostics/LinterRuleTests/NoHardcodedLocationRuleTests.cs @@ -148,10 +148,10 @@ public void If_ResLocationIs_StringLiteral_ShouldFail_WithFixes() } "); - result.Diagnostics.Should().HaveDiagnostics(new[] - { + result.Diagnostics.Should().HaveDiagnostics( + [ (NoHardcodedLocationRule.Code, DiagnosticLevel.Warning, "A resource location should not use a hard-coded string or variable value. Please use a parameter value, an expression, or the string 'global'. Found: 'westus'") - }); + ]); } [TestMethod] @@ -170,8 +170,8 @@ public void If_ResLocationIs_VariableDefinedAsLiteral_ShouldFail_WithFixToChange } "); - result.Diagnostics.Should().HaveFixableDiagnostics(new[] - { + result.Diagnostics.Should().HaveFixableDiagnostics( + [ ( NoHardcodedLocationRule.Code, DiagnosticLevel.Warning, @@ -179,7 +179,7 @@ public void If_ResLocationIs_VariableDefinedAsLiteral_ShouldFail_WithFixToChange "Change variable 'location' into a parameter instead", "param location string = 'westus'" ) - }); + ]); } [TestMethod] @@ -235,8 +235,8 @@ public void If_ResLocationIs_VariableDefinedAsLiteral_ShouldFail_WithFixToChange } "); - result.Diagnostics.Should().HaveFixableDiagnostics(new[] - { + result.Diagnostics.Should().HaveFixableDiagnostics( + [ ( NoHardcodedLocationRule.Code, DiagnosticLevel.Warning, @@ -251,7 +251,7 @@ public void If_ResLocationIs_VariableDefinedAsLiteral_ShouldFail_WithFixToChange "Change variable 'location2' into a parameter instead", "param location2 string = 'westus'" ) - }); + ]); } [TestMethod] @@ -279,10 +279,10 @@ public void If_ResLocationIs_VariableDefinedAsLiteral_Used2Times_ShouldFailJustO } "); - result.Diagnostics.Should().HaveDiagnostics(new[] - { + result.Diagnostics.Should().HaveDiagnostics( + [ (NoHardcodedLocationRule.Code, DiagnosticLevel.Warning, "A resource location should not use a hard-coded string or variable value. Change variable 'location' into a parameter instead.") - }); + ]); } [TestMethod] @@ -331,10 +331,10 @@ public void If_ResLocationIs_VariableDefinedAsLiteral_UsedInResourcesAndModules_ ") ); - result.Diagnostics.Should().HaveDiagnostics(new[] - { + result.Diagnostics.Should().HaveDiagnostics( + [ (NoHardcodedLocationRule.Code, DiagnosticLevel.Warning, "A resource location should not use a hard-coded string or variable value. Change variable 'location' into a parameter instead.") - }); + ]); } [TestMethod] @@ -354,10 +354,10 @@ public void If_ResLocationIs_IndirectVariableDefinedAsLiteral_ShouldFail() } "); - result.Diagnostics.Should().HaveDiagnostics(new[] - { + result.Diagnostics.Should().HaveDiagnostics( + [ (NoHardcodedLocationRule.Code, DiagnosticLevel.Warning, "A resource location should not use a hard-coded string or variable value. Change variable 'location' into a parameter instead.") - }); + ]); } [TestMethod] @@ -386,10 +386,10 @@ public void If_ResLocationIs_IndirectVariableDefinedAsLiteral_UsedIn2Places_Shou } "); - result.Diagnostics.Should().HaveDiagnostics(new[] - { + result.Diagnostics.Should().HaveDiagnostics( + [ (NoHardcodedLocationRule.Code, DiagnosticLevel.Warning, "A resource location should not use a hard-coded string or variable value. Change variable 'location' into a parameter instead.") - }); + ]); } [TestMethod] @@ -418,10 +418,10 @@ public void If_ResLocationIs_IndirectVariableDefinedAsLiteral_UsedIn2PlacesDiffe } "); - result.Diagnostics.Should().HaveDiagnostics(new[] - { + result.Diagnostics.Should().HaveDiagnostics( + [ (NoHardcodedLocationRule.Code, DiagnosticLevel.Warning, "A resource location should not use a hard-coded string or variable value. Change variable 'location' into a parameter instead."), - }); + ]); } [TestMethod] @@ -480,10 +480,10 @@ public void If_ResLocationIs_TwiceIndirectedVariableDefinedAsLiteral_ShouldFail_ } "); - result.Diagnostics.Should().HaveDiagnostics(new[] - { + result.Diagnostics.Should().HaveDiagnostics( + [ (NoHardcodedLocationRule.Code, DiagnosticLevel.Warning, "A resource location should not use a hard-coded string or variable value. Change variable 'location' into a parameter instead.") - }); + ]); } [TestMethod] @@ -604,10 +604,10 @@ public void ResLoc_If_Resource_HasLocation_AsIndirectStringLiteral_ShouldFail() }" ); - result.Diagnostics.Should().HaveDiagnostics(new[] - { + result.Diagnostics.Should().HaveDiagnostics( + [ (NoHardcodedLocationRule.Code, DiagnosticLevel.Warning, "A resource location should not use a hard-coded string or variable value. Change variable 'v1' into a parameter instead.") - }); + ]); } @@ -630,10 +630,10 @@ public void ForLoop2_Module() ") ); - result.Diagnostics.Should().HaveDiagnostics(new[] - { + result.Diagnostics.Should().HaveDiagnostics( + [ (NoHardcodedLocationRule.Code, DiagnosticLevel.Warning, "Parameter 'location' may be used as a resource location in the module and should not be assigned a hard-coded string or variable value. Please use a parameter value, an expression, or the string 'global'. Found: 'westus'") - }); + ]); } [TestMethod] @@ -655,10 +655,10 @@ public void ResLoc_If_Module_HasLocationProperty_WithDefault_AndStringLiteralPas ") ); - result.Diagnostics.Should().HaveDiagnostics(new[] - { + result.Diagnostics.Should().HaveDiagnostics( + [ (NoHardcodedLocationRule.Code, DiagnosticLevel.Warning, "Parameter 'location' may be used as a resource location in the module and should not be assigned a hard-coded string or variable value. Please use a parameter value, an expression, or the string 'global'. Found: 'westus'") - }); + ]); } } diff --git a/src/Bicep.Core.UnitTests/Diagnostics/LinterRuleTests/NoLocationExprOutsideParamsRuleTests.cs b/src/Bicep.Core.UnitTests/Diagnostics/LinterRuleTests/NoLocationExprOutsideParamsRuleTests.cs index ef333acd693..9a6c43b9543 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) @@ -50,9 +50,9 @@ protected void ExpectFailWithFix(string bicepText, string expectedMessage, Expec diagnostics => { diagnostics.Should().HaveCount(1); - diagnostics.Should().HaveFixableDiagnostics(new[] { + diagnostics.Should().HaveFixableDiagnostics([ (NoLocationExprOutsideParamsRule.Code, DiagnosticLevel.Warning, expectedMessage, expectedFix.Description, expectedFix.ReplacementText) - }); ; + ]); ; } ); } @@ -219,10 +219,10 @@ public void If_ResLocIs_ResourceGroupLocation_ShouldFail() " ); - result.Diagnostics.Should().HaveDiagnostics(new[] - { + result.Diagnostics.Should().HaveDiagnostics( + [ (NoLocationExprOutsideParamsRule.Code, DiagnosticLevel.Warning, "Use a parameter here instead of 'resourceGroup().location'. 'resourceGroup().location' and 'deployment().location' should only be used as a default value for parameters.") - }); + ]); } [TestMethod] @@ -239,10 +239,10 @@ public void ForLoop1_Resource() }] " ); - result.Diagnostics.Should().HaveDiagnostics(new[] - { + result.Diagnostics.Should().HaveDiagnostics( + [ (NoLocationExprOutsideParamsRule.Code, DiagnosticLevel.Warning, "Use a parameter here instead of 'resourceGroup().location'. 'resourceGroup().location' and 'deployment().location' should only be used as a default value for parameters.") - }); + ]); } [TestMethod] diff --git a/src/Bicep.Core.UnitTests/Diagnostics/LinterRuleTests/NoUnnecessaryDependsOnRuleTests.cs b/src/Bicep.Core.UnitTests/Diagnostics/LinterRuleTests/NoUnnecessaryDependsOnRuleTests.cs index 588562bab8a..5f4c3f86bd6 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'." - } + ] ); } @@ -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..810144e6fa9 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(); @@ -883,7 +883,7 @@ public void Invariants(TestData data) var mostRecent = allVersions.OrderBy(v => v.Date).Last(); if (mostRecent.IsPreview && DateIsOld(mostRecent.Date, data.Today, data.MaxAgeInDays)) { - allowedVersions.Where(v => v.IsPreview).Select(v => v.ToString()).Should().BeEquivalentTo(new string[] { mostRecent.ToString() }, "if the most recent version is a preview version that’s > 2 years old, that one preview version is allowed"); + allowedVersions.Where(v => v.IsPreview).Select(v => v.ToString()).Should().BeEquivalentTo([mostRecent.ToString()], "if the most recent version is a preview version that’s > 2 years old, that one preview version is allowed"); } // If there are no stable versions, all recent preview versions are allowed @@ -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", - }, + ], 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", - }, + ], 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", - }, + ], 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", - }, + ], 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/Emit/InlineDependencyVisitorTests.cs b/src/Bicep.Core.UnitTests/Emit/InlineDependencyVisitorTests.cs index cfebb7b7baa..f24fcb4d206 100644 --- a/src/Bicep.Core.UnitTests/Emit/InlineDependencyVisitorTests.cs +++ b/src/Bicep.Core.UnitTests/Emit/InlineDependencyVisitorTests.cs @@ -30,13 +30,13 @@ public void VisitorShouldCalculateInliningInBulk() var inlineVariables = InlineDependencyVisitor.GetVariablesToInline(compilation.GetEntrypointSemanticModel()); - inlineVariables.Should().Contain(new[] - { + inlineVariables.Should().Contain( + [ GetVariableSymbolByName(compilation, "keys"), GetVariableSymbolByName(compilation, "indirection"), GetVariableSymbolByName(compilation, "runtimeLoop"), GetVariableSymbolByName(compilation, "runtimeLoop2") - }); + ]); } [DataRow("things")] 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..c2be230acea 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(); } @@ -330,7 +330,7 @@ public void ValidDisableNextLineDiagnosticsDirective_WithTrailingWhiteSpaceFollo public void ValidDisableNextLineDiagnosticsDirective_WithinResourceAndWithTrailingWhiteSpace_ShouldLexCorrectly() { string text = @"resource vm 'Microsoft.Compute/virtualMachines@2020-12-01' = { -#disable-next-line BCP226 +#disable-next-line BCP226 properties: vmProperties }"; var diagnosticWriter = ToListDiagnosticWriter.Create(); diff --git a/src/Bicep.Core.UnitTests/Registry/ArtifactDispatcherTests.cs b/src/Bicep.Core.UnitTests/Registry/ArtifactDispatcherTests.cs index 403cdde44c2..0481b04f8b5 100644 --- a/src/Bicep.Core.UnitTests/Registry/ArtifactDispatcherTests.cs +++ b/src/Bicep.Core.UnitTests/Registry/ArtifactDispatcherTests.cs @@ -150,7 +150,7 @@ public async Task MockRegistries_ModuleLifecycle() @uri.Should().Be(new Uri("untitled://validRef3")); entryPointBuilder3!.Should().BeNull(); - (await dispatcher.RestoreArtifacts(new[] { validRef, validRef3 }, false)).Should().BeTrue(); + (await dispatcher.RestoreArtifacts([validRef, validRef3], false)).Should().BeTrue(); dispatcher.GetArtifactRestoreStatus(validRef3, out var goodAvailabilityBuilder3AfterRestore).Should().Be(ArtifactRestoreStatus.Failed); goodAvailabilityBuilder3AfterRestore!.Should().HaveCode("RegFail"); @@ -184,7 +184,7 @@ public async Task GetModuleRestoreStatus_ConfigurationChanges_ReturnsCachedStatu var dispatcher = CreateDispatcher(configManagerMock.Object, registryMock.Object); var configuration = BicepTestConstants.CreateMockConfiguration(); - await dispatcher.RestoreArtifacts(new[] { badReference }, false); + await dispatcher.RestoreArtifacts([badReference], false); // Act. var status = dispatcher.GetArtifactRestoreStatus(badReference, out _); @@ -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/OciModuleRegistryTests.cs b/src/Bicep.Core.UnitTests/Registry/OciModuleRegistryTests.cs index 21fb3c7b8a8..4db793a4fc3 100644 --- a/src/Bicep.Core.UnitTests/Registry/OciModuleRegistryTests.cs +++ b/src/Bicep.Core.UnitTests/Registry/OciModuleRegistryTests.cs @@ -698,7 +698,7 @@ public async Task RestoreModuleWithSource_ShouldRestoreSourceToDisk(bool publish private async Task RestoreModule(OciArtifactRegistry ociRegistry, OciArtifactReference reference) { - var (_, failureBuilder) = (await ociRegistry.RestoreArtifacts(new[] { reference })).SingleOrDefault(); + var (_, failureBuilder) = (await ociRegistry.RestoreArtifacts([reference])).SingleOrDefault(); if (failureBuilder is { }) { var builder = new DiagnosticBuilderInternal(new Core.Parsing.TextSpan()); diff --git a/src/Bicep.Core.UnitTests/Registry/TokenCredentialFactoryTests.cs b/src/Bicep.Core.UnitTests/Registry/TokenCredentialFactoryTests.cs index bb5fc13c79b..1c15e95c0b9 100644 --- a/src/Bicep.Core.UnitTests/Registry/TokenCredentialFactoryTests.cs +++ b/src/Bicep.Core.UnitTests/Registry/TokenCredentialFactoryTests.cs @@ -41,14 +41,14 @@ 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] public void ShouldCreateExpectedSingleItemChain() { var f = new TokenCredentialFactory(); - var credential = f.CreateChain(new[] { CredentialType.VisualStudioCode }, null, exampleAuthorityUri); + var credential = f.CreateChain([CredentialType.VisualStudioCode], null, exampleAuthorityUri); AssertCredentialTypes(credential, typeof(VisualStudioCodeCredential)); } @@ -56,7 +56,7 @@ public void ShouldCreateExpectedSingleItemChain() public void ShouldCreateExpectedMultiItemChain() { var f = new TokenCredentialFactory(); - var credential = f.CreateChain(new[] { CredentialType.AzureCLI, CredentialType.ManagedIdentity, CredentialType.VisualStudio }, null, exampleAuthorityUri); + var credential = f.CreateChain([CredentialType.AzureCLI, CredentialType.ManagedIdentity, CredentialType.VisualStudio], null, exampleAuthorityUri); AssertCredentialTypes(credential, typeof(AzureCliCredential), typeof(ManagedIdentityCredential), typeof(VisualStudioCredential)); } @@ -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/Rewriters/TypeCasingFixerRewriterTests.cs b/src/Bicep.Core.UnitTests/Rewriters/TypeCasingFixerRewriterTests.cs index 603cf4ebb05..1ec87cb0d6e 100644 --- a/src/Bicep.Core.UnitTests/Rewriters/TypeCasingFixerRewriterTests.cs +++ b/src/Bicep.Core.UnitTests/Rewriters/TypeCasingFixerRewriterTests.cs @@ -112,9 +112,9 @@ public void Nested_casing_issues_take_multiple_passes_to_correct() """; var typeDefinition = TestTypeHelper.CreateCustomResourceType("My.Rp/resA", "2020-01-01", TypeSymbolValidationFlags.WarnOnTypeMismatch, - new TypeProperty("lowercaseobj", new ObjectType("lowercaseobj", TypeSymbolValidationFlags.Default, new[] { + new TypeProperty("lowercaseobj", new ObjectType("lowercaseobj", TypeSymbolValidationFlags.Default, [ new TypeProperty("lowercasestr", LanguageConstants.String) - }, null))); + ], null))); var typeLoader = TestTypeHelper.CreateResourceTypeLoaderWithTypes(typeDefinition.AsEnumerable()); var (_, _, compilation) = CompilationHelper.Compile(typeLoader, ("main.bicep", bicepFile)); diff --git a/src/Bicep.Core.UnitTests/Semantics/ArmTemplateSemanticModelTests.cs b/src/Bicep.Core.UnitTests/Semantics/ArmTemplateSemanticModelTests.cs index 09ae4fa12a0..e90d3d32301 100644 --- a/src/Bicep.Core.UnitTests/Semantics/ArmTemplateSemanticModelTests.cs +++ b/src/Bicep.Core.UnitTests/Semantics/ArmTemplateSemanticModelTests.cs @@ -362,7 +362,7 @@ public void Model_creates_union_null_types_from_nullable_modifier() var members = parameterType.As().Members; members.Should().HaveCount(2); - members.Should().Contain(new[] { LanguageConstants.Null, LanguageConstants.LooseString }); + members.Should().Contain([LanguageConstants.Null, LanguageConstants.LooseString]); } [TestMethod] @@ -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/AuxiliaryFileCacheTests.cs b/src/Bicep.Core.UnitTests/Semantics/AuxiliaryFileCacheTests.cs index 24419523bd9..b8900643afe 100644 --- a/src/Bicep.Core.UnitTests/Semantics/AuxiliaryFileCacheTests.cs +++ b/src/Bicep.Core.UnitTests/Semantics/AuxiliaryFileCacheTests.cs @@ -79,10 +79,10 @@ public void ClearEntries_should_clear_cached_results() sut.GetEntries().Should().BeEquivalentTo(new[] { fileUri }); // clear a different file, verify the original is still cached - sut.ClearEntries(new[] { new Uri("file:///different/file.txt") }); + sut.ClearEntries([new Uri("file:///different/file.txt")]); sut.GetEntries().Should().BeEquivalentTo(new[] { fileUri }); - sut.ClearEntries(new[] { fileUri }); + sut.ClearEntries([fileUri]); sut.GetEntries().Should().BeEmpty(); } @@ -101,10 +101,10 @@ public void PruneInactiveEntries_should_clear_inactive_entries() sut.Read(fileUri).Unwrap(); sut.GetEntries().Should().BeEquivalentTo(new[] { fileUri }); - sut.PruneInactiveEntries(new[] { fileUri }); + sut.PruneInactiveEntries([fileUri]); sut.GetEntries().Should().BeEquivalentTo(new[] { fileUri }); - sut.PruneInactiveEntries(new[] { new Uri("file:///different/file.txt") }); + sut.PruneInactiveEntries([new Uri("file:///different/file.txt")]); sut.GetEntries().Should().BeEmpty(); } } 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..123500246c7 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,88 +175,77 @@ 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 yield return data( - new string[] - { + [ RootC("deployment/a.txt"), RootC("Deployment/b&.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"), - }); + ]); #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/TestTests/PrintHelperTests.cs b/src/Bicep.Core.UnitTests/TestTests/PrintHelperTests.cs index 0822ebe37cc..ae20dc9f125 100644 --- a/src/Bicep.Core.UnitTests/TestTests/PrintHelperTests.cs +++ b/src/Bicep.Core.UnitTests/TestTests/PrintHelperTests.cs @@ -24,15 +24,15 @@ public void PrintHelper_should_add_annotations() } ").Compilation; - var output = PrintHelper.PrintWithAnnotations(compilation.GetEntrypointSemanticModel().SourceFile, new[] { + var output = PrintHelper.PrintWithAnnotations(compilation.GetEntrypointSemanticModel().SourceFile, [ new PrintHelper.Annotation(new TextSpan(26, 18), "what is this!?"), // 0 length span should produce a '^' rather than a '~' new PrintHelper.Annotation(new TextSpan(80, 0), "oh, hi!"), new PrintHelper.Annotation(new TextSpan(129, 14), "i can't believe you've done this"), - }, 1, true); + ], 1, true); output.Should().Be( -@"1| +@"1| 2| resource domainServices 'Microsoft.MadeUpRp/madeUpType@2017-06-01' = { ~~~~~~~~~~~~~~~~~~ what is this!? 3| name: 'hello' @@ -63,7 +63,7 @@ public void PrintHelper_only_includes_nearby_context() about ''' -// +// // give me a cursor here please! // @@ -83,12 +83,12 @@ public void PrintHelper_only_includes_nearby_context() ''' ").Compilation; - var output = PrintHelper.PrintWithAnnotations(compilation.GetEntrypointSemanticModel().SourceFile, new[] { + var output = PrintHelper.PrintWithAnnotations(compilation.GetEntrypointSemanticModel().SourceFile, [ new PrintHelper.Annotation(new TextSpan(108, 4), "here's your cursor!"), - }, 1, true); + ], 1, true); output.Should().Be( -@"16| // +@"16| // 17| // give me a cursor here please! ~~~~ here's your cursor! 18| // 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..7e2959eb346 100644 --- a/src/Bicep.Core.UnitTests/TypeSystem/Az/AzResourceTypeProviderTests.cs +++ b/src/Bicep.Core.UnitTests/TypeSystem/Az/AzResourceTypeProviderTests.cs @@ -159,9 +159,9 @@ public void AzResourceTypeProvider_should_warn_for_missing_resource_types() name: 'missingResource' } "); - compilation.Should().HaveDiagnostics(new[] { + compilation.Should().HaveDiagnostics([ ("BCP081", DiagnosticLevel.Warning, "Resource type \"Mock.Rp/madeUpResourceType@2020-01-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] @@ -179,18 +179,18 @@ Compilation createCompilation(string program) => Services } } "); - compilation.Should().HaveDiagnostics(new[] { + compilation.Should().HaveDiagnostics([ ("BCP035", DiagnosticLevel.Error, "The specified \"resource\" declaration is missing the following required properties: \"name\".") - }); + ]); compilation = createCompilation(@" resource missingRequired 'Test.Rp/readWriteTests@2020-01-01' = { name: 'missingRequired' } "); - compilation.Should().HaveDiagnostics(new[] { + compilation.Should().HaveDiagnostics([ ("BCP035", DiagnosticLevel.Warning, "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.") - }); + ]); // Top-level properties that aren't part of the type definition - should be an error compilation = createCompilation(@" @@ -202,9 +202,9 @@ Compilation createCompilation(string program) => Services madeUpProperty: true } "); - compilation.Should().HaveDiagnostics(new[] { + compilation.Should().HaveDiagnostics([ ("BCP037", DiagnosticLevel.Error, "The property \"madeUpProperty\" is not allowed on objects of type \"Test.Rp/readWriteTests@2020-01-01\". Permissible properties include \"dependsOn\". If this is an inaccuracy in the documentation, please report it to the Bicep Team."), - }); + ]); // Missing non top-level properties - should be a warning compilation = createCompilation(@" @@ -214,9 +214,9 @@ Compilation createCompilation(string program) => Services } } "); - compilation.Should().HaveDiagnostics(new[] { + compilation.Should().HaveDiagnostics([ ("BCP035", DiagnosticLevel.Warning, "The specified \"object\" declaration is missing the following required properties: \"required\". If this is an inaccuracy in the documentation, please report it to the Bicep Team."), - }); + ]); // Non top-level properties that aren't part of the type definition - should be a warning compilation = createCompilation(@" @@ -228,13 +228,13 @@ Compilation createCompilation(string program) => Services } } "); - compilation.Should().HaveDiagnostics(new[] { + compilation.Should().HaveDiagnostics([ ("BCP037", DiagnosticLevel.Warning, "The property \"madeUpProperty\" is not allowed on objects of type \"Properties\". Permissible properties include \"readwrite\", \"writeonly\". If this is an inaccuracy in the documentation, please report it to the Bicep Team."), - }); + ]); } - 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/DiscriminatedObjectTypeTests.cs b/src/Bicep.Core.UnitTests/TypeSystem/DiscriminatedObjectTypeTests.cs index 9fefab20332..552da71d4b1 100644 --- a/src/Bicep.Core.UnitTests/TypeSystem/DiscriminatedObjectTypeTests.cs +++ b/src/Bicep.Core.UnitTests/TypeSystem/DiscriminatedObjectTypeTests.cs @@ -13,19 +13,19 @@ public class DiscriminatedObjectTypeTests [TestMethod] public void DiscriminatedObjectType_should_be_correctly_instantiated() { - var objectA = new ObjectType("objA", TypeSymbolValidationFlags.Default, new[] - { + var objectA = new ObjectType("objA", TypeSymbolValidationFlags.Default, + [ new TypeProperty("discKey", TypeFactory.CreateStringLiteralType("keyA")), new TypeProperty("keyAProp", LanguageConstants.String), - }, null); + ], null); - var objectB = new ObjectType("objB", TypeSymbolValidationFlags.Default, new[] - { + var objectB = new ObjectType("objB", TypeSymbolValidationFlags.Default, + [ new TypeProperty("discKey", TypeFactory.CreateStringLiteralType("keyB")), new TypeProperty("keyBProp", LanguageConstants.String), - }, null); + ], null); - var discObj = new DiscriminatedObjectType("discObj", TypeSymbolValidationFlags.Default, "discKey", new[] { objectA, objectB }); + var discObj = new DiscriminatedObjectType("discObj", TypeSymbolValidationFlags.Default, "discKey", [objectA, objectB]); discObj.UnionMembersByKey.Keys.Should().BeEquivalentTo("'keyA'", "'keyB'"); discObj.TypeKind.Should().Be(TypeKind.DiscriminatedObject); @@ -37,33 +37,33 @@ public void DiscriminatedObjectType_should_be_correctly_instantiated() [TestMethod] public void DiscriminatedObject_should_throw_for_various_badly_formatted_object_arguments() { - var objectA = new ObjectType("objA", TypeSymbolValidationFlags.Default, new[] - { + var objectA = new ObjectType("objA", TypeSymbolValidationFlags.Default, + [ new TypeProperty("discKey", TypeFactory.CreateStringLiteralType("keyA")), new TypeProperty("keyAProp", LanguageConstants.String), - }, null); + ], null); - var missingKeyObject = new ObjectType("objB", TypeSymbolValidationFlags.Default, new[] - { + var missingKeyObject = new ObjectType("objB", TypeSymbolValidationFlags.Default, + [ new TypeProperty("keyBProp", LanguageConstants.String), - }, null); - Action missingKeyConstructorAction = () => new DiscriminatedObjectType("discObj", TypeSymbolValidationFlags.Default, "discKey", new[] { objectA, missingKeyObject }); + ], null); + Action missingKeyConstructorAction = () => new DiscriminatedObjectType("discObj", TypeSymbolValidationFlags.Default, "discKey", [objectA, missingKeyObject]); missingKeyConstructorAction.Should().Throw(); - var invalidKeyTypeObject = new ObjectType("objB", TypeSymbolValidationFlags.Default, new[] - { + var invalidKeyTypeObject = new ObjectType("objB", TypeSymbolValidationFlags.Default, + [ new TypeProperty("discKey", LanguageConstants.String), new TypeProperty("keyBProp", LanguageConstants.String), - }, null); - Action invalidKeyTypeConstructorAction = () => new DiscriminatedObjectType("discObj", TypeSymbolValidationFlags.Default, "discKey", new[] { objectA, invalidKeyTypeObject }); + ], null); + Action invalidKeyTypeConstructorAction = () => new DiscriminatedObjectType("discObj", TypeSymbolValidationFlags.Default, "discKey", [objectA, invalidKeyTypeObject]); invalidKeyTypeConstructorAction.Should().Throw(); - var duplicateKeyObject = new ObjectType("objB", TypeSymbolValidationFlags.Default, new[] - { + var duplicateKeyObject = new ObjectType("objB", TypeSymbolValidationFlags.Default, + [ new TypeProperty("discKey", TypeFactory.CreateStringLiteralType("keyA")), new TypeProperty("keyBProp", LanguageConstants.String), - }, null); - Action duplicateKeyConstructorAction = () => new DiscriminatedObjectType("discObj", TypeSymbolValidationFlags.Default, "discKey", new[] { objectA, duplicateKeyObject }); + ], null); + Action duplicateKeyConstructorAction = () => new DiscriminatedObjectType("discObj", TypeSymbolValidationFlags.Default, "discKey", [objectA, duplicateKeyObject]); duplicateKeyConstructorAction.Should().Throw(); } } diff --git a/src/Bicep.Core.UnitTests/TypeSystem/FunctionResolverTests.cs b/src/Bicep.Core.UnitTests/TypeSystem/FunctionResolverTests.cs index 081cb70ca8c..86d4b37f508 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,9 @@ 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 +125,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 +134,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 +149,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 +164,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 +178,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 +191,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 +204,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 +217,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 +234,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 +250,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 +266,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,10 +287,10 @@ 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[] - { + return + [ CreateRow(TypeFactory.CreateStringLiteralType("++++0"), TypeFactory.CreateIntegerLiteralType(0), TypeFactory.CreateIntegerLiteralType(5), @@ -303,7 +304,7 @@ static object[] CreateRow(TypeSymbol expectedReturnType, params TypeSymbol[] arg CreateRow(TypeFactory.CreateStringType(20, 20), TypeFactory.CreateStringType(1, 10), TypeFactory.CreateIntegerLiteralType(20)), - }; + ]; } [TestMethod] @@ -311,7 +312,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 +324,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 +337,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,10 +345,10 @@ public void LengthInfersPossibleRangesFromRefinementMetadata(TypeSymbol argument private static IEnumerable GetLengthTestCases() { static object[] CreateRow(TypeSymbol argumentType, TypeSymbol returnType) - => new object[] { argumentType, returnType }; + => [argumentType, returnType]; - return new[] - { + return + [ CreateRow(TypeFactory.CreateStringLiteralType("boo!"), TypeFactory.CreateIntegerLiteralType(4)), CreateRow(TypeFactory.CreateStringType(3, 3), @@ -361,54 +362,50 @@ static object[] CreateRow(TypeSymbol argumentType, TypeSymbol returnType) TypeFactory.CreateIntegerType(0)), CreateRow(new ObjectType("object", default, - new TypeProperty[] { new("prop", LanguageConstants.Any, TypePropertyFlags.Required) }, + [new("prop", LanguageConstants.Any, TypePropertyFlags.Required)], null), TypeFactory.CreateIntegerLiteralType(1)), CreateRow(new ObjectType("object", default, - new TypeProperty[] - { + [ new("prop", LanguageConstants.Any, TypePropertyFlags.Required), new("prop2", LanguageConstants.Any), - }, + ], null), TypeFactory.CreateIntegerType(1, 2)), CreateRow(new ObjectType("object", default, - new TypeProperty[] - { + [ new("prop", LanguageConstants.Any, TypePropertyFlags.Required), new("prop2", LanguageConstants.Any), - }, + ], LanguageConstants.Any), TypeFactory.CreateIntegerType(1)), - CreateRow(new DiscriminatedObjectType("discriminated", default, "type", new[] - { + CreateRow(new DiscriminatedObjectType("discriminated", default, "type", + [ new ObjectType("object", default, - new TypeProperty[] - { + [ new("type", TypeFactory.CreateStringLiteralType("fizz"), TypePropertyFlags.Required), new("prop", LanguageConstants.Any, TypePropertyFlags.Required), - }, + ], null), new ObjectType("object", default, - new TypeProperty[] - { + [ new("type", TypeFactory.CreateStringLiteralType("buzz"), TypePropertyFlags.Required), new("prop", LanguageConstants.Any, TypePropertyFlags.Required), new("prop2", LanguageConstants.Any), - }, + ], null), - }), TypeFactory.CreateIntegerType(2, 3)), + ]), TypeFactory.CreateIntegerType(2, 3)), 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)), - }; + ]; } [DataTestMethod] @@ -417,7 +414,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,10 +422,10 @@ 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[] - { + return + [ CreateRow(LanguageConstants.Array, LanguageConstants.String, LanguageConstants.String), CreateRow(new TypedArrayType(TypeFactory.CreateStringType(1, 10), default, 1, 10), TypeFactory.CreateStringLiteralType("/"), @@ -436,19 +433,19 @@ 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)), - }; + ]; } [DataTestMethod] @@ -464,10 +461,10 @@ public void SubstringInfersPossibleLengthRangesFromRefinementMetadata(IList GetSubstringTestCases() { static object[] CreateRow(TypeSymbol expectedReturnType, params TypeSymbol[] argumentTypes) - => new object[] { argumentTypes.ToList(), expectedReturnType }; + => [argumentTypes.ToList(), expectedReturnType]; - return new[] - { + return + [ CreateRow(LanguageConstants.String, LanguageConstants.String, LanguageConstants.Int), CreateRow(LanguageConstants.String, LanguageConstants.Any, LanguageConstants.Int), CreateRow(LanguageConstants.String, LanguageConstants.String, LanguageConstants.Any), @@ -485,7 +482,7 @@ static object[] CreateRow(TypeSymbol expectedReturnType, params TypeSymbol[] arg CreateRow(TypeFactory.CreateStringType(null, 10), TypeFactory.CreateStringType(9, 10), LanguageConstants.Int, TypeFactory.CreateIntegerLiteralType(50)), CreateRow(TypeFactory.CreateStringType(4, 5), TypeFactory.CreateStringType(9, 10), TypeFactory.CreateIntegerLiteralType(5), TypeFactory.CreateIntegerLiteralType(5)), CreateRow(TypeFactory.CreateStringType(2, 2), TypeFactory.CreateStringType(9, 10), TypeFactory.CreateIntegerLiteralType(5), TypeFactory.CreateIntegerLiteralType(2)), - }; + ]; } [DataTestMethod] @@ -494,7 +491,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,10 +499,10 @@ 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[] - { + return + [ CreateRow(LanguageConstants.String, LanguageConstants.Int, LanguageConstants.String), CreateRow(LanguageConstants.String, LanguageConstants.Any, LanguageConstants.String), CreateRow(LanguageConstants.SecureString, LanguageConstants.Int, LanguageConstants.SecureString), @@ -528,7 +525,7 @@ static object[] CreateRow(TypeSymbol originalValue, TypeSymbol numberToSkip, Typ CreateRow(TypeFactory.CreateArrayType(1, 10), TypeFactory.CreateIntegerLiteralType(1), TypeFactory.CreateArrayType(minLength: null, 9)), CreateRow(TypeFactory.CreateArrayType(1, 10), TypeFactory.CreateIntegerLiteralType(15), TypeFactory.CreateArrayType(minLength: null, 0)), CreateRow(TypeFactory.CreateArrayType(5, 10), TypeFactory.CreateIntegerType(2, 3), TypeFactory.CreateArrayType(2, 8)), - }; + ]; } [DataTestMethod] @@ -537,7 +534,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,10 +542,10 @@ 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[] - { + return + [ CreateRow(LanguageConstants.String, LanguageConstants.Int, LanguageConstants.String), CreateRow(LanguageConstants.String, LanguageConstants.Any, LanguageConstants.String), CreateRow(LanguageConstants.SecureString, LanguageConstants.Int, LanguageConstants.SecureString), @@ -573,7 +570,7 @@ static object[] CreateRow(TypeSymbol originalValue, TypeSymbol numberToTake, Typ CreateRow(TypeFactory.CreateArrayType(1, 10), TypeFactory.CreateIntegerLiteralType(15), TypeFactory.CreateArrayType(1, 10)), CreateRow(TypeFactory.CreateArrayType(5, 10), TypeFactory.CreateIntegerType(2, 3), TypeFactory.CreateArrayType(2, 3)), CreateRow(TypeFactory.CreateArrayType(5, 8), TypeFactory.CreateIntegerType(2, 10), TypeFactory.CreateArrayType(2, 8)), - }; + ]; } [TestMethod] @@ -581,7 +578,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 +590,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,10 +598,10 @@ 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[] - { + return + [ CreateRow(LanguageConstants.Any, LanguageConstants.Int, TypeFactory.CreateArrayType(LanguageConstants.Int)), CreateRow(LanguageConstants.Int, LanguageConstants.Any, TypeFactory.CreateArrayType(LanguageConstants.Int)), CreateRow(LanguageConstants.Int, LanguageConstants.Int, TypeFactory.CreateArrayType(LanguageConstants.Int)), @@ -627,7 +624,7 @@ static object[] CreateRow(TypeSymbol startIndex, TypeSymbol count, TypeSymbol ex CreateRow(TypeFactory.CreateIntegerLiteralType(10), TypeHelper.CreateTypeUnion(TypeFactory.CreateIntegerType(0, 11), TypeFactory.CreateIntegerType(19, 30), TypeFactory.CreateIntegerType(9, 20), TypeFactory.CreateIntegerLiteralType(10)), TypeFactory.CreateArrayType(TypeFactory.CreateIntegerType(10, 39), 0, 30)), - }; + ]; } private FunctionResult EvaluateFunction(string functionName, IList argumentTypes, FunctionArgumentSyntax[] arguments) @@ -639,176 +636,166 @@ 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) }, - }; - - private static IEnumerable GetFlattenPositiveTestCases() => new[] - { + private static IEnumerable GetInputsThatFlattenToArrayOfAny() => + [ + [LanguageConstants.Any], + [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() => + [ // flatten(string[][]) -> string[] - new object[] { new TypedArrayType(new TypedArrayType(LanguageConstants.String, default), default), new TypedArrayType(LanguageConstants.String, default) }, + [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[] - { + private static IEnumerable GetFlattenNegativeTestCases() => + [ // flatten(string[]) -> - new object[] { new TypedArrayType(LanguageConstants.String, default), @"Values of type ""string[]"" cannot be flattened because ""string"" is not an array type." }, + [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[] - { + private static IEnumerable GetFirstTestCases() => + [ // first(resourceGroup[]) -> resourceGroup | null - new object[] - { + [ new TypedArrayType(LanguageConstants.CreateResourceScopeReference(ResourceScope.ResourceGroup), default), 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[] - { + private static IEnumerable GetLastTestCases() => + [ // last(resourceGroup[]) -> resourceGroup | null - new object[] - { + [ new TypedArrayType(LanguageConstants.CreateResourceScopeReference(ResourceScope.ResourceGroup), default), 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,11 +830,11 @@ 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[] - { + return + [ CreateRow("IEZpenog", "base64", " Fizz "), CreateRow(" Fizz ", "base64ToString", "IEZpenog"), CreateRow("data:text/plain;charset=utf-8;base64,IEZpenog", "dataUri", " Fizz "), @@ -865,7 +852,7 @@ object[] CreateRow(object? returnedLiteral, string functionName, params object[] CreateRow("1/2/3/True", "format", "{0}/{1}/{2}/{3}", 1, 2, 3, true), CreateRow(" 00", "padLeft", "00", 5, " "), CreateRow(5, "length", "table"), - CreateRow(5, "length", new[] { new[] { 1, 2, 3, 4, 5 } }), + CreateRow(5, "length", [new[] { 1, 2, 3, 4, 5 }]), CreateRow("https://github.com/Azure/bicep", "uri", "https://github.com/another/repo", "/Azure/bicep"), CreateRow("foo", "substring", "foot", 0, 3), CreateRow("foo", "take", "foot", 3), @@ -883,17 +870,17 @@ object[] CreateRow(object? returnedLiteral, string functionName, params object[] CreateRow(true, "contains", new[] { "fizz", "buzz", "pop" }, "fizz"), CreateRow(new[] { "pop" }, "intersection", new[] { "fizz", "buzz", "pop" }, new[] { "snap", "crackle", "pop" }), CreateRow(new[] { "fizz", "buzz", "pop" }, "union", new[] { "fizz", "buzz" }, new[] { "pop" }), - CreateRow("fizz", "first", new[] { new[] { "fizz", "buzz", "pop" } }), - CreateRow(null, "first", new[] { Array.Empty() }), - CreateRow("pop", "last", new[] { new[] { "fizz", "buzz", "pop" } }), - CreateRow(null, "last", new[] { Array.Empty() }), + CreateRow("fizz", "first", [new[] { "fizz", "buzz", "pop" }]), + CreateRow(null, "first", [Array.Empty()]), + CreateRow("pop", "last", [new[] { "fizz", "buzz", "pop" }]), + CreateRow(null, "last", [Array.Empty()]), CreateRow(0, "indexOf", new[] { "fizz", "buzz", "pop", "fizz" }, "fizz"), CreateRow(3, "lastIndexOf", new[] { "fizz", "buzz", "pop", "fizz" }, "fizz"), CreateRow(1, "min", new[] { 10, 4, 1, 6 }), CreateRow(10, "max", new[] { 10, 4, 1, 6 }), CreateRow("foo/bar/baz", "join", new[] { "foo", "bar", "baz"}, "/"), CreateRow("abc/123/True", "join", new object[] { "abc", 123, true }, "/"), - }; + ]; } public static string GetDisplayName(MethodInfo method, object[] row) @@ -909,7 +896,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 +930,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 +945,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 +960,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 +990,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..95e00614c10 100644 --- a/src/Bicep.Core.UnitTests/TypeSystem/OperatorTests.cs +++ b/src/Bicep.Core.UnitTests/TypeSystem/OperatorTests.cs @@ -82,15 +82,15 @@ 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"); UnaryOperationSyntax minus = new(TestSyntaxFactory.CreateToken(TokenType.Minus), symbolRef); UnaryOperationSyntax not = new(TestSyntaxFactory.CreateToken(TokenType.Exclamation), symbolRef); - return new[] - { + return + [ Case(minus, LanguageConstants.Int, LanguageConstants.Int), Case(minus, TypeFactory.CreateIntegerLiteralType(1), TypeFactory.CreateIntegerLiteralType(-1)), Case(minus, TypeFactory.CreateIntegerType(-20, -10), TypeFactory.CreateIntegerType(10, 20)), @@ -99,7 +99,7 @@ static object[] Case(UnaryOperationSyntax expression, TypeSymbol operandType, Ty Case(not, LanguageConstants.Bool, LanguageConstants.Bool), Case(not, TypeFactory.CreateBooleanLiteralType(true), TypeFactory.CreateBooleanLiteralType(false)), Case(not, TypeHelper.CreateTypeUnion(TypeFactory.CreateBooleanLiteralType(true), TypeFactory.CreateBooleanLiteralType(false)), TypeHelper.CreateTypeUnion(TypeFactory.CreateBooleanLiteralType(true), TypeFactory.CreateBooleanLiteralType(false))), - }; + ]; } [DataTestMethod] @@ -145,10 +145,10 @@ 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[] - { + return + [ // || Case(BinaryOperator.LogicalOr, LanguageConstants.Bool, LanguageConstants.Bool, LanguageConstants.Bool), Case(BinaryOperator.LogicalOr, LanguageConstants.True, LanguageConstants.Any, LanguageConstants.True), @@ -305,7 +305,7 @@ static object[] Case(BinaryOperator @operator, TypeSymbol leftOperandType, TypeS TypeHelper.CreateTypeUnion(LanguageConstants.Null, TypeFactory.CreateStringLiteralType("Fizz"), TypeFactory.CreateStringLiteralType("Buzz")), TypeFactory.CreateStringLiteralType("Pop"), TypeHelper.CreateTypeUnion(TypeFactory.CreateStringLiteralType("Fizz"), TypeFactory.CreateStringLiteralType("Buzz"), TypeFactory.CreateStringLiteralType("Pop"))), - }; + ]; } } } diff --git a/src/Bicep.Core.UnitTests/TypeSystem/ResourceDerivedTypeResolverTests.cs b/src/Bicep.Core.UnitTests/TypeSystem/ResourceDerivedTypeResolverTests.cs index e9b8ea5f09d..c98305bdd2a 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); @@ -91,14 +91,13 @@ public void Hydrates_discriminated_object_variant_types() var containsUnresolved = new DiscriminatedObjectType("discriminatedObject", TypeSymbolValidationFlags.Default, "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(), null) - }); + ]); sut.ResolveResourceDerivedTypes(containsUnresolved).Should().BeOfType() .Subject.UnionMembersByKey["'foo'"].Should().BeSameAs(hydrated); @@ -112,7 +111,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() @@ -127,8 +126,8 @@ 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 +141,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 +153,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 +167,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( @@ -187,10 +186,10 @@ private static (ResourceDerivedTypeResolver sut, ResourceTypeReference unhydrate var resourceTypeProviderMock = StrictMock.Of(); var stubbedNamespaceType = new NamespaceType(AzNamespaceType.BuiltInName, AzNamespaceType.Settings, - ImmutableArray.Empty, - ImmutableArray.Empty, - ImmutableArray.Empty, - ImmutableArray.Empty, + [], + [], + [], + [], resourceTypeProviderMock.Object); resourceTypeProviderMock.Setup(x => x.TryGetDefinedType(stubbedNamespaceType, unhydratedTypeRef, ResourceTypeGenerationFlags.None)) .Returns(new ResourceType(stubbedNamespaceType, @@ -199,7 +198,7 @@ private static (ResourceDerivedTypeResolver sut, ResourceTypeReference unhydrate ResourceScope.None, ResourceFlags.None, hydratedType, - ImmutableHashSet.Empty)); + [])); var resolver = NamespaceResolver.Create([ new("az", stubbedNamespaceType, null), @@ -218,10 +217,10 @@ public void Emits_diagnostic_and_uses_fallback_type_when_resource_not_found() var resourceTypeProviderMock = StrictMock.Of(); var stubbedNamespaceType = new NamespaceType(AzNamespaceType.BuiltInName, AzNamespaceType.Settings, - ImmutableArray.Empty, - ImmutableArray.Empty, - ImmutableArray.Empty, - ImmutableArray.Empty, + [], + [], + [], + [], resourceTypeProviderMock.Object); resourceTypeProviderMock.Setup(x => x.TryGetDefinedType(stubbedNamespaceType, unhydratedTypeRef, ResourceTypeGenerationFlags.None)) .Returns((ResourceType?)null); @@ -238,7 +237,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()); @@ -250,33 +249,36 @@ public void Supports_pointers_to_partial_resource_body_types() var targetType = TypeFactory.CreateBooleanLiteralType(false); var hydrated = new ObjectType("object", TypeSymbolValidationFlags.Default, - ImmutableArray.Create(new TypeProperty("property", + [new TypeProperty("property", new TupleType( - ImmutableArray.Create(new ObjectType("dictionary", + [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)), + 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))), + 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..2bd4e12b9bb 100644 --- a/src/Bicep.Core.UnitTests/TypeSystem/TypeHelperTests.cs +++ b/src/Bicep.Core.UnitTests/TypeSystem/TypeHelperTests.cs @@ -27,8 +27,8 @@ static object[] Row(TypeSymbol expected, params TypeSymbol[] toCollapse) => expected.AsEnumerable().Concat(toCollapse).ToArray(); // In the explanatory comments for test cases, the `{inclusiveMin,inclusiveMax}` suffix is used to denote length constraints - return new[] - { + return + [ // collapse(true, false) -> bool Row(LanguageConstants.Bool, LanguageConstants.True, LanguageConstants.False), // collapse(bool, false) -> bool @@ -110,23 +110,23 @@ 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)), + ]; } [TestMethod] @@ -136,19 +136,17 @@ public void Tagged_union_formed_from_object_collapse_where_possible() { new("{type: 'a', foo: string}", default, - new TypeProperty[] - { + [ new("type", TypeFactory.CreateStringLiteralType("a"), TypePropertyFlags.Required), new("foo", LanguageConstants.String, TypePropertyFlags.Required), - }, + ], null), new("{type: 'b', bar: int}", default, - new TypeProperty[] - { + [ new("type", TypeFactory.CreateStringLiteralType("b"), TypePropertyFlags.Required), new("bar", LanguageConstants.Int, TypePropertyFlags.Required), - }, + ], null), }; @@ -167,19 +165,17 @@ public void Tagged_union_should_not_be_formed_when_discriminator_is_not_required { new("{type: 'a', foo: string}", default, - new TypeProperty[] - { + [ new("type", TypeFactory.CreateStringLiteralType("a"), TypePropertyFlags.Required), new("foo", LanguageConstants.String, TypePropertyFlags.Required), - }, + ], null), new("{type: 'b', bar: int}", default, - new TypeProperty[] - { + [ new("type", TypeFactory.CreateStringLiteralType("b"), default), new("bar", LanguageConstants.Int, TypePropertyFlags.Required), - }, + ], null), }; @@ -193,27 +189,24 @@ public void Tagged_union_should_not_be_formed_when_multiple_members_use_same_dis { new("{type: 'a', foo: string}", default, - new TypeProperty[] - { + [ new("type", TypeFactory.CreateStringLiteralType("a"), TypePropertyFlags.Required), new("foo", LanguageConstants.String, TypePropertyFlags.Required), - }, + ], null), new("{type: 'b', bar: int}", default, - new TypeProperty[] - { + [ new("type", TypeFactory.CreateStringLiteralType("b"), default), new("bar", LanguageConstants.Int, TypePropertyFlags.Required), - }, + ], null), new("{type: 'a', baz: int}", default, - new TypeProperty[] - { + [ new("type", TypeFactory.CreateStringLiteralType("a"), default), new("baz", LanguageConstants.Int, TypePropertyFlags.Required), - }, + ], null), }; @@ -227,21 +220,19 @@ public void Tagged_union_formation_should_prefer_discriminator_named_type_when_m { new("{type: 'a', foo: string}", default, - new TypeProperty[] - { + [ new("type", TypeFactory.CreateStringLiteralType("a"), TypePropertyFlags.Required), new("fizz", TypeFactory.CreateStringLiteralType("buzz"), TypePropertyFlags.Required), new("foo", LanguageConstants.String, TypePropertyFlags.Required), - }, + ], null), new("{type: 'b', bar: int}", default, - new TypeProperty[] - { + [ new("type", TypeFactory.CreateStringLiteralType("b"), TypePropertyFlags.Required), new("fizz", TypeFactory.CreateStringLiteralType("pop"), TypePropertyFlags.Required), new("bar", LanguageConstants.Int, TypePropertyFlags.Required), - }, + ], null), }; @@ -258,21 +249,19 @@ public void Tagged_union_formation_should_prefer_discriminator_named_kind_when_m { new("{type: 'a', foo: string}", default, - new TypeProperty[] - { + [ new("kind", TypeFactory.CreateStringLiteralType("a"), TypePropertyFlags.Required), new("fizz", TypeFactory.CreateStringLiteralType("buzz"), TypePropertyFlags.Required), new("foo", LanguageConstants.String, TypePropertyFlags.Required), - }, + ], null), new("{type: 'b', bar: int}", default, - new TypeProperty[] - { + [ new("kind", TypeFactory.CreateStringLiteralType("b"), TypePropertyFlags.Required), new("fizz", TypeFactory.CreateStringLiteralType("pop"), TypePropertyFlags.Required), new("bar", LanguageConstants.Int, TypePropertyFlags.Required), - }, + ], null), }; @@ -289,21 +278,19 @@ public void Tagged_union_formation_should_prefer_alpha_sorted_discriminator_when { new("{type: 'a', foo: string}", default, - new TypeProperty[] - { + [ new("variety", TypeFactory.CreateStringLiteralType("a"), TypePropertyFlags.Required), new("fizz", TypeFactory.CreateStringLiteralType("buzz"), TypePropertyFlags.Required), new("foo", LanguageConstants.String, TypePropertyFlags.Required), - }, + ], null), new("{type: 'b', bar: int}", default, - new TypeProperty[] - { + [ new("variety", TypeFactory.CreateStringLiteralType("b"), TypePropertyFlags.Required), new("fizz", TypeFactory.CreateStringLiteralType("pop"), TypePropertyFlags.Required), new("bar", LanguageConstants.Int, TypePropertyFlags.Required), - }, + ], null), }; diff --git a/src/Bicep.Core.UnitTests/TypeSystem/TypeValidatorAssignabilityTests.cs b/src/Bicep.Core.UnitTests/TypeSystem/TypeValidatorAssignabilityTests.cs index ba3b4dc5695..3faa0b5e528 100644 --- a/src/Bicep.Core.UnitTests/TypeSystem/TypeValidatorAssignabilityTests.cs +++ b/src/Bicep.Core.UnitTests/TypeSystem/TypeValidatorAssignabilityTests.cs @@ -249,10 +249,10 @@ 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[] - { + return + [ // A matching source and target type should narrow to the same and produce no warnings Row(LanguageConstants.String, LanguageConstants.String, LanguageConstants.String), @@ -304,7 +304,7 @@ static object[] Row(TypeSymbol sourceType, TypeSymbol targetType, TypeSymbol exp // A literal source type should narrow to the literal Row(TypeFactory.CreateStringLiteralType("boo!"), LanguageConstants.String, TypeFactory.CreateStringLiteralType("boo!")), - }; + ]; } [TestMethod] @@ -339,10 +339,10 @@ 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[] - { + return + [ // A matching source and target type should narrow to the same and produce no warnings Row(LanguageConstants.Int, LanguageConstants.Int, LanguageConstants.Int), @@ -394,7 +394,7 @@ static object[] Row(TypeSymbol sourceType, TypeSymbol targetType, TypeSymbol exp // A literal source type should narrow to the literal Row(TypeFactory.CreateIntegerLiteralType(0), LanguageConstants.Int, TypeFactory.CreateIntegerLiteralType(0)), - }; + ]; } [DataTestMethod] @@ -423,10 +423,10 @@ public void Variousobjects_ShouldProduceAnErrorWhenAssignedToString(string displ [TestMethod] public void MinimalResourceShouldBeValid() { - var obj = TestSyntaxFactory.CreateObject(new[] - { + var obj = TestSyntaxFactory.CreateObject( + [ TestSyntaxFactory.CreateProperty("name", TestSyntaxFactory.CreateString("test")) - }); + ]); var hierarchy = SyntaxHierarchy.Build(obj); @@ -438,15 +438,15 @@ public void MinimalResourceShouldBeValid() [TestMethod] public void ResourceWithValidZonesShouldBeAccepted() { - var obj = TestSyntaxFactory.CreateObject(new[] - { + var obj = TestSyntaxFactory.CreateObject( + [ TestSyntaxFactory.CreateProperty("name", TestSyntaxFactory.CreateString("test")), - TestSyntaxFactory.CreateProperty("zones", TestSyntaxFactory.CreateArray(new [] - { + TestSyntaxFactory.CreateProperty("zones", TestSyntaxFactory.CreateArray( + [ TestSyntaxFactory.CreateArrayItem(TestSyntaxFactory.CreateString("1")), TestSyntaxFactory.CreateArrayItem(TestSyntaxFactory.CreateString("2")) - })) - }); + ])) + ]); var hierarchy = SyntaxHierarchy.Build(obj); @@ -457,30 +457,30 @@ public void ResourceWithValidZonesShouldBeAccepted() [TestMethod] public void InvalidArrayValuesShouldBeRejected() { - var obj = TestSyntaxFactory.CreateObject(new[] - { + var obj = TestSyntaxFactory.CreateObject( + [ TestSyntaxFactory.CreateProperty("name", TestSyntaxFactory.CreateString("test")), // zones is an array of strings - set wrong item types - TestSyntaxFactory.CreateProperty("zones", TestSyntaxFactory.CreateArray(new[] - { + TestSyntaxFactory.CreateProperty("zones", TestSyntaxFactory.CreateArray( + [ TestSyntaxFactory.CreateArrayItem(TestSyntaxFactory.CreateBool(true)), TestSyntaxFactory.CreateArrayItem(TestSyntaxFactory.CreateInt(2)) - })), + ])), // this property is an array - specify a string instead TestSyntaxFactory.CreateProperty("managedByExtended", TestSyntaxFactory.CreateString("not an array")) - }); + ]); var hierarchy = SyntaxHierarchy.Build(obj); var (narrowedType, diagnostics) = NarrowTypeAndCollectDiagnostics(hierarchy, obj, CreateDummyResourceType()); - diagnostics.OrderBy(x => x.Message).Should().HaveDiagnostics(new[] { + diagnostics.OrderBy(x => x.Message).Should().HaveDiagnostics([ ("BCP034", DiagnosticLevel.Error, "The enclosing array expected an item of type \"string\", but the provided item was of type \"2\"."), ("BCP034", DiagnosticLevel.Error, "The enclosing array expected an item of type \"string\", but the provided item was of type \"true\"."), ("BCP036", DiagnosticLevel.Error, "The property \"managedByExtended\" expected a value of type \"string[]\" but the provided value is of type \"'not an array'\"."), - }); + ]); } [TestMethod] @@ -489,18 +489,18 @@ 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[] - { + diagnostics.Should().HaveDiagnostics( + [ // the string at index 0 is too long ("BCP332", DiagnosticLevel.Error, "The provided value (whose length will always be greater than or equal to 3) is too long to assign to a target for which the maximum allowable length is 2."), // the int at index 1 is too small ("BCP328", DiagnosticLevel.Error, "The provided value (which will always be less than or equal to 5) is too small to assign to a target for which the minimum allowable value is 6."), // the whole array is too long ("BCP332", DiagnosticLevel.Error, "The provided value (whose length will always be greater than or equal to 3) is too long to assign to a target for which the maximum allowable length is 2."), - }); + ]); } [DataTestMethod] @@ -531,10 +531,10 @@ 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[] - { + return + [ // A matching source and target type should narrow to the same and produce no warnings Row(LanguageConstants.Array, LanguageConstants.Array, LanguageConstants.Array), @@ -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), @@ -599,13 +599,13 @@ static object[] Row(TypeSymbol sourceType, TypeSymbol targetType, TypeSymbol exp new TupleType(LanguageConstants.DeclarationTypes.Values.ToImmutableArray(), default), TypeFactory.CreateArrayType(maxLength: LanguageConstants.DeclarationTypes.Count - 1), ("BCP333", DiagnosticLevel.Error, $"The provided value (whose length will always be less than or equal to {LanguageConstants.DeclarationTypes.Count - 1}) is too short to assign to a target for which the minimum allowable length is {LanguageConstants.DeclarationTypes.Count}.")), - }; + ]; } [TestMethod] public void RequiredPropertyShouldBeRequired() { - var obj = TestSyntaxFactory.CreateObject(new ObjectPropertySyntax[0]); + var obj = TestSyntaxFactory.CreateObject([]); var hierarchy = SyntaxHierarchy.Build(obj); @@ -618,10 +618,10 @@ public void RequiredPropertyShouldBeRequired() [TestMethod] public void RequiredPropertyWithParseErrorsShouldProduceNoErrors() { - var obj = TestSyntaxFactory.CreateObject(new[] - { + var obj = TestSyntaxFactory.CreateObject( + [ TestSyntaxFactory.CreateProperty("foo", TestSyntaxFactory.CreateString("a")), - }); + ]); var hierarchy = SyntaxHierarchy.Build(obj); var parsingErrorLookupMock = StrictMock.Of(); @@ -636,39 +636,39 @@ public void RequiredPropertyWithParseErrorsShouldProduceNoErrors() [TestMethod] public void WrongTypeOfAdditionalPropertiesShouldBeRejected() { - var obj = TestSyntaxFactory.CreateObject(new[] - { + var obj = TestSyntaxFactory.CreateObject( + [ TestSyntaxFactory.CreateProperty("name", TestSyntaxFactory.CreateString("test")), - TestSyntaxFactory.CreateProperty("tags", TestSyntaxFactory.CreateObject(new[] - { + TestSyntaxFactory.CreateProperty("tags", TestSyntaxFactory.CreateObject( + [ TestSyntaxFactory.CreateProperty("wrongTagType", TestSyntaxFactory.CreateBool(true)), TestSyntaxFactory.CreateProperty("wrongTagType2", TestSyntaxFactory.CreateInt(3)) - })) - }); + ])) + ]); var hierarchy = SyntaxHierarchy.Build(obj); var (narrowedType, diagnostics) = NarrowTypeAndCollectDiagnostics(hierarchy, obj, CreateDummyResourceType()); - diagnostics.OrderBy(x => x.Message).Should().HaveDiagnostics(new[] { + diagnostics.OrderBy(x => x.Message).Should().HaveDiagnostics([ ("BCP036", DiagnosticLevel.Error, "The property \"wrongTagType\" expected a value of type \"string\" but the provided value is of type \"true\"."), ("BCP036", DiagnosticLevel.Error, "The property \"wrongTagType2\" expected a value of type \"string\" but the provided value is of type \"3\"."), - }); + ]); } [TestMethod] public void WrongTypeOfAdditionalPropertiesWithParseErrorsShouldProduceNoErrors() { - var tags = TestSyntaxFactory.CreateProperty("tags", TestSyntaxFactory.CreateObject(new[] - { + var tags = TestSyntaxFactory.CreateProperty("tags", TestSyntaxFactory.CreateObject( + [ TestSyntaxFactory.CreateProperty("wrongTagType", TestSyntaxFactory.CreateBool(true)), - })); + ])); - var obj = TestSyntaxFactory.CreateObject(new[] - { + var obj = TestSyntaxFactory.CreateObject( + [ TestSyntaxFactory.CreateProperty("name", TestSyntaxFactory.CreateString("test")), tags, - }); + ]); var hierarchy = SyntaxHierarchy.Build(obj); @@ -684,18 +684,18 @@ public void WrongTypeOfAdditionalPropertiesWithParseErrorsShouldProduceNoErrors( [TestMethod] public void AdditionalPropertiesWithFallbackTypeFlagShouldProduceWarning() { - var obj = TestSyntaxFactory.CreateObject(new[] - { + var obj = TestSyntaxFactory.CreateObject( + [ TestSyntaxFactory.CreateProperty("inSchema", TestSyntaxFactory.CreateString("ping")), TestSyntaxFactory.CreateProperty("notInSchema", TestSyntaxFactory.CreateString("pong")), - }); + ]); var hierarchy = SyntaxHierarchy.Build(obj); var (narrowedType, diagnostics) = NarrowTypeAndCollectDiagnostics(hierarchy, obj, new ObjectType( "additionalPropertiesFallbackTypeTest", TypeSymbolValidationFlags.Default, - new[] { new TypeProperty("inSchema", LanguageConstants.String) }, + [new TypeProperty("inSchema", LanguageConstants.String)], LanguageConstants.Any, TypePropertyFlags.FallbackProperty)); @@ -710,26 +710,25 @@ public void DiscriminatedObjectType_raises_appropriate_diagnostics_for_matches() "discObj", TypeSymbolValidationFlags.Default, "myDiscriminator", - new[] - { - new ObjectType("typeA", TypeSymbolValidationFlags.Default, new [] - { + [ + new ObjectType("typeA", TypeSymbolValidationFlags.Default, + [ new TypeProperty("myDiscriminator", TypeFactory.CreateStringLiteralType("valA")), new TypeProperty("fieldA", LanguageConstants.String, TypePropertyFlags.Required), - }, null), - new ObjectType("typeB", TypeSymbolValidationFlags.Default, new [] - { + ], null), + new ObjectType("typeB", TypeSymbolValidationFlags.Default, + [ new TypeProperty("myDiscriminator", TypeFactory.CreateStringLiteralType("valB")), new TypeProperty("fieldB", LanguageConstants.String, TypePropertyFlags.Required), - }, null), - }); + ], null), + ]); { // no discriminator field supplied - var obj = TestSyntaxFactory.CreateObject(new[] - { + var obj = TestSyntaxFactory.CreateObject( + [ TestSyntaxFactory.CreateProperty("fieldA", TestSyntaxFactory.CreateString("someVal")), - }); + ]); var hierarchy = SyntaxHierarchy.Build(obj); var (narrowedType, diagnostics) = NarrowTypeAndCollectDiagnostics(hierarchy, obj, discriminatedType); @@ -744,11 +743,11 @@ 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())), + var obj = TestSyntaxFactory.CreateObject( + [ + TestSyntaxFactory.CreateProperty("myDiscriminator", TestSyntaxFactory.CreateObject([])), TestSyntaxFactory.CreateProperty("fieldB", TestSyntaxFactory.CreateString("someVal")), - }); + ]); var hierarchy = SyntaxHierarchy.Build(obj); var (narrowedType, diagnostics) = NarrowTypeAndCollectDiagnostics(hierarchy, obj, discriminatedType); @@ -763,10 +762,10 @@ public void DiscriminatedObjectType_raises_appropriate_diagnostics_for_matches() { // discriminator value that matches neither option supplied - var obj = TestSyntaxFactory.CreateObject(new[] - { + var obj = TestSyntaxFactory.CreateObject( + [ TestSyntaxFactory.CreateProperty("myDiscriminator", TestSyntaxFactory.CreateString("valC")), - }); + ]); var hierarchy = SyntaxHierarchy.Build(obj); var (narrowedType, diagnostics) = NarrowTypeAndCollectDiagnostics(hierarchy, obj, discriminatedType); @@ -781,10 +780,10 @@ public void DiscriminatedObjectType_raises_appropriate_diagnostics_for_matches() { // missing required property for the 'valB' branch - var obj = TestSyntaxFactory.CreateObject(new[] - { + var obj = TestSyntaxFactory.CreateObject( + [ TestSyntaxFactory.CreateProperty("myDiscriminator", TestSyntaxFactory.CreateString("valB")), - }); + ]); var hierarchy = SyntaxHierarchy.Build(obj); var (narrowedType, diagnostics) = NarrowTypeAndCollectDiagnostics(hierarchy, obj, discriminatedType); @@ -806,11 +805,11 @@ public void DiscriminatedObjectType_raises_appropriate_diagnostics_for_matches() { // supplied the required property for the 'valB' branch - var obj = TestSyntaxFactory.CreateObject(new[] - { + var obj = TestSyntaxFactory.CreateObject( + [ TestSyntaxFactory.CreateProperty("myDiscriminator", TestSyntaxFactory.CreateString("valB")), TestSyntaxFactory.CreateProperty("fieldB", TestSyntaxFactory.CreateString("someVal")), - }); + ]); var hierarchy = SyntaxHierarchy.Build(obj); var (narrowedType, diagnostics) = NarrowTypeAndCollectDiagnostics(hierarchy, obj, discriminatedType); @@ -849,7 +848,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,33 +902,33 @@ 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])); + yield return CreateRow("Empty", TestSyntaxFactory.CreateObject([])); - yield return CreateRow("StringProperty", TestSyntaxFactory.CreateObject(new[] { TestSyntaxFactory.CreateProperty("test", TestSyntaxFactory.CreateString("value")) })); + yield return CreateRow("StringProperty", TestSyntaxFactory.CreateObject([TestSyntaxFactory.CreateProperty("test", TestSyntaxFactory.CreateString("value"))])); - yield return CreateRow("IntProperty", TestSyntaxFactory.CreateObject(new[] { TestSyntaxFactory.CreateProperty("test", TestSyntaxFactory.CreateInt(42)) })); + yield return CreateRow("IntProperty", TestSyntaxFactory.CreateObject([TestSyntaxFactory.CreateProperty("test", TestSyntaxFactory.CreateInt(42))])); - yield return CreateRow("MixedProperties", TestSyntaxFactory.CreateObject(new[] - { + yield return CreateRow("MixedProperties", TestSyntaxFactory.CreateObject( + [ TestSyntaxFactory.CreateProperty("int", TestSyntaxFactory.CreateInt(444)), TestSyntaxFactory.CreateProperty("str", TestSyntaxFactory.CreateString("str value")), TestSyntaxFactory.CreateProperty("bool", TestSyntaxFactory.CreateBool(true)), TestSyntaxFactory.CreateProperty("not", TestSyntaxFactory.CreateBool(false)), - TestSyntaxFactory.CreateProperty("obj", TestSyntaxFactory.CreateObject(new[] - { + TestSyntaxFactory.CreateProperty("obj", TestSyntaxFactory.CreateObject( + [ TestSyntaxFactory.CreateProperty("nested", TestSyntaxFactory.CreateString("nested value")), - TestSyntaxFactory.CreateProperty("nested2", TestSyntaxFactory.CreateObject(new ObjectPropertySyntax[0])) - })) - })); + TestSyntaxFactory.CreateProperty("nested2", TestSyntaxFactory.CreateObject([])) + ])) + ])); - yield return CreateRow("DuplicatedObjectProperties", TestSyntaxFactory.CreateObject(new[] - { + yield return CreateRow("DuplicatedObjectProperties", TestSyntaxFactory.CreateObject( + [ TestSyntaxFactory.CreateProperty("foo", TestSyntaxFactory.CreateInt(444)), TestSyntaxFactory.CreateProperty("bar", TestSyntaxFactory.CreateString("str value")), - })); + ])); } private TypeSymbol CreateDummyResourceType() diff --git a/src/Bicep.Core.UnitTests/TypeSystem/TypeValidatorCompileTimeConstantTests.cs b/src/Bicep.Core.UnitTests/TypeSystem/TypeValidatorCompileTimeConstantTests.cs index 3c873b96009..563abbe0daa 100644 --- a/src/Bicep.Core.UnitTests/TypeSystem/TypeValidatorCompileTimeConstantTests.cs +++ b/src/Bicep.Core.UnitTests/TypeSystem/TypeValidatorCompileTimeConstantTests.cs @@ -103,17 +103,17 @@ private static IEnumerable GetLiteralExpressionData() yield return CreateRow("int", TestSyntaxFactory.CreateInt(42)); yield return CreateRow("negative int", TestSyntaxFactory.CreateUnaryMinus(TestSyntaxFactory.CreateInt(42))); - yield return CreateRow("empty object", TestSyntaxFactory.CreateObject(new ObjectPropertySyntax[0])); + yield return CreateRow("empty object", TestSyntaxFactory.CreateObject([])); - yield return CreateRow("object literal", TestSyntaxFactory.CreateObject(new[] - { + yield return CreateRow("object literal", TestSyntaxFactory.CreateObject( + [ TestSyntaxFactory.CreateProperty("one", TestSyntaxFactory.CreateNull()), TestSyntaxFactory.CreateProperty("two", TestSyntaxFactory.CreateBool(true)), TestSyntaxFactory.CreateProperty("three", TestSyntaxFactory.CreateBool(false)), TestSyntaxFactory.CreateProperty("four", TestSyntaxFactory.CreateString("hello")), TestSyntaxFactory.CreateProperty("five", TestSyntaxFactory.CreateInt(42)), - TestSyntaxFactory.CreateProperty("six", TestSyntaxFactory.CreateObject(new [] - { + TestSyntaxFactory.CreateProperty("six", TestSyntaxFactory.CreateObject( + [ TestSyntaxFactory.CreateProperty("one", TestSyntaxFactory.CreateNull()), TestSyntaxFactory.CreateProperty("two", TestSyntaxFactory.CreateBool(true)), TestSyntaxFactory.CreateProperty("three", TestSyntaxFactory.CreateBool(false)), @@ -127,10 +127,10 @@ private static IEnumerable GetLiteralExpressionData() TestSyntaxFactory.CreateString("other"), TestSyntaxFactory.CreateInt(103) })) - })) - })); + ])) + ])); - yield return CreateRow("empty array", TestSyntaxFactory.CreateArray(new ArrayItemSyntax[0])); + yield return CreateRow("empty array", TestSyntaxFactory.CreateArray([])); yield return CreateRow("array literal", TestSyntaxFactory.CreateArray(new SyntaxBase[] { @@ -139,8 +139,8 @@ private static IEnumerable GetLiteralExpressionData() TestSyntaxFactory.CreateBool(false), TestSyntaxFactory.CreateString("other"), TestSyntaxFactory.CreateInt(103), - TestSyntaxFactory.CreateObject(new[] - { + TestSyntaxFactory.CreateObject( + [ TestSyntaxFactory.CreateProperty("one", TestSyntaxFactory.CreateNull()), TestSyntaxFactory.CreateProperty("two", TestSyntaxFactory.CreateBool(true)), TestSyntaxFactory.CreateProperty("three", TestSyntaxFactory.CreateBool(false)), @@ -154,7 +154,7 @@ private static IEnumerable GetLiteralExpressionData() TestSyntaxFactory.CreateString("other"), TestSyntaxFactory.CreateInt(103) })) - }), + ]), TestSyntaxFactory.CreateArray(new SyntaxBase[] { TestSyntaxFactory.CreateNull(), @@ -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..f1cc41b4214 100644 --- a/src/Bicep.Core.UnitTests/Utils/BuiltInTestTypes.cs +++ b/src/Bicep.Core.UnitTests/Utils/BuiltInTestTypes.cs @@ -21,45 +21,45 @@ private static ResourceTypeComponents BasicTestsType() return new ResourceTypeComponents(resourceType, ResourceScope.ResourceGroup, ResourceScope.None, ResourceFlags.None, new ObjectType(resourceType.FormatName(), TypeSymbolValidationFlags.Default, - AzResourceTypeProvider.GetCommonResourceProperties(resourceType).Concat(new[] { + AzResourceTypeProvider.GetCommonResourceProperties(resourceType).Concat([ new TypeProperty("kind", LanguageConstants.String, TypePropertyFlags.ReadOnly, "kind property"), - }), null)); + ]), null)); } private static ResourceTypeComponents ReadWriteTestsType() { var resourceType = ResourceTypeReference.Parse("Test.Rp/readWriteTests@2020-01-01"); - var propertiesType = new ObjectType("Properties", TypeSymbolValidationFlags.WarnOnPropertyTypeMismatch, new[] { + var propertiesType = new ObjectType("Properties", TypeSymbolValidationFlags.WarnOnPropertyTypeMismatch, [ new TypeProperty("readwrite", LanguageConstants.String, TypePropertyFlags.None, "This is a property which supports reading AND writing!"), new TypeProperty("readonly", LanguageConstants.String, TypePropertyFlags.ReadOnly, "This is a property which only supports reading."), new TypeProperty("writeonly", LanguageConstants.String, TypePropertyFlags.WriteOnly, "This is a property which only supports writing."), new TypeProperty("required", LanguageConstants.String, TypePropertyFlags.Required, "This is a property which is required."), - }, null); + ], null); return new ResourceTypeComponents(resourceType, ResourceScope.ResourceGroup, ResourceScope.None, ResourceFlags.None, new ObjectType(resourceType.FormatName(), TypeSymbolValidationFlags.Default, - AzResourceTypeProvider.GetCommonResourceProperties(resourceType).Concat(new[] { + AzResourceTypeProvider.GetCommonResourceProperties(resourceType).Concat([ new TypeProperty("properties", propertiesType, TypePropertyFlags.Required, "properties property"), - }), null)); + ]), null)); } private static ResourceTypeComponents ReadOnlyTestsType() { var resourceType = ResourceTypeReference.Parse("Test.Rp/readOnlyTests@2020-01-01"); - var propertiesType = new ObjectType("Properties", TypeSymbolValidationFlags.WarnOnPropertyTypeMismatch, new[] { + var propertiesType = new ObjectType("Properties", TypeSymbolValidationFlags.WarnOnPropertyTypeMismatch, [ new TypeProperty("readwrite", LanguageConstants.String, TypePropertyFlags.None, "This is a property which supports reading AND writing!"), new TypeProperty("readonly", LanguageConstants.String, TypePropertyFlags.ReadOnly, "This is a property which only supports reading."), new TypeProperty("writeonly", LanguageConstants.String, TypePropertyFlags.WriteOnly, "This is a property which only supports writing."), new TypeProperty("required", LanguageConstants.String, TypePropertyFlags.Required, "This is a property which is required."), - }, null); + ], null); return new ResourceTypeComponents(resourceType, ResourceScope.ResourceGroup, ResourceScope.None, ResourceFlags.ReadOnly, new ObjectType(resourceType.FormatName(), TypeSymbolValidationFlags.Default, - AzResourceTypeProvider.GetCommonResourceProperties(resourceType).Concat(new[] { + AzResourceTypeProvider.GetCommonResourceProperties(resourceType).Concat([ new TypeProperty("properties", propertiesType, TypePropertyFlags.ReadOnly, "properties property"), - }), null)); + ]), null)); } private static ResourceTypeComponents DiscriminatorTestsType() @@ -69,33 +69,33 @@ private static ResourceTypeComponents DiscriminatorTestsType() var bodyAProps = new ObjectType( "BodyAProperties", TypeSymbolValidationFlags.WarnOnPropertyTypeMismatch, - new[] { + [ new TypeProperty("propA", LanguageConstants.String, TypePropertyFlags.None, "This is the description for propA!"), - }, + ], null); var bodyBProps = new ObjectType( "BodyBProperties", TypeSymbolValidationFlags.WarnOnPropertyTypeMismatch, - new[] { + [ new TypeProperty("propB", LanguageConstants.String, TypePropertyFlags.None, "This is the description for propB!"), - }, + ], null); var bodyType = new DiscriminatedObjectType( resourceType.FormatName(), TypeSymbolValidationFlags.Default, "kind", - new[] { - new ObjectType("BodyA", TypeSymbolValidationFlags.Default, AzResourceTypeProvider.GetCommonResourceProperties(resourceType).Concat(new [] { + [ + new ObjectType("BodyA", TypeSymbolValidationFlags.Default, AzResourceTypeProvider.GetCommonResourceProperties(resourceType).Concat([ new TypeProperty("kind", TypeFactory.CreateStringLiteralType("BodyA"), TypePropertyFlags.None, "This is the kind of body A"), new TypeProperty("properties", bodyAProps, TypePropertyFlags.None, "These are the properties for body A"), - }), null), - new ObjectType("BodyB", TypeSymbolValidationFlags.Default, AzResourceTypeProvider.GetCommonResourceProperties(resourceType).Concat(new [] { + ]), null), + new ObjectType("BodyB", TypeSymbolValidationFlags.Default, AzResourceTypeProvider.GetCommonResourceProperties(resourceType).Concat([ new TypeProperty("kind", TypeFactory.CreateStringLiteralType("BodyB"), TypePropertyFlags.None, "This is the kind of body B"), new TypeProperty("properties", bodyBProps, TypePropertyFlags.None, "These are the properties for body B"), - }), null), - }); + ]), null), + ]); return new ResourceTypeComponents(resourceType, ResourceScope.ResourceGroup, ResourceScope.None, ResourceFlags.None, bodyType); } @@ -107,32 +107,32 @@ private static ResourceTypeComponents DiscriminatedPropertiesTestsType() var propsA = new ObjectType( "PropertiesA", TypeSymbolValidationFlags.WarnOnPropertyTypeMismatch, - new[] { + [ new TypeProperty("propType", TypeFactory.CreateStringLiteralType("PropertiesA"), TypePropertyFlags.None, "..."), new TypeProperty("propA", LanguageConstants.String, TypePropertyFlags.None, "This is the description for propA!"), - }, + ], null); var propsB = new ObjectType( "PropertiesB", TypeSymbolValidationFlags.WarnOnPropertyTypeMismatch, - new[] { + [ new TypeProperty("propType", TypeFactory.CreateStringLiteralType("PropertiesB"), TypePropertyFlags.None, "..."), new TypeProperty("propB", LanguageConstants.String, TypePropertyFlags.None, "This is the description for propB!"), - }, + ], null); var propertiesType = new DiscriminatedObjectType( "properties", TypeSymbolValidationFlags.Default, "propType", - new[] { propsA, propsB }); + [propsA, propsB]); return new ResourceTypeComponents(resourceType, ResourceScope.ResourceGroup, ResourceScope.None, ResourceFlags.None, new ObjectType(resourceType.FormatName(), TypeSymbolValidationFlags.Default, - AzResourceTypeProvider.GetCommonResourceProperties(resourceType).Concat(new[] { + AzResourceTypeProvider.GetCommonResourceProperties(resourceType).Concat([ new TypeProperty("properties", propertiesType, TypePropertyFlags.Required, "properties property"), - }), null)); + ]), null)); } private static ResourceTypeComponents DiscriminatedPropertiesTestsType2() @@ -142,54 +142,54 @@ private static ResourceTypeComponents DiscriminatedPropertiesTestsType2() var bodyAProps = new ObjectType( "BodyAProperties", TypeSymbolValidationFlags.WarnOnPropertyTypeMismatch, - new[] { + [ new TypeProperty("propA", LanguageConstants.String, TypePropertyFlags.None, "This is the description for propA!"), - }, + ], null); var bodyBProps = new ObjectType( "BodyBProperties", TypeSymbolValidationFlags.WarnOnPropertyTypeMismatch, - new[] { + [ new TypeProperty("propB", LanguageConstants.String, TypePropertyFlags.None, "This is the description for propB!"), - }, + ], null); var propertiesType = new DiscriminatedObjectType( "properties", TypeSymbolValidationFlags.Default, "propType", - new[] { - new ObjectType("BodyA", TypeSymbolValidationFlags.Default, AzResourceTypeProvider.GetCommonResourceProperties(resourceType).Concat(new [] { + [ + new ObjectType("BodyA", TypeSymbolValidationFlags.Default, AzResourceTypeProvider.GetCommonResourceProperties(resourceType).Concat([ new TypeProperty("propType", TypeFactory.CreateStringLiteralType("PropertiesA"), TypePropertyFlags.None, "This is the propType of body A"), new TypeProperty("values", bodyAProps, TypePropertyFlags.None, "These are the properties for body A"), - }), null), - new ObjectType("BodyB", TypeSymbolValidationFlags.Default, AzResourceTypeProvider.GetCommonResourceProperties(resourceType).Concat(new [] { + ]), null), + new ObjectType("BodyB", TypeSymbolValidationFlags.Default, AzResourceTypeProvider.GetCommonResourceProperties(resourceType).Concat([ new TypeProperty("propType", TypeFactory.CreateStringLiteralType("PropertiesB"), TypePropertyFlags.None, "This is the propType of body B"), new TypeProperty("values", bodyBProps, TypePropertyFlags.None, "These are the properties for body B"), - }), null), - }); + ]), null), + ]); return new ResourceTypeComponents(resourceType, ResourceScope.ResourceGroup, ResourceScope.None, ResourceFlags.None, new ObjectType(resourceType.FormatName(), TypeSymbolValidationFlags.Default, - AzResourceTypeProvider.GetCommonResourceProperties(resourceType).Concat(new[] { + AzResourceTypeProvider.GetCommonResourceProperties(resourceType).Concat([ new TypeProperty("properties", propertiesType, TypePropertyFlags.Required, "properties property"), - }), null)); + ]), null)); } private static ResourceTypeComponents FallbackPropertyTestsType() { var resourceType = ResourceTypeReference.Parse("Test.Rp/fallbackProperties@2020-01-01"); - var propertiesType = new ObjectType("Properties", TypeSymbolValidationFlags.WarnOnPropertyTypeMismatch, new[] { + var propertiesType = new ObjectType("Properties", TypeSymbolValidationFlags.WarnOnPropertyTypeMismatch, [ new TypeProperty("required", LanguageConstants.String, TypePropertyFlags.Required, "This is a property which is required."), - }, null); + ], null); return new ResourceTypeComponents(resourceType, ResourceScope.ResourceGroup, ResourceScope.None, ResourceFlags.None, new ObjectType(resourceType.FormatName(), TypeSymbolValidationFlags.Default, - AzResourceTypeProvider.GetCommonResourceProperties(resourceType).Concat(new[] { + AzResourceTypeProvider.GetCommonResourceProperties(resourceType).Concat([ new TypeProperty("properties", propertiesType, TypePropertyFlags.Required, "properties property"), - }).Concat( + ]).Concat( AzResourceTypeProvider.KnownTopLevelResourceProperties().Where(p => !string.Equals(p.Name, "properties", LanguageConstants.IdentifierComparison)) .Select(p => new TypeProperty(p.Name, p.TypeReference, TypePropertyFlags.None, "Property that does something important")) ), null)); @@ -200,20 +200,20 @@ private static ResourceTypeComponents ListFunctionsType() var resourceType = ResourceTypeReference.Parse("Test.Rp/listFuncTests@2020-01-01"); var noInputOutput = new ObjectType("NoInputOutput", TypeSymbolValidationFlags.Default, - new[] { + [ new TypeProperty("noInputOutputVal", LanguageConstants.String, TypePropertyFlags.ReadOnly, "Foo description"), - }, null); + ], null); var withInputInput = new ObjectType("WithInputInput", TypeSymbolValidationFlags.Default, - new[] { + [ new TypeProperty("withInputInputVal", LanguageConstants.String, TypePropertyFlags.WriteOnly | TypePropertyFlags.Required, "Foo description"), new TypeProperty("optionalVal", LanguageConstants.String, TypePropertyFlags.WriteOnly, "optionalVal description"), new TypeProperty("optionalLiteralVal", TypeHelper.CreateTypeUnion(TypeFactory.CreateStringLiteralType("either"), TypeFactory.CreateStringLiteralType("or")), TypePropertyFlags.WriteOnly, "optionalLiteralVal description"), - }, null); + ], null); var withInputOutput = new ObjectType("WithInputOutput", TypeSymbolValidationFlags.Default, - new[] { + [ new TypeProperty("withInputOutputVal", LanguageConstants.String, TypePropertyFlags.ReadOnly, "Foo description"), - }, null); + ], null); var overloads = new[] { @@ -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/TestSyntaxFactory.cs b/src/Bicep.Core.UnitTests/Utils/TestSyntaxFactory.cs index 6fe45b2e1d5..a6a1326ef7a 100644 --- a/src/Bicep.Core.UnitTests/Utils/TestSyntaxFactory.cs +++ b/src/Bicep.Core.UnitTests/Utils/TestSyntaxFactory.cs @@ -36,9 +36,9 @@ public static class TestSyntaxFactory public static UnaryOperationSyntax CreateUnaryMinus(SyntaxBase operand) => new(CreateToken(TokenType.Minus), operand); - public static Token CreateToken(TokenType type) => new(type, TextSpan.Nil, ImmutableArray.Create(), ImmutableArray.Create()); + public static Token CreateToken(TokenType type) => new(type, TextSpan.Nil, [], []); - public static FreeformToken CreateToken(TokenType type, string text) => new(type, TextSpan.Nil, text, ImmutableArray.Create(), ImmutableArray.Create()); + public static FreeformToken CreateToken(TokenType type, string text) => new(type, TextSpan.Nil, text, [], []); private static IEnumerable CreateChildrenWithNewLines(IEnumerable children) { 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/ArtifactsParametersRule.cs b/src/Bicep.Core/Analyzers/Linter/Rules/ArtifactsParametersRule.cs index f4589385d62..08da2dd6470 100644 --- a/src/Bicep.Core/Analyzers/Linter/Rules/ArtifactsParametersRule.cs +++ b/src/Bicep.Core/Analyzers/Linter/Rules/ArtifactsParametersRule.cs @@ -34,14 +34,12 @@ public ArtifactsParametersRule() : base( public override string FormatMessage(params object[] values) => string.Format((string)values[0]); - override public IEnumerable AnalyzeInternal(SemanticModel model, DiagnosticLevel diagnosticLevel) + public override IEnumerable AnalyzeInternal(SemanticModel model, DiagnosticLevel diagnosticLevel) { - var diagnostics = new List(); - - diagnostics.AddRange(VerifyTopLevelParameters(model, diagnosticLevel)); - diagnostics.AddRange(VerifyModuleParameters(model, diagnosticLevel)); - - return diagnostics.ToArray(); + return [ + ..VerifyTopLevelParameters(model, diagnosticLevel), + ..VerifyModuleParameters(model, diagnosticLevel) + ]; } private IEnumerable VerifyTopLevelParameters(SemanticModel model, DiagnosticLevel diagnosticLevel) 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..5b24017f1b1 100644 --- a/src/Bicep.Core/Analyzers/Linter/Rules/MaxNumberOutputsRule.cs +++ b/src/Bicep.Core/Analyzers/Linter/Rules/MaxNumberOutputsRule.cs @@ -28,9 +28,9 @@ override public IEnumerable AnalyzeInternal(SemanticModel model, Di if (model.Root.OutputDeclarations.Count() > MaxNumber) { var firstItem = model.Root.OutputDeclarations.First(); - return new IDiagnostic[] { CreateDiagnosticForSpan(diagnosticLevel, firstItem.NameSource.Span, MaxNumber) }; + return [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..3d093d450d7 100644 --- a/src/Bicep.Core/Analyzers/Linter/Rules/MaxNumberParametersRule.cs +++ b/src/Bicep.Core/Analyzers/Linter/Rules/MaxNumberParametersRule.cs @@ -28,9 +28,9 @@ override public IEnumerable AnalyzeInternal(SemanticModel model, Di if (model.Root.ParameterDeclarations.Count() > MaxNumber) { var firstItem = model.Root.ParameterDeclarations.First(); - return new IDiagnostic[] { CreateDiagnosticForSpan(diagnosticLevel, firstItem.NameSource.Span, MaxNumber) }; + return [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..99b26d41e74 100644 --- a/src/Bicep.Core/Analyzers/Linter/Rules/MaxNumberResourcesRule.cs +++ b/src/Bicep.Core/Analyzers/Linter/Rules/MaxNumberResourcesRule.cs @@ -28,9 +28,9 @@ override public IEnumerable AnalyzeInternal(SemanticModel model, Di if (model.DeclaredResources.Length > MaxNumber) { var firstItem = model.DeclaredResources.Where(r => r.Parent is null).First(); - return new IDiagnostic[] { CreateDiagnosticForSpan(diagnosticLevel, firstItem.Symbol.NameSource.Span, MaxNumber) }; + return [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..b8806d73292 100644 --- a/src/Bicep.Core/Analyzers/Linter/Rules/MaxNumberVariablesRule.cs +++ b/src/Bicep.Core/Analyzers/Linter/Rules/MaxNumberVariablesRule.cs @@ -28,9 +28,9 @@ override public IEnumerable AnalyzeInternal(SemanticModel model, Di if (model.Root.VariableDeclarations.Count() > MaxNumber) { var firstItem = model.Root.VariableDeclarations.First(); - return new IDiagnostic[] { CreateDiagnosticForSpan(diagnosticLevel, firstItem.NameSource.Span, MaxNumber) }; + return [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..fd1d3bc2c70 100644 --- a/src/Bicep.Core/Analyzers/Linter/Rules/NoConflictingMetadataRule.cs +++ b/src/Bicep.Core/Analyzers/Linter/Rules/NoConflictingMetadataRule.cs @@ -35,10 +35,7 @@ private record MetadataPropertySetByDecorator(string MetadataPropertyName, strin private class Visitor : AstVisitor { - private static readonly ImmutableArray metadataPropertySetByDecorators = ImmutableArray.CreateRange(new MetadataPropertySetByDecorator[] - { - new(LanguageConstants.MetadataDescriptionPropertyName, SystemNamespaceType.BuiltInName, LanguageConstants.MetadataDescriptionPropertyName), - }); + 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..3948d70aa56 100644 --- a/src/Bicep.Core/Analyzers/Linter/Rules/UseProtectedSettingsForCommandToExecuteSecretsRule.cs +++ b/src/Bicep.Core/Analyzers/Linter/Rules/UseProtectedSettingsForCommandToExecuteSecretsRule.cs @@ -13,12 +13,14 @@ 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" + // 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..37967d99c93 100644 --- a/src/Bicep.Core/Analyzers/Linter/Rules/UseResourceIdFunctionsRule.cs +++ b/src/Bicep.Core/Analyzers/Linter/Rules/UseResourceIdFunctionsRule.cs @@ -50,7 +50,7 @@ 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 @@ -104,7 +104,7 @@ public Exclusion(string? regexResourceType, string? propertyName) // 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..0794a52e79c 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 [SyntaxFactory.CreateArray([])]; case StringType: - return new[] { SyntaxFactory.CreateStringLiteral(String.Empty) }; + return [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..4a6ef6f4f27 100644 --- a/src/Bicep.Core/Emit/ExpressionConverter.cs +++ b/src/Bicep.Core/Emit/ExpressionConverter.cs @@ -135,7 +135,7 @@ public LanguageExpression ConvertExpression(Expression expression) var listArgs = listFunction.Parameters.Length switch { - 0 => new Expression[] { resourceIdExpression, apiVersionExpression, }, + 0 => [resourceIdExpression, apiVersionExpression,], _ => new Expression[] { resourceIdExpression, }.Concat(listFunction.Parameters), }; @@ -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); @@ -240,7 +240,7 @@ private LanguageExpression ConvertAccessExpression(AccessExpression expression, // - conditional outputs (where the accessed property will be omitted from the `outputs` object) // - outputs with a null value (where the accessed property will be present in the `outputs` object, but its `value` property will be omitted) @base = CreateFunction("tryGet", @base.AsEnumerable().Concat(properties)); - properties = new[] { new JTokenExpression("value") }; + properties = [new JTokenExpression("value")]; } else { @@ -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), @@ -861,11 +857,11 @@ public LanguageExpression GenerateManagementGroupResourceId(SyntaxBase managemen if (fullyQualified) { - return GenerateTenantResourceId(managementGroupType, new[] { managementGroupName }); + return GenerateTenantResourceId(managementGroupType, [managementGroupName]); } else { - return GenerateUnqualifiedResourceId(managementGroupType, new[] { managementGroupName }); + return GenerateUnqualifiedResourceId(managementGroupType, [managementGroupName]); } } @@ -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..3e4bd059764 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")]; } } }; @@ -329,27 +329,27 @@ public static Expression ConvertModuleParameter(Expression parameter) case TernaryExpression ternary: return new TernaryExpression(ternary.SourceSyntax, ternary.Condition, ConvertModuleParameter(ternary.True), ConvertModuleParameter(ternary.False)); default: - return ExpressionFactory.CreateObject(new[] { + return ExpressionFactory.CreateObject([ ExpressionFactory.CreateObjectProperty("value", parameter) - }, parameter.SourceSyntax); + ], parameter.SourceSyntax); } } private static Expression ConvertModuleParameterGetSecret(ResourceFunctionCallExpression functionCall) { var properties = new List(); - properties.Add(ExpressionFactory.CreateObjectProperty("keyVault", ExpressionFactory.CreateObject(new[] { + properties.Add(ExpressionFactory.CreateObjectProperty("keyVault", ExpressionFactory.CreateObject([ ExpressionFactory.CreateObjectProperty("id", new PropertyAccessExpression(functionCall.Resource.SourceSyntax, functionCall.Resource, "id", AccessExpressionFlags.None)), - }, functionCall.SourceSyntax))); + ], functionCall.SourceSyntax))); properties.Add(ExpressionFactory.CreateObjectProperty("secretName", functionCall.Parameters[0])); if (functionCall.Parameters.Length > 1) { properties.Add(ExpressionFactory.CreateObjectProperty("secretVersion", functionCall.Parameters[1])); } - return ExpressionFactory.CreateObject(new[] { + return ExpressionFactory.CreateObject([ ExpressionFactory.CreateObjectProperty("reference", ExpressionFactory.CreateObject(properties)) - }, functionCall.SourceSyntax); + ], functionCall.SourceSyntax); } public void EmitProperty(ObjectPropertyExpression property) diff --git a/src/Bicep.Core/Emit/InlineDependencyVisitor.cs b/src/Bicep.Core/Emit/InlineDependencyVisitor.cs index 3fc47f899ad..f431bb62a2a 100644 --- a/src/Bicep.Core/Emit/InlineDependencyVisitor.cs +++ b/src/Bicep.Core/Emit/InlineDependencyVisitor.cs @@ -38,8 +38,8 @@ private InlineDependencyVisitor(SemanticModel model, VariableDeclarationSyntax? if (targetVariable is not null) { - // the functionality - this.currentStack = ImmutableStack.Create(); + // the functionality + 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 e26a06735e3..700865294ed 100644 --- a/src/Bicep.Core/Emit/TemplateWriter.cs +++ b/src/Bicep.Core/Emit/TemplateWriter.cs @@ -392,28 +392,25 @@ ResourceDerivedTypeExpression or // literals StringLiteralTypeExpression @string => ExpressionFactory.CreateObject( - new[] - { + [ TypeProperty(LanguageConstants.TypeNameString, @string.SourceSyntax), AllowedValuesProperty(SingleElementArray(ExpressionFactory.CreateStringLiteral(@string.Value, @string.SourceSyntax)), @string.SourceSyntax), - }, + ], @string.SourceSyntax), IntegerLiteralTypeExpression @int => ExpressionFactory.CreateObject( - new[] - { + [ TypeProperty(LanguageConstants.TypeNameInt, @int.SourceSyntax), AllowedValuesProperty(SingleElementArray(ExpressionFactory.CreateIntegerLiteral(@int.Value, @int.SourceSyntax)), @int.SourceSyntax), - }, + ], @int.SourceSyntax), BooleanLiteralTypeExpression @bool => ExpressionFactory.CreateObject( - new[] - { + [ TypeProperty(LanguageConstants.TypeNameBool, @bool.SourceSyntax), AllowedValuesProperty(SingleElementArray(ExpressionFactory.CreateBooleanLiteral(@bool.Value, @bool.SourceSyntax)), @bool.SourceSyntax), - }, + ], @bool.SourceSyntax), UnionTypeExpression unionType => GetTypePropertiesForUnionTypeExpression(unionType), @@ -462,11 +459,11 @@ 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[] - { + => ExpressionFactory.CreateObject( + [ TypeProperty(GetNonLiteralTypeName(DerivedType), sourceSyntax), ExpressionFactory.CreateObjectProperty(LanguageConstants.ParameterMetadataPropertyName, ExpressionFactory.CreateObject( @@ -479,7 +476,7 @@ public ObjectExpression GetTypePropertiesForResolvedReferenceExpression(SyntaxBa sourceSyntax).AsEnumerable(), sourceSyntax), sourceSyntax), - }); + ]); } private record ResolvedInternalReference(ImmutableArray PointerSegments, TypeExpression Declaration) : ITypeReferenceExpressionResolution @@ -495,7 +492,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) { @@ -691,8 +688,8 @@ private static ObjectExpression GetTypePropertiesForResourceType(ResourceTypeExp { var typeString = expression.ExpressedResourceType.TypeReference.FormatName(); - return ExpressionFactory.CreateObject(new[] - { + return ExpressionFactory.CreateObject( + [ TypeProperty(LanguageConstants.TypeNameString, expression.SourceSyntax), ExpressionFactory.CreateObjectProperty(LanguageConstants.ParameterMetadataPropertyName, ExpressionFactory.CreateObject( @@ -701,7 +698,7 @@ private static ObjectExpression GetTypePropertiesForResourceType(ResourceTypeExp expression.SourceSyntax).AsEnumerable(), expression.SourceSyntax), expression.SourceSyntax), - }); + ]); } private ObjectExpression GetTypePropertiesForArrayType(ArrayTypeExpression expression) @@ -760,8 +757,8 @@ private ObjectExpression GetTypePropertiesForObjectType(ObjectTypeExpression exp return ExpressionFactory.CreateObject(properties, expression.SourceSyntax); } - private ObjectExpression GetTypePropertiesForTupleType(TupleTypeExpression expression) => ExpressionFactory.CreateObject(new[] - { + private ObjectExpression GetTypePropertiesForTupleType(TupleTypeExpression expression) => ExpressionFactory.CreateObject( + [ TypeProperty(LanguageConstants.ArrayType, expression.SourceSyntax), ExpressionFactory.CreateObjectProperty("prefixItems", ExpressionFactory.CreateArray( @@ -769,7 +766,7 @@ private ObjectExpression GetTypePropertiesForTupleType(TupleTypeExpression expre expression.SourceSyntax), expression.SourceSyntax), ExpressionFactory.CreateObjectProperty("items", ExpressionFactory.CreateBooleanLiteral(false), expression.SourceSyntax), - }); + ]); private ObjectExpression GetTypePropertiesForUnionTypeExpression(UnionTypeExpression expression) { @@ -1138,7 +1135,7 @@ private void EmitResource(ExpressionEmitter emitter, DeclaredResourceExpression // Since we don't want to be mutating the body of the original ObjectSyntax, we create an placeholder body in place // and emit its properties to merge decorator properties. - foreach (var property in ApplyDescription(resource, ExpressionFactory.CreateObject(ImmutableArray.Empty)).Properties) + foreach (var property in ApplyDescription(resource, ExpressionFactory.CreateObject([])).Properties) { emitter.EmitProperty(property); } @@ -1223,10 +1220,10 @@ private void EmitModuleParameters(ExpressionEmitter emitter, DeclaredModuleExpre private void EmitModuleForLocalDeploy(PositionTrackingJsonTextWriter jsonWriter, DeclaredModuleExpression module, ExpressionEmitter emitter) { - emitter.EmitObject(() => + emitter.EmitObject(() => { emitter.EmitProperty("import", "az0synthesized"); - + var body = module.Body; if (body is ForLoopExpression forLoop) { @@ -1261,7 +1258,7 @@ private void EmitModuleForLocalDeploy(PositionTrackingJsonTextWriter jsonWriter, // Since we don't want to be mutating the body of the original ObjectSyntax, we create an placeholder body in place // and emit its properties to merge decorator properties. - foreach (var property in ApplyDescription(module, ExpressionFactory.CreateObject(ImmutableArray.Empty)).Properties) + foreach (var property in ApplyDescription(module, ExpressionFactory.CreateObject([])).Properties) { emitter.EmitProperty(property); } @@ -1308,7 +1305,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 +1314,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)); } @@ -1356,7 +1353,7 @@ private void EmitModule(PositionTrackingJsonTextWriter jsonWriter, DeclaredModul // Since we don't want to be mutating the body of the original ObjectSyntax, we create an placeholder body in place // and emit its properties to merge decorator properties. - foreach (var property in ApplyDescription(module, ExpressionFactory.CreateObject(ImmutableArray.Empty)).Properties) + foreach (var property in ApplyDescription(module, ExpressionFactory.CreateObject([])).Properties) { emitter.EmitProperty(property); } 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..4bad9f38615 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() { @@ -318,14 +318,13 @@ public static TypeSymbol CreateModuleType(IFeatureProvider features, IEnumerable var moduleBody = new ObjectType( typeName, TypeSymbolValidationFlags.Default, - new[] - { + [ new TypeProperty(ModuleNamePropertyName, LanguageConstants.String, nameRequirednessFlags | TypePropertyFlags.DeployTimeConstant | TypePropertyFlags.ReadableAtDeployTime | TypePropertyFlags.LoopVariant), new TypeProperty(ResourceScopePropertyName, CreateResourceScopeReference(moduleScope), scopePropertyFlags), new TypeProperty(ModuleParamsPropertyName, paramsType, paramsRequiredFlag | TypePropertyFlags.WriteOnly), new TypeProperty(ModuleOutputsPropertyName, outputsType, TypePropertyFlags.ReadOnly), new TypeProperty(ResourceDependsOnPropertyName, ResourceOrResourceCollectionRefArray, TypePropertyFlags.WriteOnly | TypePropertyFlags.DisallowAny), - }, + ], null); return new ModuleType(typeName, moduleScope, moduleBody); 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/Modules/TemplateSpecModuleReference.cs b/src/Bicep.Core/Modules/TemplateSpecModuleReference.cs index 00593665524..538f3cab097 100644 --- a/src/Bicep.Core/Modules/TemplateSpecModuleReference.cs +++ b/src/Bicep.Core/Modules/TemplateSpecModuleReference.cs @@ -15,7 +15,7 @@ public class TemplateSpecModuleReference : ArtifactReference private static readonly UriTemplate TemplateSpecUriTemplate = new("{subscriptionId}/{resourceGroupName}/{templateSpecName}:{version}"); - private static readonly HashSet ResourceGroupNameAllowedCharacterSet = new(new[] { '-', '_', '.', '(', ')' }); + private static readonly HashSet ResourceGroupNameAllowedCharacterSet = new(['-', '_', '.', '(', ')']); private static readonly Regex ResourceNameRegex = new(@"^[-\w\.\(\)]{0,89}[-\w\(\)]$", RegexOptions.Compiled | RegexOptions.CultureInvariant); diff --git a/src/Bicep.Core/Parsing/BaseParser.cs b/src/Bicep.Core/Parsing/BaseParser.cs index 244f1e46f85..6c6d2292d10 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); @@ -505,7 +505,7 @@ protected IEnumerable HandleArrayOrObjectElements(TokenType closingT if (Check(closingTokenType)) { // always allow a close on the same line - return ImmutableArray.Empty; + return []; } var itemsOrTokens = new List(); @@ -556,7 +556,7 @@ private IEnumerable HandleFunctionElements(TokenType closingTokenTyp if (Check(closingTokenType)) { // always allow a close on the same line - return ImmutableArray.Empty; + return []; } var itemsOrTokens = new List(); @@ -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); } @@ -889,7 +889,7 @@ private SyntaxBase MemberExpression(ExpressionFlags expressionFlags) { functionCall = ( new IdentifierSyntax(new SkippedTriviaSyntax(TextSpan.Between(safeAccessMarker.Span, identifier.Span), - new SyntaxBase[] { safeAccessMarker, identifier }, + [safeAccessMarker, identifier], DiagnosticBuilder.ForPosition(safeAccessMarker).SafeDereferenceNotPermittedOnInstanceFunctions().AsEnumerable())), functionCall.OpenParen, functionCall.ArgumentNodes, @@ -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,8 +1350,8 @@ 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(); - return new SkippedTriviaSyntax(span, ImmutableArray.Empty, errors); + var errors = errorFunc is null ? [] : errorFunc(DiagnosticBuilder.ForPosition(span)).AsEnumerable(); + return new SkippedTriviaSyntax(span, [], errors); } private void Synchronize(bool consumeTerminator, params TokenType[] expectedTypes) 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..7a51d69f5c8 100644 --- a/src/Bicep.Core/Semantics/DeclarationVisitor.cs +++ b/src/Bicep.Core/Semantics/DeclarationVisitor.cs @@ -71,8 +71,8 @@ public override void VisitProgramSyntax(ProgramSyntax syntax) string.Empty, syntax, syntax, - ImmutableArray.Empty, - ImmutableArray.Empty, + [], + [], ScopeResolution.GlobalsOnly); this.PushScope(scope); @@ -130,7 +130,7 @@ public override void VisitResourceDeclarationSyntax(ResourceDeclarationSyntax sy // and the actual object body (for-loop). That's OK, in that case, this scope will // be empty and we'll use the `for` scope for lookups. var bindingSyntax = syntax.Value is IfConditionSyntax ifConditionSyntax ? ifConditionSyntax.Body : syntax.Value; - var scope = new LocalScope(string.Empty, syntax, bindingSyntax, ImmutableArray.Empty, ImmutableArray.Empty, ScopeResolution.InheritAll); + var scope = new LocalScope(string.Empty, syntax, bindingSyntax, [], [], ScopeResolution.InheritAll); this.PushScope(scope); base.VisitResourceDeclarationSyntax(syntax); @@ -193,7 +193,7 @@ public override void VisitParameterAssignmentSyntax(ParameterAssignmentSyntax sy public override void VisitLambdaSyntax(LambdaSyntax syntax) { // create new scope without any descendants - var scope = new LocalScope(string.Empty, syntax, syntax.Body, ImmutableArray.Empty, ImmutableArray.Empty, ScopeResolution.InheritAll); + var scope = new LocalScope(string.Empty, syntax, syntax.Body, [], [], ScopeResolution.InheritAll); this.PushScope(scope); /* @@ -215,7 +215,7 @@ public override void VisitLambdaSyntax(LambdaSyntax syntax) public override void VisitTypedLambdaSyntax(TypedLambdaSyntax syntax) { // create new scope without any descendants - var scope = new LocalScope(string.Empty, syntax, syntax.Body, ImmutableArray.Empty, ImmutableArray.Empty, ScopeResolution.InheritFunctionsOnly); + var scope = new LocalScope(string.Empty, syntax, syntax.Body, [], [], ScopeResolution.InheritFunctionsOnly); this.PushScope(scope); /* @@ -237,7 +237,7 @@ public override void VisitTypedLambdaSyntax(TypedLambdaSyntax syntax) public override void VisitForSyntax(ForSyntax syntax) { // create new scope without any descendants - var scope = new LocalScope(string.Empty, syntax, syntax.Body, ImmutableArray.Empty, ImmutableArray.Empty, ScopeResolution.InheritAll); + var scope = new LocalScope(string.Empty, syntax, syntax.Body, [], [], ScopeResolution.InheritAll); this.PushScope(scope); /* @@ -295,18 +295,18 @@ 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 +317,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 +330,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..04936a47b52 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); @@ -98,7 +98,7 @@ public override void VisitResourceAccessSyntax(ResourceAccessSyntax syntax) if (resourceBody == null) { // If we have no body then there will be nothing to reference. - var error = new ErrorSymbol(DiagnosticBuilder.ForPosition(syntax.ResourceName).NestedResourceNotFound(resourceSymbol.Name, syntax.ResourceName.IdentifierName, nestedResourceNames: new[] { "(none)", })); + var error = new ErrorSymbol(DiagnosticBuilder.ForPosition(syntax.ResourceName).NestedResourceNotFound(resourceSymbol.Name, syntax.ResourceName.IdentifierName, nestedResourceNames: ["(none)",])); this.bindings.Add(syntax, error); return; } diff --git a/src/Bicep.Core/Semantics/Namespaces/AzNamespaceType.cs b/src/Bicep.Core/Semantics/Namespaces/AzNamespaceType.cs index ee2fa5aa5e5..c8d7611fb79 100644 --- a/src/Bicep.Core/Semantics/Namespaces/AzNamespaceType.cs +++ b/src/Bicep.Core/Semantics/Namespaces/AzNamespaceType.cs @@ -52,70 +52,70 @@ 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[] - { + => new(new TenantScopeType(functionCall.Arguments, + [ new TypeProperty("tenantId", LanguageConstants.String), new TypeProperty("country", LanguageConstants.String), new TypeProperty("countryCode", LanguageConstants.String), new TypeProperty("displayName", LanguageConstants.String), - })); + ])); private static FunctionResult GetManagementGroupReturnResult(SemanticModel model, IDiagnosticWriter diagnostics, FunctionCallSyntaxBase functionCall, ImmutableArray argumentTypes) { - var summary = new ObjectType("summaryProperties", TypeSymbolValidationFlags.Default, new[] - { + var summary = new ObjectType("summaryProperties", TypeSymbolValidationFlags.Default, + [ new TypeProperty("id", LanguageConstants.String), new TypeProperty("name", LanguageConstants.String), new TypeProperty("type", LanguageConstants.String), - }, null); + ], null); - var details = new ObjectType("detailsProperties", TypeSymbolValidationFlags.Default, new[] - { + var details = new ObjectType("detailsProperties", TypeSymbolValidationFlags.Default, + [ new TypeProperty("version", LanguageConstants.String), new TypeProperty("updatedTime", LanguageConstants.String), new TypeProperty("updatedBy", LanguageConstants.String), new TypeProperty("parent", summary) - }, null); + ], null); - var properties = new ObjectType("properties", TypeSymbolValidationFlags.Default, new[] - { + var properties = new ObjectType("properties", TypeSymbolValidationFlags.Default, + [ new TypeProperty("tenantId", LanguageConstants.String), new TypeProperty("displayName", LanguageConstants.String), new TypeProperty("details", details) - }, null); + ], null); - return new(new ManagementGroupScopeType(functionCall.Arguments, new[] - { + return new(new ManagementGroupScopeType(functionCall.Arguments, + [ new TypeProperty("id", LanguageConstants.String), new TypeProperty("name", LanguageConstants.String), new TypeProperty("type", LanguageConstants.String), new TypeProperty("properties", properties), - })); + ])); } private static FunctionResult GetResourceGroupReturnResult(SemanticModel model, IDiagnosticWriter diagnostics, FunctionCallSyntaxBase functionCall, ImmutableArray argumentTypes) { - var properties = new ObjectType("properties", TypeSymbolValidationFlags.Default, new[] - { + var properties = new ObjectType("properties", TypeSymbolValidationFlags.Default, + [ new TypeProperty("provisioningState", LanguageConstants.String), - }, null); + ], null); - return new(new ResourceGroupScopeType(functionCall.Arguments, new[] - { + return new(new ResourceGroupScopeType(functionCall.Arguments, + [ new TypeProperty("id", LanguageConstants.String), new TypeProperty("name", LanguageConstants.String), new TypeProperty("type", LanguageConstants.String), @@ -123,53 +123,53 @@ private static FunctionResult GetResourceGroupReturnResult(SemanticModel model, new TypeProperty("managedBy", LanguageConstants.String), new TypeProperty("tags", AzResourceTypeProvider.Tags), new TypeProperty("properties", properties), - })); + ])); } private static FunctionResult GetSubscriptionReturnResult(SemanticModel model, IDiagnosticWriter diagnostics, FunctionCallSyntaxBase functionCall, ImmutableArray argumentTypes) { - return new(new SubscriptionScopeType(functionCall.Arguments, new[] - { + return new(new SubscriptionScopeType(functionCall.Arguments, + [ new TypeProperty("id", LanguageConstants.String), new TypeProperty("subscriptionId", LanguageConstants.String), new TypeProperty("tenantId", LanguageConstants.String), new TypeProperty("displayName", LanguageConstants.String), - })); + ])); } private static ObjectType GetProvidersSingleResourceReturnType() { // from https://docs.microsoft.com/en-us/azure/azure-resource-manager/templates/template-functions-resource?tabs=json#providers - return new ObjectType("ProviderResource", TypeSymbolValidationFlags.Default, new[] - { + return new ObjectType("ProviderResource", TypeSymbolValidationFlags.Default, + [ new TypeProperty("resourceType", LanguageConstants.String), new TypeProperty("locations", new TypedArrayType(LanguageConstants.String, TypeSymbolValidationFlags.Default)), new TypeProperty("apiVersions", new TypedArrayType(LanguageConstants.String, TypeSymbolValidationFlags.Default)), - }, null); + ], null); } private static ObjectType GetProvidersSingleProviderReturnType() { // from https://docs.microsoft.com/en-us/azure/azure-resource-manager/templates/template-functions-resource?tabs=json#providers - return new ObjectType("Provider", TypeSymbolValidationFlags.Default, new[] - { + return new ObjectType("Provider", TypeSymbolValidationFlags.Default, + [ new TypeProperty("namespace", LanguageConstants.String), new TypeProperty("resourceTypes", new TypedArrayType(GetProvidersSingleResourceReturnType(), TypeSymbolValidationFlags.Default)), - }, null); + ], null); } private static ObjectType GetEnvironmentReturnType() { - return new ObjectType("environment", TypeSymbolValidationFlags.Default, new[] - { + return new ObjectType("environment", TypeSymbolValidationFlags.Default, + [ new TypeProperty("activeDirectoryDataLake", LanguageConstants.String), - new TypeProperty("authentication", new ObjectType("authenticationProperties", TypeSymbolValidationFlags.Default, new [] - { + new TypeProperty("authentication", new ObjectType("authenticationProperties", TypeSymbolValidationFlags.Default, + [ new TypeProperty("audiences", new TypedArrayType(LanguageConstants.String, TypeSymbolValidationFlags.Default)), new TypeProperty("identityProvider", LanguageConstants.String), new TypeProperty("loginEndpoint", LanguageConstants.String), new TypeProperty("tenant", LanguageConstants.String), - }, null)), + ], null)), new TypeProperty("batch", LanguageConstants.String), new TypeProperty("gallery", LanguageConstants.String), new TypeProperty("graph", LanguageConstants.String), @@ -179,8 +179,8 @@ private static ObjectType GetEnvironmentReturnType() new TypeProperty("portal", LanguageConstants.String), new TypeProperty("resourceManager", LanguageConstants.String), new TypeProperty("sqlManagement", LanguageConstants.String), - new TypeProperty("suffixes", new ObjectType("suffixesProperties", TypeSymbolValidationFlags.Default, new [] - { + new TypeProperty("suffixes", new ObjectType("suffixesProperties", TypeSymbolValidationFlags.Default, + [ new TypeProperty("acrLoginServer", LanguageConstants.String), new TypeProperty("azureDatalakeAnalyticsCatalogAndJob", LanguageConstants.String), new TypeProperty("azureDatalakeStoreFileSystem", LanguageConstants.String), @@ -188,9 +188,9 @@ private static ObjectType GetEnvironmentReturnType() new TypeProperty("keyvaultDns", LanguageConstants.String), new TypeProperty("sqlServerHostname", LanguageConstants.String), new TypeProperty("storage", LanguageConstants.String), - }, null)), + ], null)), new TypeProperty("vmImageAliasDoc", LanguageConstants.String), - }, null); + ], null); } private static ObjectType GetDeploymentReturnType(bool resourceGroupScope) @@ -199,22 +199,22 @@ private static ObjectType GetDeploymentReturnType(bool resourceGroupScope) // We're going to omit them and only include what is truly necessary. If we get feature requests to expose more properties, we should discuss this further. // Properties such as 'template', 'templateHash', 'parameters' depend on the codegen, and feel like they could be fragile. // template.contentVersion was requested in issue #3114 - IEnumerable properties = new[] - { + IEnumerable properties = + [ new TypeProperty("name", LanguageConstants.String), - new TypeProperty("properties", new ObjectType("properties", TypeSymbolValidationFlags.Default, new [] - { - new TypeProperty("template", new ObjectType("templateProperties", TypeSymbolValidationFlags.Default, new [] - { + new TypeProperty("properties", new ObjectType("properties", TypeSymbolValidationFlags.Default, + [ + new TypeProperty("template", new ObjectType("templateProperties", TypeSymbolValidationFlags.Default, + [ new TypeProperty("contentVersion", LanguageConstants.String) - }, null)), - new TypeProperty("templateLink", new ObjectType("templateLinkProperties", TypeSymbolValidationFlags.Default, new [] - { + ], null)), + new TypeProperty("templateLink", new ObjectType("templateLinkProperties", TypeSymbolValidationFlags.Default, + [ new TypeProperty("id", LanguageConstants.String), new TypeProperty("uri", LanguageConstants.String), - }, null)) - }, null)), - }; + ], null)) + ], null)), + ]; if (!resourceGroupScope) { @@ -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") @@ -352,7 +352,7 @@ static IEnumerable GetParamsFilePermittedOverloads() secretVersion = sv; } - var kvResourceId = ResourceGroupLevelResourceId.Create(subscriptionId, resourceGroupName, "Microsoft.KeyVault", new[] { "vaults" }, new[] { keyVaultName }); + var kvResourceId = ResourceGroupLevelResourceId.Create(subscriptionId, resourceGroupName, "Microsoft.KeyVault", ["vaults"], [keyVaultName]); return new(LanguageConstants.SecureString, new ParameterKeyVaultReferenceExpression(func, kvResourceId.FullyQualifiedId, secretName, secretVersion)); }, LanguageConstants.SecureString) .WithRequiredParameter("subscriptionId", LanguageConstants.String, "Id of the Subscription that has the target KeyVault") @@ -531,10 +531,10 @@ public static NamespaceType Create(string? aliasName, ResourceScope scope, IReso ConfigurationType: null, ArmTemplateProviderName: "AzureResourceManager", ArmTemplateProviderVersion: EmbeddedAzProviderVersion), - ImmutableArray.Empty, + [], Overloads.Where(x => x.IsVisible(scope, sourceFileKind)).Select(x => x.Value), - ImmutableArray.Empty, - ImmutableArray.Empty, + [], + [], resourceTypeProvider); } } diff --git a/src/Bicep.Core/Semantics/Namespaces/K8sNamespaceType.cs b/src/Bicep.Core/Semantics/Namespaces/K8sNamespaceType.cs index cd540d9d09d..3e6e254ecd2 100644 --- a/src/Bicep.Core/Semantics/Namespaces/K8sNamespaceType.cs +++ b/src/Bicep.Core/Semantics/Namespaces/K8sNamespaceType.cs @@ -25,12 +25,12 @@ private static readonly Lazy TypeProviderLazy private static ObjectType GetConfigurationType() { - return new ObjectType("configuration", TypeSymbolValidationFlags.Default, new[] - { + return new ObjectType("configuration", TypeSymbolValidationFlags.Default, + [ new TypeProperty("namespace", LanguageConstants.String, TypePropertyFlags.Required, "The default Kubernetes namespace to deploy resources to."), new TypeProperty("kubeConfig", LanguageConstants.String, TypePropertyFlags.Required, "The Kubernetes configuration file, base-64 encoded."), new TypeProperty("context", LanguageConstants.String), - }, null); + ], null); } public static NamespaceType Create(string aliasName) @@ -38,10 +38,10 @@ public static NamespaceType Create(string aliasName) return new NamespaceType( aliasName, Settings, - ImmutableArray.Empty, - ImmutableArray.Empty, - ImmutableArray.Empty, - ImmutableArray.Empty, + [], + [], + [], + [], TypeProviderLazy.Value); } } diff --git a/src/Bicep.Core/Semantics/Namespaces/MicrosoftGraphNamespaceType.cs b/src/Bicep.Core/Semantics/Namespaces/MicrosoftGraphNamespaceType.cs index 6efa9dfb87d..018823fbbbb 100644 --- a/src/Bicep.Core/Semantics/Namespaces/MicrosoftGraphNamespaceType.cs +++ b/src/Bicep.Core/Semantics/Namespaces/MicrosoftGraphNamespaceType.cs @@ -26,10 +26,10 @@ public static NamespaceType Create(string aliasName) return new NamespaceType( aliasName, Settings, - ImmutableArray.Empty, - ImmutableArray.Empty, - ImmutableArray.Empty, - ImmutableArray.Empty, + [], + [], + [], + [], TypeProviderLazy.Value); } } 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 7a641024c54..eab69d146c7 100644 --- a/src/Bicep.Core/Semantics/Namespaces/SystemNamespaceType.cs +++ b/src/Bicep.Core/Semantics/Namespaces/SystemNamespaceType.cs @@ -427,7 +427,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 @@ -1077,15 +1077,15 @@ static IEnumerable GetParamsFilePermittedOverloads() private static ObjectType GetParseCidrReturnType() { - return new ObjectType("parseCidr", TypeSymbolValidationFlags.Default, new[] - { + return new ObjectType("parseCidr", TypeSymbolValidationFlags.Default, + [ new TypeProperty("network", LanguageConstants.String), new TypeProperty("netmask", LanguageConstants.String), new TypeProperty("broadcast", LanguageConstants.String), new TypeProperty("firstUsable", LanguageConstants.String), new TypeProperty("lastUsable", LanguageConstants.String), new TypeProperty("cidr", TypeFactory.CreateIntegerType(0, 255)), - }, null); + ], null); } private static ResultWithDiagnostic TryGetFileUriWithDiagnostics(IBinder binder, string filePath) @@ -1173,7 +1173,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) @@ -1306,7 +1306,16 @@ 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 { @@ -1323,7 +1332,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}"), @@ -1336,10 +1345,10 @@ private static TypeSymbol GetItemsReturnType(TypeSymbol keyType, TypeSymbol valu new ObjectType( "object", TypeSymbolValidationFlags.Default, - new[] { + [ new TypeProperty("key", keyType, description: "The key of the object property being iterated over."), new TypeProperty("value", valueType, description: "The value of the object property being iterated over."), - }, + ], null), TypeSymbolValidationFlags.Default); @@ -1442,8 +1451,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. @@ -1469,7 +1478,7 @@ private static FunctionResult JsonResultBuilder(SemanticModel model, IDiagnostic BannedFunction.CreateForOperator("and", "&&"), BannedFunction.CreateForOperator("or", "||"), BannedFunction.CreateForOperator("coalesce", "??") - }.ToImmutableArray(); + ]; private static IEnumerable> GetSystemDecorators() { @@ -1887,9 +1896,9 @@ static IEnumerable GetResourceDerivedTypesTypeProperties() { yield return new(LanguageConstants.TypeNameResource, new TypeTemplate(LanguageConstants.TypeNameResource, - ImmutableArray.Create(new TypeParameter("ResourceTypeIdentifier", + [new TypeParameter("ResourceTypeIdentifier", "A string of the format '@' that identifies the kind of resource whose body type definition is to be used.", - LanguageConstants.StringResourceIdentifier)), + 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/Namespaces/ThirdPartyNamespaceType.cs b/src/Bicep.Core/Semantics/Namespaces/ThirdPartyNamespaceType.cs index 0e590326df7..469955cd91c 100644 --- a/src/Bicep.Core/Semantics/Namespaces/ThirdPartyNamespaceType.cs +++ b/src/Bicep.Core/Semantics/Namespaces/ThirdPartyNamespaceType.cs @@ -31,10 +31,10 @@ public static NamespaceType Create(string? aliasName, IResourceTypeProvider reso ConfigurationType: namespaceConfig.ConfigurationObject, ArmTemplateProviderName: namespaceConfig.Name, ArmTemplateProviderVersion: namespaceConfig.Version), - ImmutableArray.Empty, - ImmutableArray.Empty, - ImmutableArray.Empty, - ImmutableArray.Empty, + [], + [], + [], + [], resourceTypeProvider, artifact); } 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..8d5e316599c 100644 --- a/src/Bicep.Core/SourceCode/SourceArchive.cs +++ b/src/Bicep.Core/SourceCode/SourceArchive.cs @@ -64,7 +64,7 @@ public static class SourceKind private static readonly ImmutableHashSet PathCharsToAvoid = Path.GetInvalidFileNameChars() .Union(Path.GetInvalidPathChars()) - .Union(new char[] { '"', '*', ':', '&', '<', '>', '?', '\\', '/', '|', '+', '[', ']', '#' }) + .Union(['"', '*', ':', '&', '<', '>', '?', '\\', '/', '|', '+', '[', ']', '#']) .Where(ch => ch != '/') .ToImmutableHashSet(); @@ -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/SkippedTriviaSyntax.cs b/src/Bicep.Core/Syntax/SkippedTriviaSyntax.cs index 375e39abcad..f0ab6196e26 100644 --- a/src/Bicep.Core/Syntax/SkippedTriviaSyntax.cs +++ b/src/Bicep.Core/Syntax/SkippedTriviaSyntax.cs @@ -9,7 +9,7 @@ namespace Bicep.Core.Syntax public class SkippedTriviaSyntax : SyntaxBase { public SkippedTriviaSyntax(TextSpan span, IEnumerable elements) - : this(span, elements, ImmutableArray.Empty) + : this(span, elements, []) { } diff --git a/src/Bicep.Core/Syntax/SyntaxFactory.cs b/src/Bicep.Core/Syntax/SyntaxFactory.cs index cc176a705fe..f6ca0758655 100644 --- a/src/Bicep.Core/Syntax/SyntaxFactory.cs +++ b/src/Bicep.Core/Syntax/SyntaxFactory.cs @@ -8,12 +8,11 @@ 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 IEnumerable SingleSpaceTrivia = [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) { @@ -139,11 +138,11 @@ public static ForSyntax CreateRangedForSyntax(string indexIdentifier, SyntaxBase var rangeSyntax = new FunctionCallSyntax( CreateIdentifier("range"), LeftParenToken, - new SyntaxBase[] { + [ new FunctionArgumentSyntax(new IntegerLiteralSyntax(CreateFreeformToken(TokenType.Integer, "0"), 0)), CommaToken, new FunctionArgumentSyntax(count), - }, + ], RightParenToken); return CreateForSyntax(indexIdentifier, rangeSyntax, body); @@ -251,7 +250,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) @@ -280,9 +279,9 @@ public static StringSyntax CreateInterpolatedKey(SyntaxBase syntax) var endToken = CreateStringInterpolationToken(false, true, ""); return new StringSyntax( - new[] { startToken, endToken }, + [startToken, endToken], syntax.AsEnumerable(), - new[] { "", "" }); + ["", ""]); } public static Token CreateStringInterpolationToken(bool isStart, bool isEnd, string value) @@ -345,7 +344,7 @@ public static LambdaSyntax CreateLambdaSyntax(IReadOnlyList parameterNam return new LambdaSyntax( variableBlock, SyntaxFactory.ArrowToken, - ImmutableArray.Empty, + [], functionExpression); } diff --git a/src/Bicep.Core/Syntax/TargetScopeSyntax.cs b/src/Bicep.Core/Syntax/TargetScopeSyntax.cs index 772cf96a50f..0ae565fc201 100644 --- a/src/Bicep.Core/Syntax/TargetScopeSyntax.cs +++ b/src/Bicep.Core/Syntax/TargetScopeSyntax.cs @@ -10,7 +10,7 @@ namespace Bicep.Core.Syntax public class TargetScopeSyntax : StatementSyntax, ITopLevelDeclarationSyntax { public TargetScopeSyntax(Token keyword, SyntaxBase assignment, SyntaxBase value) - : base(ImmutableArray.Empty) + : base([]) { AssertKeyword(keyword, nameof(keyword), LanguageConstants.TargetScopeKeyword); AssertSyntaxType(assignment, nameof(assignment), typeof(Token), typeof(SkippedTriviaSyntax)); 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/DeclaredTypeManager.cs b/src/Bicep.Core/TypeSystem/DeclaredTypeManager.cs index 8d98b51b2be..08461cf1953 100644 --- a/src/Bicep.Core/TypeSystem/DeclaredTypeManager.cs +++ b/src/Bicep.Core/TypeSystem/DeclaredTypeManager.cs @@ -2075,10 +2075,9 @@ private TypeSymbol CreateTestType(IEnumerable paramsProperties, st var testBody = new ObjectType( typeName, TypeSymbolValidationFlags.Default, - new[] - { + [ new TypeProperty(LanguageConstants.TestParamsPropertyName, paramsType, paramsRequiredFlag | TypePropertyFlags.WriteOnly), - }, + ], null); return new TestType(typeName, testBody); 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/FunctionResolver.cs b/src/Bicep.Core/TypeSystem/FunctionResolver.cs index c169b3e3372..aff72f39939 100644 --- a/src/Bicep.Core/TypeSystem/FunctionResolver.cs +++ b/src/Bicep.Core/TypeSystem/FunctionResolver.cs @@ -106,7 +106,7 @@ public static IEnumerable GetMatches( { case FunctionMatchResult.Match: // for full match, just return the first one - return new[] { overload }; + return [overload]; case FunctionMatchResult.PotentialMatch: potentialMatchOverloads.Add(overload); diff --git a/src/Bicep.Core/TypeSystem/OperationReturnTypeEvaluator.cs b/src/Bicep.Core/TypeSystem/OperationReturnTypeEvaluator.cs index 7dea2da946a..5120a1be315 100644 --- a/src/Bicep.Core/TypeSystem/OperationReturnTypeEvaluator.cs +++ b/src/Bicep.Core/TypeSystem/OperationReturnTypeEvaluator.cs @@ -11,14 +11,17 @@ namespace Bicep.Core.TypeSystem; public static class OperationReturnTypeEvaluator { - private static readonly ImmutableArray unaryEvaluators = ImmutableArray.Create( + private static readonly ImmutableArray unaryEvaluators = + [ new NotEvaluator(), - new MinusEvaluator()); + 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( + private static readonly ImmutableArray binaries = + [ // logical new LogicalOrEvaluator(), new LogicalAndEvaluator(), @@ -49,7 +52,8 @@ private static readonly IBinaryEvaluator equalsEvaluator 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); @@ -186,7 +190,7 @@ public BinaryEvaluator(BinaryOperator @operator, (TypeSymbol, TypeSymbol) operan public TypeSymbol Evaluate(SyntaxBase expressionSyntax, TypeSymbol leftOperandType, TypeSymbol rightOperandType, IDiagnosticWriter diagnosticWriter) { - var literal = ArmFunctionReturnTypeEvaluator.TryEvaluate(armFunctionName, out var builders, new[] { leftOperandType, rightOperandType }); + var literal = ArmFunctionReturnTypeEvaluator.TryEvaluate(armFunctionName, out var builders, [leftOperandType, rightOperandType]); diagnosticWriter.WriteMultiple(builders.Select(b => b(DiagnosticBuilder.ForPosition(expressionSyntax)))); return literal ?? TryDeriveNonLiteralType(expressionSyntax, leftOperandType, rightOperandType) ?? genericReturnType; @@ -256,7 +260,7 @@ public TypeSymbol Evaluate(SyntaxBase expressionSyntax, TypeSymbol leftOperandTy var transformedArgTypes = new TypeSymbol[2]; for (int i = 0; i < 2; i++) { - transformedArgTypes[i] = ArmFunctionReturnTypeEvaluator.TryEvaluate("toLower", out var builderDelegates, new[] { i % 2 == 0 ? leftOperandType : rightOperandType }) ?? LanguageConstants.String; + transformedArgTypes[i] = ArmFunctionReturnTypeEvaluator.TryEvaluate("toLower", out var builderDelegates, [i % 2 == 0 ? leftOperandType : rightOperandType]) ?? LanguageConstants.String; diagnosticWriter.WriteMultiple(builderDelegates.Select(b => b(DiagnosticBuilder.ForPosition(expressionSyntax)))); } 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..d45e66bdc4f 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) { @@ -120,15 +120,15 @@ public static IEnumerable KnownTopLevelResourceProperties() yield return new TypeProperty("properties", LanguageConstants.Object); - yield return new TypeProperty("sku", new ObjectType("sku", TypeSymbolValidationFlags.Default, new[] - { + yield return new TypeProperty("sku", new ObjectType("sku", TypeSymbolValidationFlags.Default, + [ new TypeProperty("name", LanguageConstants.String), new TypeProperty("tier", LanguageConstants.String), new TypeProperty("size", LanguageConstants.String), new TypeProperty("family", LanguageConstants.String), new TypeProperty("model", LanguageConstants.String), new TypeProperty("capacity", LanguageConstants.Int), - }, null)); + ], null)); yield return new TypeProperty("kind", LanguageConstants.String); yield return new TypeProperty("managedBy", LanguageConstants.String); @@ -143,11 +143,11 @@ public static IEnumerable KnownTopLevelResourceProperties() TypeFactory.CreateStringLiteralType("ArcZone"), LanguageConstants.String); - yield return new TypeProperty("extendedLocation", new ObjectType("extendedLocation", TypeSymbolValidationFlags.Default, new[] - { + yield return new TypeProperty("extendedLocation", new ObjectType("extendedLocation", TypeSymbolValidationFlags.Default, + [ new TypeProperty("type", extendedLocationType, TypePropertyFlags.Required), new TypeProperty("name", LanguageConstants.String), - }, null)); + ], null)); yield return new TypeProperty("zones", stringArray); @@ -155,12 +155,12 @@ public static IEnumerable KnownTopLevelResourceProperties() yield return new TypeProperty("eTag", LanguageConstants.String); - yield return new TypeProperty("scale", new ObjectType("scale", TypeSymbolValidationFlags.Default, new[] - { + yield return new TypeProperty("scale", new ObjectType("scale", TypeSymbolValidationFlags.Default, + [ new TypeProperty("capacity", LanguageConstants.Int, TypePropertyFlags.Required), new TypeProperty("maximum", LanguageConstants.Int), new TypeProperty("minimum", LanguageConstants.Int), - }, null)); + ], null)); var resourceIdentityType = TypeHelper.CreateTypeUnion( TypeFactory.CreateStringLiteralType("NotSpecified"), @@ -170,21 +170,21 @@ public static IEnumerable KnownTopLevelResourceProperties() TypeFactory.CreateStringLiteralType("Actor"), LanguageConstants.String); - var userAssignedIdentity = new ObjectType("userAssignedIdentityProperties", TypeSymbolValidationFlags.Default, new[] - { + var userAssignedIdentity = new ObjectType("userAssignedIdentityProperties", TypeSymbolValidationFlags.Default, + [ new TypeProperty("principalId", LanguageConstants.String), new TypeProperty("clientId", LanguageConstants.String) - }, null); + ], null); - yield return new TypeProperty("identity", new ObjectType("identity", TypeSymbolValidationFlags.Default, new[] - { + yield return new TypeProperty("identity", new ObjectType("identity", TypeSymbolValidationFlags.Default, + [ new TypeProperty("principalId", LanguageConstants.String), 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)); + ], null)); } public AzResourceTypeProvider(IResourceTypeLoader resourceTypeLoader) 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..6ab53d774df 100644 --- a/src/Bicep.Core/TypeSystem/TypeAssignmentVisitor.cs +++ b/src/Bicep.Core/TypeSystem/TypeAssignmentVisitor.cs @@ -1128,8 +1128,8 @@ public override void VisitWildcardImportSyntax(WildcardImportSyntax syntax) ArmTemplateProviderVersion: "1.0.0"), nsProperties, nsFunctions, - ImmutableArray.Empty, - ImmutableArray.Empty, + [], + [], new EmptyResourceTypeProvider()); }); @@ -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/TypeCollapser.cs b/src/Bicep.Core/TypeSystem/TypeCollapser.cs index 9c91b286fdd..694c64dd5c5 100644 --- a/src/Bicep.Core/TypeSystem/TypeCollapser.cs +++ b/src/Bicep.Core/TypeSystem/TypeCollapser.cs @@ -214,7 +214,7 @@ internal BoolCollapse(BooleanType @bool, bool nullable) ? TypeFactory.CreateBooleanLiteralType(includesTrue, flags) : TypeFactory.CreateBooleanType(flags); - return nullable ? TypeHelper.CreateTypeUnion(new[] { collapsed, LanguageConstants.Null }) : collapsed; + return nullable ? TypeHelper.CreateTypeUnion([collapsed, LanguageConstants.Null]) : collapsed; } public UnionCollapseState Push(ITypeReference memberType) 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..e8f373f65d4 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( @@ -481,7 +481,7 @@ public static FunctionOverload OverloadWithResolvedTypes(ResourceDerivedTypeReso public static ObjectType CreateDictionaryType(string name, TypeSymbolValidationFlags validationFlags, ITypeReference valueType) { - return new(name, validationFlags, ImmutableArray.Empty, valueType); + return new(name, validationFlags, [], valueType); } private static ImmutableArray NormalizeTypeList(IEnumerable unionMembers) @@ -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..f9b358391b3 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) @@ -779,7 +779,7 @@ private TypeSymbol NarrowUnionTypeForUnionExpressionType(TypeValidatorConfig con { if (!AreTypesAssignable(candidateExpressionType.Type, targetType)) { - candidacyEvaluations.Add(new(candidateExpressionType, null, ImmutableArray.Empty)); + candidacyEvaluations.Add(new(candidateExpressionType, null, [])); continue; } @@ -821,7 +821,7 @@ private TypeSymbol NarrowUnionTypeForSingleExpressionType(TypeValidatorConfig co { if (!AreTypesAssignable(expressionType, candidateTargetType.Type)) { - candidacyEvaluations.Add(new(candidateTargetType, null, ImmutableArray.Empty)); + candidacyEvaluations.Add(new(candidateTargetType, null, [])); continue; } @@ -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/TypeSystem/Types/ObjectType.cs b/src/Bicep.Core/TypeSystem/Types/ObjectType.cs index fca90465d5d..b529e5d4bc4 100644 --- a/src/Bicep.Core/TypeSystem/Types/ObjectType.cs +++ b/src/Bicep.Core/TypeSystem/Types/ObjectType.cs @@ -12,7 +12,7 @@ namespace Bicep.Core.TypeSystem.Types public class ObjectType : TypeSymbol { public ObjectType(string name, TypeSymbolValidationFlags validationFlags, IEnumerable properties, ITypeReference? additionalPropertiesType, TypePropertyFlags additionalPropertiesFlags = TypePropertyFlags.None, IEnumerable? functions = null) - : this(name, validationFlags, properties, additionalPropertiesType, additionalPropertiesFlags, owner => new FunctionResolver(owner, functions ?? ImmutableArray.Empty)) + : this(name, validationFlags, properties, additionalPropertiesType, additionalPropertiesFlags, owner => new FunctionResolver(owner, functions ?? [])) { } diff --git a/src/Bicep.Core/TypeSystem/Types/TypeTemplate.cs b/src/Bicep.Core/TypeSystem/Types/TypeTemplate.cs index 2dfdeccef65..f5ad60b99fc 100644 --- a/src/Bicep.Core/TypeSystem/Types/TypeTemplate.cs +++ b/src/Bicep.Core/TypeSystem/Types/TypeTemplate.cs @@ -47,7 +47,7 @@ public TypeTemplate(string name, ImmutableArray parameters, Insta public override TypeKind TypeKind => TypeKind.TypeReference; - public override IEnumerable GetDiagnostics() => ImmutableArray.Empty; + public override IEnumerable GetDiagnostics() => []; public TypeParameter? TryGetParameterByIndex(int index) => index < Parameters.Length ? Parameters[index] diff --git a/src/Bicep.Core/Utils/CycleDetector.cs b/src/Bicep.Core/Utils/CycleDetector.cs index 01a431d7260..3e5e71d6369 100644 --- a/src/Bicep.Core/Utils/CycleDetector.cs +++ b/src/Bicep.Core/Utils/CycleDetector.cs @@ -75,7 +75,7 @@ private static void AddCycleInformation(Stack visitStack, TNode currentNo { var cycle = visitStack .TakeWhile(x => x != currentNode) - .Concat(new[] { currentNode }) + .Concat([currentNode]) .ToImmutableArray(); foreach (var element in cycle) 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..79ada2a021b 100644 --- a/src/Bicep.Core/Workspaces/SourceFileGrouping.cs +++ b/src/Bicep.Core/Workspaces/SourceFileGrouping.cs @@ -64,7 +64,7 @@ public ResultWithDiagnostic TryGetSourceFile(IArtifactReferenceSynt public ImmutableHashSet GetFilesDependingOn(ISourceFile sourceFile) { - var filesToCheck = new Queue(new[] { sourceFile }); + var filesToCheck = new Queue([sourceFile]); var knownFiles = new HashSet(); while (filesToCheck.TryDequeue(out var current)) @@ -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..12349e5a7a2 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); @@ -168,7 +168,7 @@ LanguageExpression ReplaceWithParameter(FunctionExpression function, string type return new FunctionExpression( "parameters", - new[] { new JTokenExpression(paramName) }, + [new JTokenExpression(paramName)], function.Properties); } @@ -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/Rewriters/ForExpressionSimplifierRewriter.cs b/src/Bicep.Decompiler/Rewriters/ForExpressionSimplifierRewriter.cs index dab95af7d35..86bd562fa7d 100644 --- a/src/Bicep.Decompiler/Rewriters/ForExpressionSimplifierRewriter.cs +++ b/src/Bicep.Decompiler/Rewriters/ForExpressionSimplifierRewriter.cs @@ -138,10 +138,10 @@ protected override SyntaxBase ReplaceForSyntax(ForSyntax syntax) SyntaxBase forVariableBlockSyntax; if (independentIndexAccesses.Any()) { - forVariableBlockSyntax = SyntaxFactory.CreateVariableBlock(new[] { + forVariableBlockSyntax = SyntaxFactory.CreateVariableBlock([ SyntaxFactory.CreateIdentifier(itemVarName), SyntaxFactory.CreateIdentifier(arrayIndexSymbol.Name) - }); + ]); } else { diff --git a/src/Bicep.Decompiler/TemplateConverter.cs b/src/Bicep.Decompiler/TemplateConverter.cs index eb996805b4f..2b7b79e60db 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); @@ -375,7 +375,7 @@ rightParameter is FunctionExpression rightFunctionExpression && // key is a non-string expression // since ObjectPropertySyntax only accepts IdentifierSyntax or StringSyntax, we need // to wrap it in a string syntax - var keySyntax = SyntaxFactory.CreateString(new[] { string.Empty, string.Empty }, pair[0].AsEnumerable()); + var keySyntax = SyntaxFactory.CreateString([string.Empty, string.Empty], pair[0].AsEnumerable()); return new ObjectPropertySyntax(keySyntax, SyntaxFactory.ColonToken, pair[1]); })); return true; @@ -811,7 +811,7 @@ private IEnumerable ProcessDecoratorsWithTransform(IEnumerable ProcessMetadataDescription(Func valueLookupFunc) => ProcessDecoratorsWithTransform( - new[] { "metadata" }, + ["metadata"], valueLookupFunc, input => { @@ -829,7 +829,7 @@ private IEnumerable ProcessMetadataDescription(Func private IEnumerable ProcessMetadataMiscProperties(Func valueLookupFunc) => ProcessDecoratorsWithTransform( - new[] { "metadata" }, + ["metadata"], valueLookupFunc, input => { @@ -870,7 +870,7 @@ private ParameterDeclarationSyntax ParseParam(JProperty value) decoratorsAndNewLines.AddRange( ProcessDecoratorsWithTransform( - new[] { "minValue", "maxValue", "minLength", "maxLength", "allowedValues" }, + ["minValue", "maxValue", "minLength", "maxLength", "allowedValues"], name => value.Value?[name], input => { @@ -946,7 +946,7 @@ private VariableDeclarationSyntax ParseVariable(string name, JToken value, bool } return new VariableDeclarationSyntax( - ImmutableArray.Empty, + [], SyntaxFactory.VariableKeywordToken, SyntaxFactory.CreateIdentifierWithTrailingSpace(identifier), SyntaxFactory.AssignmentToken, @@ -1021,7 +1021,7 @@ private ForSyntax ProcessNamedCopySyntax(TToken input, string indexIdent // copyIndex() -> copyIndex() return new FunctionExpression( "copyIndex", - new[] { new JTokenExpression(name) }, + [new JTokenExpression(name)], function.Properties); } else if (function.Parameters.Length == 1 && ExpressionHelpers.TryGetStringValue(function.Parameters[0]) == null) @@ -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); } } @@ -1050,7 +1050,7 @@ private ForSyntax ProcessNamedCopySyntax(TToken input, string indexIdent // copyIndex() - replace with '' return new FunctionExpression( "variables", - new[] { new JTokenExpression(indexIdentifier) }, + [new JTokenExpression(indexIdentifier)], function.Properties); } else if (function.Parameters.Length == 2 && ExpressionHelpers.TryGetStringValue(function.Parameters[0]) == name) @@ -1058,16 +1058,15 @@ private ForSyntax ProcessNamedCopySyntax(TToken input, string indexIdent // copyIndex(, ) - replace with ' + ' var varExpression = new FunctionExpression( "variables", - new[] { new JTokenExpression(indexIdentifier), }, - Array.Empty()); + [new JTokenExpression(indexIdentifier),], + []); return new FunctionExpression( "add", - new[] - { + [ varExpression, function.Parameters[1], - }, + ], function.Properties); } @@ -1075,7 +1074,7 @@ private ForSyntax ProcessNamedCopySyntax(TToken input, string indexIdent }); return SyntaxFactory.CreateRangedForSyntax(indexIdentifier, ParseJToken(count), getSyntaxForInputFunc(input)); - }, new[] { indexIdentifier }); + }, [indexIdentifier]); } private (SyntaxBase body, IEnumerable decorators) ProcessResourceCopy(JObject resource, Func resourceBodyFunc) @@ -1244,7 +1243,7 @@ private SyntaxBase ProcessCondition(JObject resource, SyntaxBase body) private SyntaxBase ParseModule(IReadOnlyDictionary copyResourceLookup, JObject resource, string typeString, string nameString) { - var expectedProps = new HashSet(new[] { + var expectedProps = new HashSet([ "name", "type", "apiVersion", @@ -1253,15 +1252,15 @@ private SyntaxBase ParseModule(IReadOnlyDictionary copyResourceL "dependsOn", "comments", "metadata", - }, StringComparer.OrdinalIgnoreCase); + ], StringComparer.OrdinalIgnoreCase); - var propsToOmit = new HashSet(new[] { + var propsToOmit = new HashSet([ "condition", LanguageConstants.CopyLoopIdentifier, "resourceGroup", "subscriptionId", "metadata", - }, StringComparer.OrdinalIgnoreCase); + ], StringComparer.OrdinalIgnoreCase); TemplateHelpers.AssertUnsupportedProperty(resource, "scope", "The 'scope' property is not supported"); foreach (var prop in resource.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) { @@ -1531,8 +1530,8 @@ private SyntaxBase ParseResource(IReadOnlyDictionary copyResourc private ObjectSyntax ProcessResourceBody(IReadOnlyDictionary copyResourceLookup, JObject resource) { - var expectedResourceProps = new HashSet(new[] - { + var expectedResourceProps = new HashSet( + [ "name", "type", "apiVersion", @@ -1554,10 +1553,10 @@ private ObjectSyntax ProcessResourceBody(IReadOnlyDictionary cop "scope", "metadata", "asserts", - }, StringComparer.OrdinalIgnoreCase); + ], StringComparer.OrdinalIgnoreCase); - var resourcePropsToOmit = new HashSet(new[] - { + var resourcePropsToOmit = new HashSet( + [ "condition", LanguageConstants.CopyLoopIdentifier, "type", @@ -1566,7 +1565,7 @@ private ObjectSyntax ProcessResourceBody(IReadOnlyDictionary cop "comments", "scope", "metadata", - }, StringComparer.OrdinalIgnoreCase); + ], StringComparer.OrdinalIgnoreCase); var topLevelProperties = new List(); var scope = TryGetResourceScopeProperty(resource); 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..ae1d45019ff 100644 --- a/src/Bicep.LangServer.IntegrationTests/HoverTests.cs +++ b/src/Bicep.LangServer.IntegrationTests/HoverTests.cs @@ -986,7 +986,7 @@ public async Task Description_markdown_indenting_is_normalized() // https://github.com/Azure/bicep/issues/13982 var (text, cursor) = ParserHelper.GetFileWithSingleCursor(""" type obj = { - + @description('This is the name') name: string @@ -1018,7 +1018,7 @@ There might also be a link to something [link](www.google.com) .Should().EqualIgnoringTrailingWhitespace(""" ```bicep property2: string -``` +``` This is a more complex property This property requries more then one line of text to explain @@ -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/InsertResourceCommandTests.cs b/src/Bicep.LangServer.IntegrationTests/InsertResourceCommandTests.cs index c9e012614e2..de3e3056712 100644 --- a/src/Bicep.LangServer.IntegrationTests/InsertResourceCommandTests.cs +++ b/src/Bicep.LangServer.IntegrationTests/InsertResourceCommandTests.cs @@ -123,7 +123,7 @@ public async Task Insert_resource_command_should_insert_basic_resource() using var helper = await StartLanguageServer(listeners, mockAzResourceProvider.Object, typeLoader); var client = helper.Client; - var resourceId = ResourceGroupLevelResourceId.Create("23775d31-d753-4290-805b-e5bde53eba6e", "myRg", "My.Rp", new[] { "myTypes" }, new[] { "myName" }); + var resourceId = ResourceGroupLevelResourceId.Create("23775d31-d753-4290-805b-e5bde53eba6e", "myRg", "My.Rp", ["myTypes"], ["myName"]); var mockResource = new JObject { ["id"] = resourceId.FullyQualifiedId, @@ -201,7 +201,7 @@ public async Task Insert_resource_command_works_for_empty_file() using var helper = await StartLanguageServer(listeners, mockAzResourceProvider.Object, typeLoader); var client = helper.Client; - var resourceId = ResourceGroupLevelResourceId.Create("23775d31-d753-4290-805b-e5bde53eba6e", "myRg", "My.Rp", new[] { "myTypes" }, new[] { "myName" }); + var resourceId = ResourceGroupLevelResourceId.Create("23775d31-d753-4290-805b-e5bde53eba6e", "myRg", "My.Rp", ["myTypes"], ["myName"]); var mockResource = new JObject { ["id"] = resourceId.FullyQualifiedId, @@ -320,7 +320,7 @@ public async Task Insert_resource_command_should_insert_child_resource() using var helper = await StartLanguageServer(listeners, mockAzResourceProvider.Object, typeLoader); var client = helper.Client; - var resourceId = ResourceGroupLevelResourceId.Create("23775d31-d753-4290-805b-e5bde53eba6e", "myRg", "My.Rp", new[] { "myTypes", "childType" }, new[] { "myName", "childName" }); + var resourceId = ResourceGroupLevelResourceId.Create("23775d31-d753-4290-805b-e5bde53eba6e", "myRg", "My.Rp", ["myTypes", "childType"], ["myName", "childName"]); var mockResource = new JObject { ["id"] = resourceId.FullyQualifiedId, @@ -428,7 +428,7 @@ public async Task Insert_resource_command_displays_error_for_resource_with_no_ty using var helper = await StartLanguageServer(listeners, mockAzResourceProvider.Object, typeLoader); var client = helper.Client; - var resourceId = ResourceGroupLevelResourceId.Create("23775d31-d753-4290-805b-e5bde53eba6e", "myRg", "MadeUp.Rp", new[] { "madeUpTypes" }, new[] { "myName" }); + var resourceId = ResourceGroupLevelResourceId.Create("23775d31-d753-4290-805b-e5bde53eba6e", "myRg", "MadeUp.Rp", ["madeUpTypes"], ["myName"]); var fileUri = new Uri("file:///template.bicep"); var fileContents = await InvokeInsertResource(client, listeners, fileUri, @" @@ -469,7 +469,7 @@ public async Task Insert_resource_command_should_try_to_fetch_without_apiVersion using var helper = await StartLanguageServer(listeners, mockAzResourceProvider.Object, typeLoader); var client = helper.Client; - var resourceId = ResourceGroupLevelResourceId.Create("23775d31-d753-4290-805b-e5bde53eba6e", "myRg", "My.Rp", new[] { "myTypes" }, new[] { "myName" }); + var resourceId = ResourceGroupLevelResourceId.Create("23775d31-d753-4290-805b-e5bde53eba6e", "myRg", "My.Rp", ["myTypes"], ["myName"]); mockAzResourceProvider.Setup(x => x.GetGenericResource(It.IsAny(), It.Is(x => x.FullyQualifiedId == resourceId.FullyQualifiedId), "2020-01-01", It.IsAny())) .Throws(new InvalidOperationException("Something went wrong!")); @@ -546,7 +546,7 @@ public async Task Insert_resource_command_should_return_exception_info_if_both_G using var helper = await StartLanguageServer(listeners, mockAzResourceProvider.Object, typeLoader); var client = helper.Client; - var resourceId = ResourceGroupLevelResourceId.Create("23775d31-d753-4290-805b-e5bde53eba6e", "myRg", "My.Rp", new[] { "myTypes" }, new[] { "myName" }); + var resourceId = ResourceGroupLevelResourceId.Create("23775d31-d753-4290-805b-e5bde53eba6e", "myRg", "My.Rp", ["myTypes"], ["myName"]); mockAzResourceProvider.Setup(x => x.GetGenericResource(It.IsAny(), It.Is(x => x.FullyQualifiedId == resourceId.FullyQualifiedId), "2020-01-01", It.IsAny())) .Throws(new InvalidOperationException("Something went wrong!")); 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..8b50d399f52 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"; @@ -247,7 +247,7 @@ param concat string var completionProvider = CreateProvider(); var completions = (await completionProvider.GetFilteredCompletions(compilation, context, CancellationToken.None)).ToList(); - AssertExpectedFunctions(completions, expectParamDefaultFunctions: false, new[] { "sys.concat", "az.resourceGroup", "sys.base64" }); + AssertExpectedFunctions(completions, expectParamDefaultFunctions: false, ["sys.concat", "az.resourceGroup", "sys.base64"]); // outputs and assertions can't be referenced so they should not show up in completions completions.Where(c => c.Kind == SymbolKind.Output.ToCompletionItemKind()).Should().BeEmpty(); @@ -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/BicepDiagnosticBuilderTests.cs b/src/Bicep.LangServer.UnitTests/BicepDiagnosticBuilderTests.cs index 07563536197..881edad78aa 100644 --- a/src/Bicep.LangServer.UnitTests/BicepDiagnosticBuilderTests.cs +++ b/src/Bicep.LangServer.UnitTests/BicepDiagnosticBuilderTests.cs @@ -22,12 +22,12 @@ public void CreateOmnisharpDiagnosticWithCodeDesription() var sampleUri = new Uri("https://aka.ms/this/is/a/test"); var analyzerName = "unit test"; - IEnumerable diags = new[] - { + IEnumerable diags = + [ new AnalyzerDiagnostic(analyzerName, new TextSpan(0,0), DiagnosticLevel.Warning, "Analyzer Msg Code", "Analyzer message string", sampleUri), new Diagnostic(new TextSpan(0,0), DiagnosticLevel.Error, "TestCode", "Bicep language message for diagnostic", sampleUri) - }; + ]; var lineStarts = new[] { 0 }.ToImmutableArray(); var omnisharpDiagnostics = diags.ToDiagnostics(lineStarts); @@ -50,12 +50,12 @@ public void CreateOmnisharpDiagnosticWithCodeDesription() public void CreateOmnisharpDiagnosticWithoutCodeDesription() { var analyzerName = "unit test"; - IEnumerable diags = new[] - { + IEnumerable diags = + [ new AnalyzerDiagnostic(analyzerName, new TextSpan(0,0), DiagnosticLevel.Warning, "Analyzer Msg Code", "Analyzer message string", null /* no doc Uri */), new Diagnostic(new TextSpan(0,0), DiagnosticLevel.Error, "TestCode", "No docs for this error message") - }; + ]; var lineStarts = new[] { 0 }.ToImmutableArray(); var omnisharpDiagnostics = diags.ToDiagnostics(lineStarts); 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..91f64a64526 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) - }); + ]); 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) - }); + ]); 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.UnitTests/Snippets/SnippetsProviderTests.cs b/src/Bicep.LangServer.UnitTests/Snippets/SnippetsProviderTests.cs index 9189b756e97..219c4768b5e 100644 --- a/src/Bicep.LangServer.UnitTests/Snippets/SnippetsProviderTests.cs +++ b/src/Bicep.LangServer.UnitTests/Snippets/SnippetsProviderTests.cs @@ -357,19 +357,19 @@ public void GetNestedResourceDeclarationSnippets_WithNoChildResources_ShouldRetu [TestMethod] public void GetResourceBodyCompletionSnippets_WithDiscriminatedObjectTypeAndNoRequiredProperties_ShouldReturnEmptySnippet() { - var objectTypeA = new ObjectType("objA", TypeSymbolValidationFlags.Default, new[] - { + var objectTypeA = new ObjectType("objA", TypeSymbolValidationFlags.Default, + [ new TypeProperty("discKey", TypeFactory.CreateStringLiteralType("keyA")), new TypeProperty("keyAProp", LanguageConstants.String), - }, null); + ], null); - var objectTypeB = new ObjectType("objB", TypeSymbolValidationFlags.Default, new[] - { + var objectTypeB = new ObjectType("objB", TypeSymbolValidationFlags.Default, + [ new TypeProperty("discKey", TypeFactory.CreateStringLiteralType("keyB")), new TypeProperty("keyBProp", LanguageConstants.String), - }, null); + ], null); - var discriminatedObjectType = new DiscriminatedObjectType("discObj", TypeSymbolValidationFlags.Default, "discKey", new[] { objectTypeA, objectTypeB }); + var discriminatedObjectType = new DiscriminatedObjectType("discObj", TypeSymbolValidationFlags.Default, "discKey", [objectTypeA, objectTypeB]); ResourceType resourceType = new( azNamespaceType, @@ -395,23 +395,23 @@ public void GetResourceBodyCompletionSnippets_WithDiscriminatedObjectTypeAndNoRe [TestMethod] public void GetResourceBodyCompletionSnippets_WithDiscriminatedObjectTypeAndRequiredProperties_ShouldReturnRequiredPropertiesSnippet() { - var objectTypeA = new ObjectType("objA", TypeSymbolValidationFlags.Default, new[] - { + var objectTypeA = new ObjectType("objA", TypeSymbolValidationFlags.Default, + [ new TypeProperty("discKey", TypeFactory.CreateStringLiteralType("keyA")), new TypeProperty("name", TypeFactory.CreateStringLiteralType("keyA"), TypePropertyFlags.Required), new TypeProperty("location", LanguageConstants.String, TypePropertyFlags.Required), new TypeProperty("id", LanguageConstants.String) - }, null); + ], null); - var objectTypeB = new ObjectType("objB", TypeSymbolValidationFlags.Default, new[] - { + var objectTypeB = new ObjectType("objB", TypeSymbolValidationFlags.Default, + [ new TypeProperty("discKey", TypeFactory.CreateStringLiteralType("keyB")), new TypeProperty("name", LanguageConstants.String, TypePropertyFlags.Required), new TypeProperty("kind", TypeFactory.CreateStringLiteralType("discKey"), TypePropertyFlags.ReadOnly), new TypeProperty("hostPoolType", LanguageConstants.String) - }, null); + ], null); - var discriminatedObjectType = new DiscriminatedObjectType("discObj", TypeSymbolValidationFlags.Default, "discKey", new[] { objectTypeA, objectTypeB }); + var discriminatedObjectType = new DiscriminatedObjectType("discObj", TypeSymbolValidationFlags.Default, "discKey", [objectTypeA, objectTypeB]); ResourceType resourceType = new( azNamespaceType, @@ -456,12 +456,12 @@ public void GetResourceBodyCompletionSnippets_WithDiscriminatedObjectTypeAndRequ [TestMethod] public void GetModuleBodyCompletionSnippets_WithNoRequiredProperties_ShouldReturnEmptySnippet() { - var objectType = new ObjectType("objA", TypeSymbolValidationFlags.Default, new[] - { + var objectType = new ObjectType("objA", TypeSymbolValidationFlags.Default, + [ new TypeProperty("name", LanguageConstants.String, TypePropertyFlags.ReadOnly), new TypeProperty("location", LanguageConstants.String, TypePropertyFlags.WriteOnly), new TypeProperty("id", LanguageConstants.String) - }, null); + ], null); TypeSymbol typeSymbol = new ModuleType("module", ResourceScope.Module, objectType); IEnumerable snippets = CreateSnippetsProvider().GetModuleBodyCompletionSnippets(typeSymbol); @@ -479,12 +479,12 @@ public void GetModuleBodyCompletionSnippets_WithNoRequiredProperties_ShouldRetur [TestMethod] public void GetModuleBodyCompletionSnippets_WithRequiredProperties_ShouldReturnEmptyAndRequiredPropertiesSnippets() { - var objectType = new ObjectType("objA", TypeSymbolValidationFlags.Default, new[] - { + var objectType = new ObjectType("objA", TypeSymbolValidationFlags.Default, + [ new TypeProperty("name", LanguageConstants.String, TypePropertyFlags.Required), new TypeProperty("location", LanguageConstants.String, TypePropertyFlags.Required), new TypeProperty("id", LanguageConstants.String) - }, null); + ], null); TypeSymbol typeSymbol = new ModuleType("module", ResourceScope.Module, objectType); IEnumerable snippets = CreateSnippetsProvider().GetModuleBodyCompletionSnippets(typeSymbol); @@ -512,12 +512,12 @@ public void GetModuleBodyCompletionSnippets_WithRequiredProperties_ShouldReturnE [TestMethod] public void GetObjectBodyCompletionSnippets_WithNoRequiredProperties_ShouldReturnEmptySnippet() { - var objectType = new ObjectType("objA", TypeSymbolValidationFlags.Default, new[] - { + var objectType = new ObjectType("objA", TypeSymbolValidationFlags.Default, + [ new TypeProperty("name", LanguageConstants.String, TypePropertyFlags.ReadOnly), new TypeProperty("location", LanguageConstants.String, TypePropertyFlags.WriteOnly), new TypeProperty("id", LanguageConstants.String) - }, null); + ], null); IEnumerable snippets = CreateSnippetsProvider().GetObjectBodyCompletionSnippets(objectType); @@ -534,12 +534,12 @@ public void GetObjectBodyCompletionSnippets_WithNoRequiredProperties_ShouldRetur [TestMethod] public void GetObjectBodyCompletionSnippets_WithRequiredProperties_ShouldReturnEmptyAndRequiredPropertiesSnippets() { - var objectType = new ObjectType("objA", TypeSymbolValidationFlags.Default, new[] - { + var objectType = new ObjectType("objA", TypeSymbolValidationFlags.Default, + [ new TypeProperty("name", LanguageConstants.String, TypePropertyFlags.Required), new TypeProperty("location", LanguageConstants.String, TypePropertyFlags.Required), new TypeProperty("id", LanguageConstants.String) - }, null); + ], null); IEnumerable snippets = CreateSnippetsProvider().GetObjectBodyCompletionSnippets(objectType); @@ -566,19 +566,19 @@ public void GetObjectBodyCompletionSnippets_WithRequiredProperties_ShouldReturnE [TestMethod] public void GetObjectBodyCompletionSnippets_WithDiscriminatedObjectTypeAndNoRequiredProperties_ShouldReturnEmptySnippet() { - var objectTypeA = new ObjectType("objA", TypeSymbolValidationFlags.Default, new[] - { + var objectTypeA = new ObjectType("objA", TypeSymbolValidationFlags.Default, + [ new TypeProperty("discKey", TypeFactory.CreateStringLiteralType("keyA")), new TypeProperty("keyAProp", LanguageConstants.String), - }, null); + ], null); - var objectTypeB = new ObjectType("objB", TypeSymbolValidationFlags.Default, new[] - { + var objectTypeB = new ObjectType("objB", TypeSymbolValidationFlags.Default, + [ new TypeProperty("discKey", TypeFactory.CreateStringLiteralType("keyB")), new TypeProperty("keyBProp", LanguageConstants.String), - }, null); + ], null); - var discriminatedObjectType = new DiscriminatedObjectType("discObj", TypeSymbolValidationFlags.Default, "discKey", new[] { objectTypeA, objectTypeB }); + var discriminatedObjectType = new DiscriminatedObjectType("discObj", TypeSymbolValidationFlags.Default, "discKey", [objectTypeA, objectTypeB]); IEnumerable snippets = CreateSnippetsProvider().GetObjectBodyCompletionSnippets(discriminatedObjectType); @@ -595,23 +595,23 @@ public void GetObjectBodyCompletionSnippets_WithDiscriminatedObjectTypeAndNoRequ [TestMethod] public void GetObjectBodyCompletionSnippets_WithDiscriminatedObjectTypeAndRequiredProperties_ShouldReturnEmptyAndRequiredPropertiesSnippets() { - var objectTypeA = new ObjectType("objA", TypeSymbolValidationFlags.Default, new[] - { + var objectTypeA = new ObjectType("objA", TypeSymbolValidationFlags.Default, + [ new TypeProperty("discKey", TypeFactory.CreateStringLiteralType("keyA")), new TypeProperty("name", TypeFactory.CreateStringLiteralType("keyA"), TypePropertyFlags.Required), new TypeProperty("location", LanguageConstants.String, TypePropertyFlags.Required), new TypeProperty("id", LanguageConstants.String) - }, null); + ], null); - var objectTypeB = new ObjectType("objB", TypeSymbolValidationFlags.Default, new[] - { + var objectTypeB = new ObjectType("objB", TypeSymbolValidationFlags.Default, + [ new TypeProperty("discKey", TypeFactory.CreateStringLiteralType("keyB")), new TypeProperty("name", LanguageConstants.String, TypePropertyFlags.Required), new TypeProperty("kind", TypeFactory.CreateStringLiteralType("discKey"), TypePropertyFlags.ReadOnly), new TypeProperty("hostPoolType", LanguageConstants.String) - }, null); + ], null); - var discriminatedObjectType = new DiscriminatedObjectType("discObj", TypeSymbolValidationFlags.Default, "discKey", new[] { objectTypeA, objectTypeB }); + var discriminatedObjectType = new DiscriminatedObjectType("discObj", TypeSymbolValidationFlags.Default, "discKey", [objectTypeA, objectTypeB]); IEnumerable snippets = CreateSnippetsProvider().GetObjectBodyCompletionSnippets(discriminatedObjectType); 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/BicepExternalSourceDocumentLinkHandler.cs b/src/Bicep.LangServer/Handlers/BicepExternalSourceDocumentLinkHandler.cs index d978ce8a1f6..0062d20f288 100644 --- a/src/Bicep.LangServer/Handlers/BicepExternalSourceDocumentLinkHandler.cs +++ b/src/Bicep.LangServer/Handlers/BicepExternalSourceDocumentLinkHandler.cs @@ -158,7 +158,7 @@ public static async Task> ResolveDo { // We haven't tried restoring this module yet. Let's try it now. Trace.WriteLine($"Attempting to restore module {targetArtifactReference.FullyQualifiedReference}"); - await moduleDispatcher.RestoreArtifacts(new[] { targetArtifactReference }, forceRestore: false); + await moduleDispatcher.RestoreArtifacts([targetArtifactReference], forceRestore: false); restoreStatus = moduleDispatcher.GetArtifactRestoreStatus(targetArtifactReference, out errorBuilder); errorMessage = errorBuilder?.Invoke(ForDocumentStart()).Message; 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/InsertResourceHandler.cs b/src/Bicep.LangServer/Handlers/InsertResourceHandler.cs index aedd7756016..49fe6657866 100644 --- a/src/Bicep.LangServer/Handlers/InsertResourceHandler.cs +++ b/src/Bicep.LangServer/Handlers/InsertResourceHandler.cs @@ -145,13 +145,13 @@ await server.Workspace.ApplyWorkspaceEdit(new ApplyWorkspaceEditParams { Changes = new Dictionary> { - [request.TextDocument.Uri] = new[] { + [request.TextDocument.Uri] = [ new TextEdit { Range = replacement.ToRange(context.LineStarts), NewText = replacement.Text, }, - }, + ], }, }, }, cancellationToken); @@ -263,7 +263,7 @@ private static ResourceDeclarationSyntax CreateResourceSyntax(JsonElement resour SyntaxFactory.CreateStringLiteral($"Generated from {resourceId.FullyQualifiedId}")); return new ResourceDeclarationSyntax( - new SyntaxBase[] { description, SyntaxFactory.NewlineToken, }, + [description, SyntaxFactory.NewlineToken,], SyntaxFactory.ResourceKeywordToken, SyntaxFactory.CreateIdentifierWithTrailingSpace(UnifiedNamePattern().Replace(resourceId.UnqualifiedName, "")), SyntaxFactory.CreateStringLiteral(typeReference.FormatName()), diff --git a/src/Bicep.LangServer/Snippets/Snippet.cs b/src/Bicep.LangServer/Snippets/Snippet.cs index 684633ddb46..f0204a020dc 100644 --- a/src/Bicep.LangServer/Snippets/Snippet.cs +++ b/src/Bicep.LangServer/Snippets/Snippet.cs @@ -26,10 +26,9 @@ public Snippet(string text, CompletionPriority completionPriority = CompletionPr this.Prefix = prefix; this.Detail = detail; this.CompletionPriority = completionPriority; - this.Placeholders = matches + this.Placeholders = [.. matches .Select(CreatePlaceholder) - .OrderBy(p => p.Index) - .ToImmutableArray(); + .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..1ab6eb4fda6 100644 --- a/src/Bicep.LangServer/Snippets/SnippetsProvider.cs +++ b/src/Bicep.LangServer/Snippets/SnippetsProvider.cs @@ -25,7 +25,8 @@ 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( + private readonly ImmutableArray propertiesSortPreferenceList = + [ "scope", "parent", "name", @@ -38,7 +39,8 @@ public class SnippetsProvider : ISnippetsProvider "identity", "tags", "properties", - "dependsOn"); + "dependsOn" + ]; private static readonly SnippetCache snippetCache = SnippetCache.FromManifest(); @@ -122,7 +124,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..fc8a2ea2075 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) - }; + ]; 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..7b40e8bfe65 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,13 +197,13 @@ 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", @@ -212,7 +212,7 @@ public class LocalDeploymentSettings : IAzureDeploymentSettings "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/Extensions/EnumerableExtensions.cs b/src/Bicep.RegistryModuleTool/Extensions/EnumerableExtensions.cs index aed30423226..35bfd1ec6fb 100644 --- a/src/Bicep.RegistryModuleTool/Extensions/EnumerableExtensions.cs +++ b/src/Bicep.RegistryModuleTool/Extensions/EnumerableExtensions.cs @@ -23,7 +23,7 @@ public static string ToMarkdownTable(this IEnumerable enumerable, Func properties.Select(property => property.GetValue(item)?.ToString()?.Length ?? 0)) - .Union(new[] { properties.Select(property => property.Name.Length) }) + .Union([properties.Select(property => property.Name.Length)]) .Aggregate(new int[properties.Length].AsEnumerable(), (maximumWidths, widths) => maximumWidths.Zip(widths, Math.Max)) .ToArray(); 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 _) => []; } }