Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

WIP nameof function #3

Closed
wants to merge 4 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions Bicep.sln.DotSettings
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,10 @@
<s:Boolean x:Key="/Default/CodeInspection/ExcludedFiles/FileMasksToSkip/=_002A_002Etxt/@EntryIndexedValue">True</s:Boolean>
<s:Boolean x:Key="/Default/CodeStyle/CodeFormatting/CSharpFormat/WRAP_LINES/@EntryValue">False</s:Boolean>
<s:String x:Key="/Default/CodeStyle/Naming/CSharpNaming/PredefinedNamingRules/=PrivateStaticFields/@EntryIndexedValue">&lt;Policy Inspect="True" Prefix="" Suffix="" Style="aaBb" /&gt;</s:String>
<s:String x:Key="/Default/CodeStyle/Naming/CSharpNaming/UserRules/=f9fce829_002De6f4_002D4cb2_002D80f1_002D5497c44f51df/@EntryIndexedValue">&lt;Policy&gt;&lt;Descriptor Staticness="Static" AccessRightKinds="Private" Description="Static fields (private)"&gt;&lt;ElementKinds&gt;&lt;Kind Name="FIELD" /&gt;&lt;/ElementKinds&gt;&lt;/Descriptor&gt;&lt;Policy Inspect="True" Prefix="" Suffix="" Style="aaBb" /&gt;&lt;/Policy&gt;</s:String>
<s:Boolean x:Key="/Default/Environment/SettingsMigration/IsMigratorApplied/=JetBrains_002EReSharper_002EPsi_002ECSharp_002ECodeStyle_002ECSharpKeepExistingMigration/@EntryIndexedValue">True</s:Boolean>
<s:Boolean x:Key="/Default/Environment/SettingsMigration/IsMigratorApplied/=JetBrains_002EReSharper_002EPsi_002ECSharp_002ECodeStyle_002ECSharpPlaceEmbeddedOnSameLineMigration/@EntryIndexedValue">True</s:Boolean>
<s:Boolean x:Key="/Default/Environment/SettingsMigration/IsMigratorApplied/=JetBrains_002EReSharper_002EPsi_002ECSharp_002ECodeStyle_002ECSharpUseContinuousIndentInsideBracesMigration/@EntryIndexedValue">True</s:Boolean>
<s:Boolean x:Key="/Default/Environment/SettingsMigration/IsMigratorApplied/=JetBrains_002EReSharper_002EPsi_002ECSharp_002ECodeStyle_002ESettingsUpgrade_002EMigrateBlankLinesAroundFieldToBlankLinesAroundProperty/@EntryIndexedValue">True</s:Boolean>
<s:Boolean x:Key="/Default/Environment/SettingsMigration/IsMigratorApplied/=JetBrains_002EReSharper_002EPsi_002ECSharp_002ECodeStyle_002ESettingsUpgrade_002EPredefinedNamingRulesToUserRulesUpgrade/@EntryIndexedValue">True</s:Boolean>
<s:Boolean x:Key="/Default/Housekeeping/ProjectModelSynchronizer/ReadProjectModelFromDisk/@EntryValue">True</s:Boolean></wpf:ResourceDictionary>
212 changes: 212 additions & 0 deletions src/Bicep.Core.IntegrationTests/Scenarios/NameofFunctionTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,212 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.

using Bicep.Core.UnitTests.Assertions;
using Bicep.Core.UnitTests.Utils;
using FluentAssertions.Execution;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Newtonsoft.Json.Linq;

