Skip to content

Commit

Permalink
Disallow default values on nullably-typed params
Browse files Browse the repository at this point in the history
  • Loading branch information
jeskew committed Jan 9, 2023
1 parent 0262e37 commit cd10b2c
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 0 deletions.
13 changes: 13 additions & 0 deletions src/Bicep.Core.IntegrationTests/UserDefinedTypeTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -428,4 +428,17 @@ public void Warning_should_be_shown_when_setting_unknown_properties_on_unsealed_
("BCP037", DiagnosticLevel.Warning, "The property \"prop\" is not allowed on objects of type \"{ }\". No other properties are allowed."),
});
}

[TestMethod]
public void Error_should_be_emitted_when_setting_a_default_value_on_a_nullable_parameter()
{
var result = CompilationHelper.Compile(ServicesWithUserDefinedTypes, @"
#disable-next-line no-unused-params
param myParam string? = 'foo'
");

result.Should().HaveDiagnostics(new[] {
("BCP317", DiagnosticLevel.Error, "Nullable-typed parameters may not be assigned default values. They have an implicit default of 'null' that cannot be overridden."),
});
}
}
5 changes: 5 additions & 0 deletions src/Bicep.Core/Diagnostics/DiagnosticBuilder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -1806,6 +1806,11 @@ public ErrorDiagnostic NestedRuntimePropertyAccessNotSupported(string? resourceS
TextSpan,
"BCP316",
$@"Using nullable types requires enabling EXPERIMENTAL feature ""{nameof(ExperimentalFeaturesEnabled.UserDefinedTypes)}"".");

public ErrorDiagnostic NullableTypedParamsMayNotHaveDefaultValues() => new(
TextSpan,
"BCP317",
"Nullable-typed parameters may not be assigned default values. They have an implicit default of 'null' that cannot be overridden.");
}

public static DiagnosticBuilderInternal ForPosition(TextSpan span)
Expand Down
5 changes: 5 additions & 0 deletions src/Bicep.Core/TypeSystem/TypeAssignmentVisitor.cs
Original file line number Diff line number Diff line change
Expand Up @@ -377,6 +377,11 @@ public override void VisitParameterDeclarationSyntax(ParameterDeclarationSyntax
if (syntax.Modifier != null)
{
diagnostics.WriteMultiple(this.ValidateIdentifierAccess(syntax.Modifier));
if (TypeValidator.AreTypesAssignable(LanguageConstants.Null, declaredType))
{
diagnostics.Write(DiagnosticBuilder.ForPosition(syntax.Modifier).NullableTypedParamsMayNotHaveDefaultValues());
}
}
if (declaredType is ErrorType)
Expand Down

0 comments on commit cd10b2c

Please sign in to comment.