diff --git a/packages/http-client-csharp/generator/Microsoft.TypeSpec.Generator.Input/src/Extensions/StringExtensions.cs b/packages/http-client-csharp/generator/Microsoft.TypeSpec.Generator.Input/src/Extensions/StringExtensions.cs index aa4ad0142dd..a767fbb3a61 100644 --- a/packages/http-client-csharp/generator/Microsoft.TypeSpec.Generator.Input/src/Extensions/StringExtensions.cs +++ b/packages/http-client-csharp/generator/Microsoft.TypeSpec.Generator.Input/src/Extensions/StringExtensions.cs @@ -4,12 +4,24 @@ using System; using System.Diagnostics.CodeAnalysis; using System.Text; +using System.Text.RegularExpressions; using Microsoft.CodeAnalysis.CSharp; namespace Microsoft.TypeSpec.Generator.Input.Extensions { public static class StringExtensions { + private static readonly Regex _uppercaseWords = new(""" + (? + _uppercaseWords.Replace(name, static match => match.Value[..1] + match.Value[1..].ToLowerInvariant()) + .ToIdentifierName(); + private static bool IsWordSeparator(char c, bool preserveUnderscores = false) => !SyntaxFacts.IsIdentifierPartCharacter(c) || (!preserveUnderscores && c == '_'); diff --git a/packages/http-client-csharp/generator/Microsoft.TypeSpec.Generator/src/Providers/EnumProvider.cs b/packages/http-client-csharp/generator/Microsoft.TypeSpec.Generator/src/Providers/EnumProvider.cs index 74e1679a7b2..9d804acfc55 100644 --- a/packages/http-client-csharp/generator/Microsoft.TypeSpec.Generator/src/Providers/EnumProvider.cs +++ b/packages/http-client-csharp/generator/Microsoft.TypeSpec.Generator/src/Providers/EnumProvider.cs @@ -146,7 +146,8 @@ private protected string GetBackCompatibleName( private protected string[] GetGeneratedValueNames( IReadOnlyList inputValues, - IReadOnlyList lastContractNames) + IReadOnlyList lastContractNames, + bool normalizeUppercase = false) { var previousNames = inputValues.Select(v => GetGeneratedValueName(v, lastContractNames)).ToArray(); var normalizedNames = new string[previousNames.Length]; @@ -159,10 +160,30 @@ private protected string[] GetGeneratedValueNames( continue; } - var normalizedName = name.NormalizeCSharpAcronyms(); - normalizedNames[i] = lastContractNames.Contains(name, StringComparer.Ordinal) && !IsCustomizedValueName(normalizedName) - ? name - : normalizedName; + var normalizedName = name; + var hasNewUrlRewrite = false; + if (normalizeUppercase) + { + var identifier = inputValues[i].Name.ToPascalCaseIdentifierName(); + normalizedName = identifier.NormalizeCSharpUrlSuffix(); + hasNewUrlRewrite = normalizedName != identifier && normalizedName != name; + } + + normalizedName = normalizedName.NormalizeCSharpAcronyms(); + if (lastContractNames.Contains(name, StringComparer.Ordinal) && !IsCustomizedValueName(normalizedName)) + { + normalizedName = name; + } + else if (hasNewUrlRewrite && !IsCustomizedValueName(normalizedName)) + { + // A new suffix rewrite can hide a compatible name that differs only in casing or underscores. + var compatibleName = GetBackCompatibleName(name, previousNames, lastContractNames, isExactName: false); + if (compatibleName != name) + { + normalizedName = compatibleName; + } + } + normalizedNames[i] = normalizedName; } return normalizedNames; } diff --git a/packages/http-client-csharp/generator/Microsoft.TypeSpec.Generator/src/Providers/ExtensibleEnumProvider.cs b/packages/http-client-csharp/generator/Microsoft.TypeSpec.Generator/src/Providers/ExtensibleEnumProvider.cs index b60ded0dfc7..1e7dd3da2a6 100644 --- a/packages/http-client-csharp/generator/Microsoft.TypeSpec.Generator/src/Providers/ExtensibleEnumProvider.cs +++ b/packages/http-client-csharp/generator/Microsoft.TypeSpec.Generator/src/Providers/ExtensibleEnumProvider.cs @@ -59,7 +59,7 @@ private protected override bool IsCustomizedValueName(string name) protected override IReadOnlyList BuildEnumValues() { var lastContractNames = LastContractView?.Properties.Select(p => p.Name).ToArray() ?? []; - var generatedNames = GetGeneratedValueNames(_allowedValues, lastContractNames); + var generatedNames = GetGeneratedValueNames(_allowedValues, lastContractNames, normalizeUppercase: true); var values = new EnumTypeMember[_allowedValues.Count]; for (int i = 0; i < _allowedValues.Count; i++) diff --git a/packages/http-client-csharp/generator/Microsoft.TypeSpec.Generator/test/Providers/EnumProviders/EnumProviderTests.cs b/packages/http-client-csharp/generator/Microsoft.TypeSpec.Generator/test/Providers/EnumProviders/EnumProviderTests.cs index 4f6fbc74326..91ea08e25ea 100644 --- a/packages/http-client-csharp/generator/Microsoft.TypeSpec.Generator/test/Providers/EnumProviders/EnumProviderTests.cs +++ b/packages/http-client-csharp/generator/Microsoft.TypeSpec.Generator/test/Providers/EnumProviders/EnumProviderTests.cs @@ -1184,6 +1184,24 @@ await MockHelpers.LoadMockGeneratorAsync( Assert.AreEqual("Other", enumType.Properties[1].Name); } + [TestCase("CallbackURL")] + [TestCase("CALLBACK_URL")] + public async Task BackCompat_ExtensibleEnumUrlSuffixPreservesUnderscoredName(string inputName) + { + await MockHelpers.LoadMockGeneratorAsync( + createCSharpTypeCore: _ => typeof(string), + lastContractCompilation: async () => await Helpers.GetCompilationFromDirectoryAsync()); + var input = InputFactory.StringEnum("mockInputEnum", [(inputName, "callback-url")], isExtensible: true); + + var enumType = EnumProvider.Create(input); + enumType.EnsureBuilt(); + enumType.ProcessTypeForBackCompatibility(); + + Assert.AreEqual("Callback_Url", enumType.Properties.Single().Name); + var field = enumType.Fields.Single(f => f.Name == "Callback_UrlValue"); + Assert.AreEqual("callback-url", ((LiteralExpression)field.InitializationValue!).Literal); + } + // Verifies that when custom code already implements the underscore-named member (e.g. the // user manually re-added 'Existing_Value' pointing at the generated 'ExistingValue'), the // underscore back-compat restoration does NOT rename the generated member. Otherwise the @@ -1348,6 +1366,69 @@ public void BuildEnumType_ExtensibleStringEnum_IsExactNameValuePreserved() Assert.AreEqual("snake_case_value", properties[1].Name); } + [Test] + public void BuildEnumType_ExtensibleStringEnum_MemberCasing() + { + MockHelpers.LoadMockGenerator(createCSharpTypeCore: _ => typeof(string)); + + var members = new (string Name, bool IsExactName)[] + { + ("AND", false), + ("OR", false), + ("NOT_FOUND", false), + ("FooOR", false), + ("ORfoo", false), + ("Foo_OR", false), + ("OR_foo", false), + ("ORFoo", false), + ("FooHTTP", false), + ("HTTPStatus", false), + ("HTTP2", false), + ("UTF8", false), + ("VM2", false), + ("IO2", false), + ("IPV4", false), + ("IPV6", false), + ("HTTP2foo", false), + ("HTTP2", true), + ("IOStream", false), + ("CallbackURL", false), + ("CALLBACKURL", false), + ("CALLBACK_URL", false), + ("AND", true), + }; + var values = new List(); + var input = InputFactory.Enum("MockInputEnum", InputPrimitiveType.String, values, isExtensible: true); + foreach (var member in members) + { + values.Add(InputFactory.EnumMember.String(member.Name, member.Name, input, isExactName: member.IsExactName)); + } + + var provider = EnumProvider.Create(input); + CollectionAssert.AreEqual( + new[] + { + "And", "Or", "NotFound", "FooOR", "ORfoo", "FooOr", "OrFoo", "ORFoo", "FooHTTP", "HTTPStatus", + "Http2", "Utf8", "Vm2", "Io2", "IPV4", "IPV6", "HTTP2foo", "HTTP2", "IOStream", "CallbackURL", + "Callbackurl", "CallbackUri", "AND" + }, + provider.Properties.Select(p => p.Name).ToArray()); + var content = new TypeProviderWriter(provider).Write().Content; + Assert.AreEqual(Helpers.GetExpectedFromFile(), content); + } + + [Test] + public void BuildEnumType_ExtensibleStringEnum_UnderscoredNumericSuffixCasing() + { + MockHelpers.LoadMockGenerator(createCSharpTypeCore: _ => typeof(string)); + var input = InputFactory.StringEnum("MockInputEnum", [("HTTP_2", "HTTP_2")], isExtensible: true); + + var provider = EnumProvider.Create(input); + + Assert.AreEqual("Http2", provider.Properties.Single().Name); + Assert.AreEqual("HTTP_2", ((LiteralExpression)provider.EnumValues.Single().Field.InitializationValue!).Literal); + } + [TestCase(false, "CallbackUrl", false, "CallbackUri")] [TestCase(true, "CallbackUrl", false, "CallbackUri")] [TestCase(false, "CallbackUrlValue", false, "CallbackUrlValue")] @@ -1374,16 +1455,17 @@ public void BuildEnumType_ReplacesCompleteUrlSuffixOnValues( Assert.AreEqual(expectedName, enumProvider.EnumValues.Single().Name); } - [TestCase(false, "Fixed")] - [TestCase(true, "Extensible")] - public async Task BuildEnumType_PreservesUrlSuffixFromLastContract(bool isExtensible, string testData) + [TestCase(false, "Fixed", "CallbackUrl")] + [TestCase(true, "Extensible", "CallbackUrl")] + [TestCase(true, "Extensible", "CallbackURL")] + public async Task BuildEnumType_PreservesUrlSuffixFromLastContract(bool isExtensible, string testData, string inputName) { await MockHelpers.LoadMockGeneratorAsync( createCSharpTypeCore: (inputType) => typeof(string), lastContractCompilation: async () => await Helpers.GetCompilationFromDirectoryAsync(parameters: testData)); var input = InputFactory.StringEnum( "mockInputEnum", - [("CallbackUrl", "value")], + [(inputName, "value")], isExtensible: isExtensible); var enumProvider = EnumProvider.Create(input); diff --git a/packages/http-client-csharp/generator/Microsoft.TypeSpec.Generator/test/Providers/EnumProviders/TestData/EnumProviderTests/BackCompat_ExtensibleEnumUrlSuffixPreservesUnderscoredName/MockInputEnum.cs b/packages/http-client-csharp/generator/Microsoft.TypeSpec.Generator/test/Providers/EnumProviders/TestData/EnumProviderTests/BackCompat_ExtensibleEnumUrlSuffixPreservesUnderscoredName/MockInputEnum.cs new file mode 100644 index 00000000000..2a6ba6c0cc6 --- /dev/null +++ b/packages/http-client-csharp/generator/Microsoft.TypeSpec.Generator/test/Providers/EnumProviders/TestData/EnumProviderTests/BackCompat_ExtensibleEnumUrlSuffixPreservesUnderscoredName/MockInputEnum.cs @@ -0,0 +1,7 @@ +namespace Sample.Models +{ + public readonly partial struct MockInputEnum + { + public static MockInputEnum Callback_Url { get; } + } +} diff --git a/packages/http-client-csharp/generator/Microsoft.TypeSpec.Generator/test/Providers/EnumProviders/TestData/EnumProviderTests/BuildEnumType_ExtensibleStringEnum_MemberCasing.cs b/packages/http-client-csharp/generator/Microsoft.TypeSpec.Generator/test/Providers/EnumProviders/TestData/EnumProviderTests/BuildEnumType_ExtensibleStringEnum_MemberCasing.cs new file mode 100644 index 00000000000..5a11fb6620d --- /dev/null +++ b/packages/http-client-csharp/generator/Microsoft.TypeSpec.Generator/test/Providers/EnumProviders/TestData/EnumProviderTests/BuildEnumType_ExtensibleStringEnum_MemberCasing.cs @@ -0,0 +1,109 @@ +// + +#nullable disable + +using System; +using System.ComponentModel; +using Sample; + +namespace Sample.Models +{ + public readonly partial struct MockInputEnum : global::System.IEquatable + { + private readonly string _value; + private const string AndValue = "AND"; + private const string OrValue = "OR"; + private const string NotFoundValue = "NOT_FOUND"; + private const string FooORValue = "FooOR"; + private const string ORfooValue = "ORfoo"; + private const string FooOrValue = "Foo_OR"; + private const string OrFooValue = "OR_foo"; + private const string ORFooValue = "ORFoo"; + private const string FooHTTPValue = "FooHTTP"; + private const string HTTPStatusValue = "HTTPStatus"; + private const string Http2Value = "HTTP2"; + private const string Utf8Value = "UTF8"; + private const string Vm2Value = "VM2"; + private const string Io2Value = "IO2"; + private const string IPV4Value = "IPV4"; + private const string IPV6Value = "IPV6"; + private const string HTTP2fooValue = "HTTP2foo"; + private const string HTTP2Value = "HTTP2"; + private const string IOStreamValue = "IOStream"; + private const string CallbackURLValue = "CallbackURL"; + private const string CallbackurlValue = "CALLBACKURL"; + private const string CallbackUriValue = "CALLBACK_URL"; + private const string ANDValue = "AND"; + + public MockInputEnum(string value) + { + global::Sample.Argument.AssertNotNull(value, nameof(value)); + + _value = value; + } + + public static global::Sample.Models.MockInputEnum And { get; } = new global::Sample.Models.MockInputEnum(AndValue); + + public static global::Sample.Models.MockInputEnum Or { get; } = new global::Sample.Models.MockInputEnum(OrValue); + + public static global::Sample.Models.MockInputEnum NotFound { get; } = new global::Sample.Models.MockInputEnum(NotFoundValue); + + public static global::Sample.Models.MockInputEnum FooOR { get; } = new global::Sample.Models.MockInputEnum(FooORValue); + + public static global::Sample.Models.MockInputEnum ORfoo { get; } = new global::Sample.Models.MockInputEnum(ORfooValue); + + public static global::Sample.Models.MockInputEnum FooOr { get; } = new global::Sample.Models.MockInputEnum(FooOrValue); + + public static global::Sample.Models.MockInputEnum OrFoo { get; } = new global::Sample.Models.MockInputEnum(OrFooValue); + + public static global::Sample.Models.MockInputEnum ORFoo { get; } = new global::Sample.Models.MockInputEnum(ORFooValue); + + public static global::Sample.Models.MockInputEnum FooHTTP { get; } = new global::Sample.Models.MockInputEnum(FooHTTPValue); + + public static global::Sample.Models.MockInputEnum HTTPStatus { get; } = new global::Sample.Models.MockInputEnum(HTTPStatusValue); + + public static global::Sample.Models.MockInputEnum Http2 { get; } = new global::Sample.Models.MockInputEnum(Http2Value); + + public static global::Sample.Models.MockInputEnum Utf8 { get; } = new global::Sample.Models.MockInputEnum(Utf8Value); + + public static global::Sample.Models.MockInputEnum Vm2 { get; } = new global::Sample.Models.MockInputEnum(Vm2Value); + + public static global::Sample.Models.MockInputEnum Io2 { get; } = new global::Sample.Models.MockInputEnum(Io2Value); + + public static global::Sample.Models.MockInputEnum IPV4 { get; } = new global::Sample.Models.MockInputEnum(IPV4Value); + + public static global::Sample.Models.MockInputEnum IPV6 { get; } = new global::Sample.Models.MockInputEnum(IPV6Value); + + public static global::Sample.Models.MockInputEnum HTTP2foo { get; } = new global::Sample.Models.MockInputEnum(HTTP2fooValue); + + public static global::Sample.Models.MockInputEnum HTTP2 { get; } = new global::Sample.Models.MockInputEnum(HTTP2Value); + + public static global::Sample.Models.MockInputEnum IOStream { get; } = new global::Sample.Models.MockInputEnum(IOStreamValue); + + public static global::Sample.Models.MockInputEnum CallbackURL { get; } = new global::Sample.Models.MockInputEnum(CallbackURLValue); + + public static global::Sample.Models.MockInputEnum Callbackurl { get; } = new global::Sample.Models.MockInputEnum(CallbackurlValue); + + public static global::Sample.Models.MockInputEnum CallbackUri { get; } = new global::Sample.Models.MockInputEnum(CallbackUriValue); + + public static global::Sample.Models.MockInputEnum AND { get; } = new global::Sample.Models.MockInputEnum(ANDValue); + + public static bool operator ==(global::Sample.Models.MockInputEnum left, global::Sample.Models.MockInputEnum right) => left.Equals(right); + + public static bool operator !=(global::Sample.Models.MockInputEnum left, global::Sample.Models.MockInputEnum right) => !left.Equals(right); + + public static implicit operator global::Sample.Models.MockInputEnum(string value) => new global::Sample.Models.MockInputEnum(value); + + public static implicit operator global::Sample.Models.MockInputEnum?(string value) => (value == null) ? ((global::Sample.Models.MockInputEnum?)null) : new global::Sample.Models.MockInputEnum(value); + + [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Never)] + public override bool Equals(object obj) => ((obj is global::Sample.Models.MockInputEnum other) && this.Equals(other)); + + public bool Equals(global::Sample.Models.MockInputEnum other) => string.Equals(_value, other._value, global::System.StringComparison.InvariantCultureIgnoreCase); + + [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Never)] + public override int GetHashCode() => (_value != null) ? global::System.StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + + public override string ToString() => _value; + } +}