namespace Bicep.Core.IntegrationTests.Scenarios
{
[TestClass]
public class NameofFunctionTests
{
[DataRow("prop",".prop")]
[DataRow("'complex-prop'","['complex-prop']")]
[DataTestMethod]
public void NameofFunction_OnObjectProperty_ReturnsPropertyName(string propertyName, string propertyAccess)
{
var result = CompilationHelper.Compile($$"""
var obj = {
{{propertyName}}: 'value'
}
output name string = nameof(obj{{propertyAccess}})
""");

using (new AssertionScope())
{
result.Should().NotHaveAnyCompilationBlockingDiagnostics();
result.Template.Should().HaveValueAtPath("$.outputs['name'].value", propertyName);
}
}

[TestMethod]
public void NameofFunction_OnVariable_ReturnsVariableName()
{
var result = CompilationHelper.Compile("""
var obj = {
prop: 'value'
}
output name string = nameof(obj)
""");

using (new AssertionScope())
{
result.Should().NotHaveAnyCompilationBlockingDiagnostics();
result.Template.Should().HaveValueAtPath("$.outputs['name'].value", "obj");
}
}

[TestMethod]
public void NameofFunction_OnParameter_ReturnsParameterName()
{
var result = CompilationHelper.Compile("""
param test string
output name string = nameof(test)
""");

using (new AssertionScope())
{
result.Should().NotHaveAnyCompilationBlockingDiagnostics();
result.Template.Should().HaveValueAtPath("$.outputs['name'].value", "test");
}
}

[TestMethod]
public void NameofFunction_OnResource_ReturnsResourceSymbolicName()
{
var result = CompilationHelper.Compile("""
resource myStorage 'Microsoft.Storage/storageAccounts@2019-06-01' = {
name: 'storage123'
}

output name string = nameof(myStorage)
""");

using (new AssertionScope())
{
result.Should().NotHaveAnyCompilationBlockingDiagnostics();
result.Template.Should().HaveValueAtPath("$.outputs['name'].value", "myStorage");
}
}

[TestMethod]
public void NameofFunction_OnChildResource_ReturnsResourceSymbolicName()
{
var result = CompilationHelper.Compile("""
resource sqlServer 'Microsoft.Sql/servers@2021-11-01' = {
name: 'sql-server-name'

resource primaryDb 'databases' = {
name: 'primary'
}
}

output name string = nameof(sqlServer::primaryDb)
""");

using (new AssertionScope())
{
result.Should().NotHaveAnyCompilationBlockingDiagnostics();
result.Template.Should().HaveValueAtPath("$.outputs['name'].value", "primaryDb");
}
}

[TestMethod]
public void NameofFunction_OnLoopedResource_ReturnsResourceSymbolicName()
{
var result = CompilationHelper.Compile("""

var dbs = [
'primary'
'secondary'
'tertiary'
]

resource sqlServer 'Microsoft.Sql/servers@2021-11-01' = {
name: 'sql-server-name'

@batchSize(1)
resource databases 'databases' = [for db in dbs: {
name: db
}]
}

output name string = nameof(sqlServer::databases)
""");

using (new AssertionScope())
{
result.Should().NotHaveAnyCompilationBlockingDiagnostics();
result.Template.Should().HaveValueAtPath("$.outputs['name'].value", "databases");
}
}

[TestMethod]
public void NameofFunction_OnLoopedResourceProperty_ReturnsResourcePropertyName()
{
var result = CompilationHelper.Compile("""

var dbs = [
'primary'
'secondary'
'tertiary'
]

resource sqlServer 'Microsoft.Sql/servers@2021-11-01' = {
name: 'sql-server-name'

@batchSize(1)
resource databases 'databases' = [for db in dbs: {
name: db
}]
}

output name string = nameof(sqlServer::databases[100].properties.collation)
""");


using (new AssertionScope())
{
result.Should().NotHaveAnyCompilationBlockingDiagnostics();
result.Template.Should().HaveValueAtPath("$.outputs['name'].value", "collation");
}
}

[DataTestMethod]
[DataRow("name", "name")]
[DataRow("type", "type")]
[DataRow("location", "location")]
[DataRow("properties", "properties")]
[DataRow("properties.sku", "sku")]
public void NameofFunction_OnResourceProperty_ReturnsResourcePropertyName(string resourceProperty, string expectedValue)
{
var result = CompilationHelper.Compile($$"""
resource myStorage 'Microsoft.Storage/storageAccounts@2019-06-01' = {
name: 'storage123'
}

var name = nameof(myStorage.{{resourceProperty}})

""");

using (new AssertionScope())
{
result.Should().NotHaveAnyCompilationBlockingDiagnostics();
result.Template.Should().HaveValueAtPath("$.variables['name']", expectedValue);
}
}

[TestMethod]
public void UsingNameofFunction_ShouldNotGenerateDependsOnEntries()
{
var result = CompilationHelper.Compile("""
resource myStorage 'Microsoft.Storage/storageAccounts@2019-06-01' = {
name: 'storage123'
}

resource sqlServer 'Microsoft.Sql/servers@2021-11-01' = {
name: nameof(myStorage)
}
""");

using (new AssertionScope())
{
result.Should().NotHaveAnyCompilationBlockingDiagnostics();
result.Template.Should().HaveValueAtPath("$.resources[?(@.type == 'Microsoft.Sql/servers')].name", "myStorage", "Nameof function should emit static string during compilation");
result.Template.Should().NotHaveValueAtPath("$.resources[?(@.type == 'Microsoft.Sql/servers')].dependsOn", "Depends on should not be generated for nameof function usage");
}
}
}
}
19 changes: 19 additions & 0 deletions src/Bicep.Core.Samples/Files/baselines/Functions/sys.json
Original file line number Diff line number Diff line change
Expand Up @@ -1128,6 +1128,25 @@
"intArray: int[]"
]
},
{
"name": "nameof",
"description": "Returns the name of a variable, resource, module or property as the string constant. Function is evaluated at compile time and has no effect during deployment.",
"fixedParameters": [
{
"name": "symbol",
"description": "The variable, resource, module or property to produce the name.",
"type": "any",
"required": true
}
],
"minimumArgumentCount": 1,
"maximumArgumentCount": 1,
"flags": "default",
"typeSignature": "(symbol: any): string",
"parameterTypeSignatures": [
"symbol: any"
]
},
{
"name": "newGuid",
"description": "Returns a value in the format of a globally unique identifier. **This function can only be used in the default value for a parameter**.",
Expand Down
Loading
Loading