diff --git a/CHANGELOG.md b/CHANGELOG.md index df964aa..e95ae17 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,16 @@ # Changelog +## [1.3.0] - 2026-10-28 + +### Added +- **Smart Parameter Types = Mapping**: set the type of each smart string parameter with the new + **Localization Codegen / Smart Parameter Types** metadata on a shared table entry (`count` → `Int`, + `0` → `DateTime`, …). The table text does not change. Parameters without a type are inferred like `Inferred`, + and positional parameters can be typed too. +- Warnings when a mapped type cannot be formatted by `plural` (`String`, `Bool`, `Char`, `DateTime`, `Object`) or + `list` (anything but `List`), and for mapped names that are not parameters of the entry, empty or listed twice. +- Changing **Smart Strings** or **Smart Parameter Types** in the settings asks whether to regenerate the code. + ## [1.2.2] - 2026-10-26 ### Changed diff --git a/Installer/Assets/Editor/Localization Codegen Installer/Installer.cs b/Installer/Assets/Editor/Localization Codegen Installer/Installer.cs index 62647bd..503c293 100644 --- a/Installer/Assets/Editor/Localization Codegen Installer/Installer.cs +++ b/Installer/Assets/Editor/Localization Codegen Installer/Installer.cs @@ -16,7 +16,7 @@ namespace Severnbli.LocalizationCodegen.Installer public static partial class Installer { public const string PackageId = "com.severnbli.localization-codegen"; - public const string Version = "1.2.2"; + public const string Version = "1.3.0"; static Installer() { diff --git a/README.md b/README.md index 569607c..3d7198b 100644 --- a/README.md +++ b/README.md @@ -134,7 +134,7 @@ Add the scoped registry and the dependency to `Packages/manifest.json`: } ], "dependencies": { - "com.severnbli.localization-codegen": "1.2.2" + "com.severnbli.localization-codegen": "1.3.0" } } ``` @@ -254,12 +254,43 @@ public static string Greeting(object arg0, int count) - `{}` (the current value inside a formatter) is not a parameter. - Variables provided by a **Global Variables Group** are not parameters; Unity resolves them. - **Smart Parameter Types = Inferred** uses `int` for `plural`, `IEnumerable` for `list`, otherwise `object`. +- **Smart Parameter Types = Mapping** uses the types you set in the entry's [Smart Parameter Types metadata](#parameter-types) and infers the rest like `Inferred`. +- Changing **Smart Strings** or **Smart Parameter Types** asks whether to regenerate, since method signatures change. - Placeholder differences between locales are reported as warnings. Enable **Fail CI On Smart String Mismatch** to make `CheckBatch` fail on them. - **MethodsAndRefs** additionally emits `Ref.Greeting(...)` returning a `LocalizedString` whose arguments and local variables are set. > [!NOTE] > Smart strings are opt-in. Upgraded projects default to `Off`; new projects default to `Methods` when the setup wizard completes. +#### Parameter types + +With **Smart Parameter Types = Mapping**, you choose parameter types per entry. The types are stored as entry metadata, so the text players see never changes. + +1. Open the collection in **Window > Asset Management > Localization Tables** and open the metadata of the key (shared by all locales). +2. Add **Localization Codegen / Smart Parameter Types**. +3. Add one row per parameter: the variable name as written in the string (`count`, or `0` for `{0}`) and a type. + +```csharp +// "{player} has {count:plural:one coin|{} coins}" with player = String, count = Int +public static string Coins(int count, string player) + => LocalizedTables.GetString(TableName, "Coins", + new Dictionary { ["count"] = count, ["player"] = player }); +``` + +| Type | C# type | +|---|---| +| `Object` | `object` | +| `String` | `string` | +| `Int`, `Long`, `Float`, `Double`, `Decimal`, `Bool`, `Char` | `int`, `long`, `float`, `double`, `decimal`, `bool`, `char` | +| `DateTime` | `System.DateTime` | +| `List` | `System.Collections.IEnumerable` | + +Parameters without a row are inferred. These cases are reported as warnings: + +- A type that `plural` cannot format (`String`, `Bool`, `Char`, `DateTime`, `Object`) on a variable used with `plural`. `plural` needs a number or a collection. +- A type other than `List` on a variable used with `list`. +- A row whose name is not a parameter of the entry (for example after renaming a placeholder), a row without a name, and a name listed twice (the first row wins). + ### Reference members The regular members return a **value**: `Ui.HelloWorld` is the text in the current locale at the moment you read it. When the player switches language, a label you filled that way keeps the old text. @@ -326,7 +357,7 @@ Open **Project Settings > Localization Codegen**, or **Window > Localization Cod | Generate Reference Members | off | Emit the nested [`Ref` class](#reference-members). | | XML Documentation | off | Add XML docs with the default locale text and smart string parameters. | | Smart Strings | off (upgraded) / `Methods` (new) | `Off`, `Methods` or `MethodsAndRefs`. | -| Smart Parameter Types | `Object` | `Object` or `Inferred`. | +| Smart Parameter Types | `Object` | `Object`, `Inferred` or [`Mapping`](#parameter-types). | | Naming Convention | `Keep` | `Keep` or `PascalCase`. | | Key Separators | empty | Characters that create nested classes, e.g. `/`. | | UniTask Members | off | Also emit [`…Async` members](#unitask) returning `UniTask`. Requires UniTask. | diff --git a/Unity-Package/Assets/root/CHANGELOG.md b/Unity-Package/Assets/root/CHANGELOG.md index df964aa..e95ae17 100644 --- a/Unity-Package/Assets/root/CHANGELOG.md +++ b/Unity-Package/Assets/root/CHANGELOG.md @@ -1,5 +1,16 @@ # Changelog +## [1.3.0] - 2026-10-28 + +### Added +- **Smart Parameter Types = Mapping**: set the type of each smart string parameter with the new + **Localization Codegen / Smart Parameter Types** metadata on a shared table entry (`count` → `Int`, + `0` → `DateTime`, …). The table text does not change. Parameters without a type are inferred like `Inferred`, + and positional parameters can be typed too. +- Warnings when a mapped type cannot be formatted by `plural` (`String`, `Bool`, `Char`, `DateTime`, `Object`) or + `list` (anything but `List`), and for mapped names that are not parameters of the entry, empty or listed twice. +- Changing **Smart Strings** or **Smart Parameter Types** in the settings asks whether to regenerate the code. + ## [1.2.2] - 2026-10-26 ### Changed diff --git a/Unity-Package/Assets/root/Editor/CodegenModel.cs b/Unity-Package/Assets/root/Editor/CodegenModel.cs index 4ff1c8e..c27be9e 100644 --- a/Unity-Package/Assets/root/Editor/CodegenModel.cs +++ b/Unity-Package/Assets/root/Editor/CodegenModel.cs @@ -22,7 +22,10 @@ public enum NamingConvention public enum SmartParamTypeMode { Object = 0, - Inferred = 1 + Inferred = 1, + + /// Types from entry metadata; other parameters are inferred. + Mapping = 2 } /// A table collection reduced to the information the emitter needs. diff --git a/Unity-Package/Assets/root/Editor/CodegenSettings.cs b/Unity-Package/Assets/root/Editor/CodegenSettings.cs index ab3bc71..ef5a58f 100644 --- a/Unity-Package/Assets/root/Editor/CodegenSettings.cs +++ b/Unity-Package/Assets/root/Editor/CodegenSettings.cs @@ -73,7 +73,7 @@ public NamingConvention Naming public SmartParamTypeMode SmartParamTypes { - get => (SmartParamTypeMode)Mathf.Clamp(smartParamTypes, 0, 1); + get => (SmartParamTypeMode)Mathf.Clamp(smartParamTypes, 0, 2); set => smartParamTypes = (int)value; } diff --git a/Unity-Package/Assets/root/Editor/SettingsGui.cs b/Unity-Package/Assets/root/Editor/SettingsGui.cs index 8d4e35d..9d68db2 100644 --- a/Unity-Package/Assets/root/Editor/SettingsGui.cs +++ b/Unity-Package/Assets/root/Editor/SettingsGui.cs @@ -36,7 +36,8 @@ internal static class Content public static readonly GUIContent SmartStrings = new GUIContent("Smart Strings", "Generate methods with parameters for smart string entries. Off keeps the 1.0 behaviour."); public static readonly GUIContent SmartParamTypes = new GUIContent("Smart Parameter Types", - "Object uses object for every named parameter. Inferred uses int for plural and IEnumerable for list."); + "Object uses object for every named parameter. Inferred uses int for plural and IEnumerable for list. " + + "Mapping uses the types from the Smart Parameter Types metadata of an entry and infers the rest."); public static readonly GUIContent References = new GUIContent("Generate Reference Members", "Emit a nested Ref class with LocalizedString / LocalizedAsset references that follow locale changes."); public static readonly GUIContent UniTask = new GUIContent("UniTask Members", @@ -85,6 +86,7 @@ public static bool Draw() s.EnsureMigrated(); var oldSmartStrings = s.SmartStrings; + var oldSmartParamTypes = s.SmartParamTypes; var oldLabelWidth = EditorGUIUtility.labelWidth; EditorGUIUtility.labelWidth = LabelWidth; EditorGUI.BeginChangeCheck(); @@ -101,7 +103,13 @@ public static bool Draw() if (changed) { s.SaveSettings(); - CodegenHooks.MarkDirtyExternal(); + + var smartChanged = s.SmartStrings != oldSmartStrings || s.SmartParamTypes != oldSmartParamTypes; + // The setup wizard generates when it finishes, so it is not asked about. + if (smartChanged && s.SetupCompleted) + PromptRegenerate(); + else + CodegenHooks.MarkDirtyExternal(); if (oldSmartStrings == SmartStringMode.Off && s.SmartStrings != SmartStringMode.Off) CodeGenerator.LogPropertyToMethodChanges(); @@ -110,6 +118,32 @@ public static bool Draw() return changed; } + static bool s_RegeneratePromptPending; + + /// + /// Asks whether to regenerate after the smart string settings change, since they change method signatures. + /// The dialog opens after the current GUI pass, and only once for several changes in a row. + /// + static void PromptRegenerate() + { + if (s_RegeneratePromptPending) + return; + + s_RegeneratePromptPending = true; + EditorApplication.delayCall += () => + { + s_RegeneratePromptPending = false; + if (EditorUtility.DisplayDialog( + "Localization Codegen", + "The smart string settings changed the generated method signatures. Regenerate the code now?", + "Regenerate", + "Later")) + { + CodeGenerator.Run(new GenerateOptions { IsAutomatic = false, PromptOnMassDeletion = true }); + } + }; + } + /// A collapsible section whose open state is remembered per user. static void Section(string id, GUIContent title, System.Action body) { diff --git a/Unity-Package/Assets/root/Editor/SmartParameterMapping.cs b/Unity-Package/Assets/root/Editor/SmartParameterMapping.cs new file mode 100644 index 0000000..1363fad --- /dev/null +++ b/Unity-Package/Assets/root/Editor/SmartParameterMapping.cs @@ -0,0 +1,141 @@ +using System; +using System.Collections.Generic; +using System.Linq; + +namespace Severnbli.LocalizationCodegen.Editor +{ + /// + /// Applies metadata to the parameters of a smart string entry + /// (). + /// + internal static class SmartParameterMapping + { + /// C# type name emitted for a mapped type. + public static string TypeName(SmartParameterType type) + { + switch (type) + { + case SmartParameterType.String: return "string"; + case SmartParameterType.Int: return "int"; + case SmartParameterType.Long: return "long"; + case SmartParameterType.Float: return "float"; + case SmartParameterType.Double: return "double"; + case SmartParameterType.Decimal: return "decimal"; + case SmartParameterType.Bool: return "bool"; + case SmartParameterType.Char: return "char"; + case SmartParameterType.DateTime: return "System.DateTime"; + case SmartParameterType.List: return "System.Collections.IEnumerable"; + default: return "object"; + } + } + + /// + /// Whether the plural formatter can format a value of this type. It takes numbers and collections; strings, + /// booleans, dates and characters (whose ToDecimal throws) make it fail at runtime. + /// + public static bool AcceptsPlural(SmartParameterType type) + { + switch (type) + { + case SmartParameterType.Int: + case SmartParameterType.Long: + case SmartParameterType.Float: + case SmartParameterType.Double: + case SmartParameterType.Decimal: + case SmartParameterType.List: + return true; + default: + return false; + } + } + + /// Whether the list formatter can format a value of this type. + public static bool AcceptsList(SmartParameterType type) => type == SmartParameterType.List; + + /// + /// Sets the type of every parameter named in and reports duplicate hints, hints + /// without a parameter, and types the plural or list formatter cannot format. + /// + public static void Apply( + EntryModel entry, + IList hints, + List warnings, + string collectionName, + string key) + { + if (hints == null || hints.Count == 0) + return; + + var prefix = $"Collection '{collectionName}', key '{key}': "; + var seen = new HashSet(StringComparer.Ordinal); + + foreach (var hint in hints) + { + if (hint == null) + continue; + + var name = NormalizeName(hint.Name); + if (name.Length == 0) + { + warnings.Add(prefix + "Smart Parameter Types has a parameter without a name."); + continue; + } + + if (!seen.Add(name)) + { + warnings.Add(prefix + $"Smart Parameter Types lists '{name}' more than once; the first type is used."); + continue; + } + + var param = entry.Params.FirstOrDefault(p => string.Equals(p.SourceName, name, StringComparison.Ordinal)); + if (param == null) + { + warnings.Add(prefix + $"Smart Parameter Types lists '{name}', which is not a parameter of this entry."); + continue; + } + + param.TypeName = TypeName(hint.Type); + + var formatters = FormattersOf(entry, param); + if (formatters.Any(IsPlural) && !AcceptsPlural(hint.Type)) + { + warnings.Add(prefix + + $"variable '{name}' is declared as {hint.Type} but used with plural, which needs a number " + + "or a collection. Plural will not format it at runtime."); + } + + if (formatters.Any(IsList) && !AcceptsList(hint.Type)) + { + warnings.Add(prefix + + $"variable '{name}' is declared as {hint.Type} but used with list, which needs a collection. " + + "List will not format it at runtime."); + } + } + } + + /// Accepts count, 0 and {0}. + static string NormalizeName(string name) + { + return (name ?? "").Trim().TrimStart('{').TrimEnd('}').Trim(); + } + + static List FormattersOf(EntryModel entry, SmartParam param) + { + return entry.Usages + .Where(u => param.IsPositional + ? u.IsPositional && u.Index == param.Index + : !u.IsPositional && string.Equals(u.SourceName, param.SourceName, StringComparison.Ordinal)) + .Select(u => u.FormatterName) + .Where(f => !string.IsNullOrEmpty(f)) + .ToList(); + } + + static bool IsPlural(string formatter) => + string.Equals(formatter, "plural", StringComparison.OrdinalIgnoreCase) || + string.Equals(formatter, "p", StringComparison.OrdinalIgnoreCase); + + static bool IsList(string formatter) => + string.Equals(formatter, "list", StringComparison.OrdinalIgnoreCase) || + string.Equals(formatter, "l", StringComparison.OrdinalIgnoreCase); + } +} diff --git a/Unity-Package/Assets/root/Editor/SmartParameterMapping.cs.meta b/Unity-Package/Assets/root/Editor/SmartParameterMapping.cs.meta new file mode 100644 index 0000000..00da0f8 --- /dev/null +++ b/Unity-Package/Assets/root/Editor/SmartParameterMapping.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 018ec9411a4149938065dd2f83546fb8 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Unity-Package/Assets/root/Editor/TableReader.cs b/Unity-Package/Assets/root/Editor/TableReader.cs index d9d5c9d..0b2a898 100644 --- a/Unity-Package/Assets/root/Editor/TableReader.cs +++ b/Unity-Package/Assets/root/Editor/TableReader.cs @@ -432,6 +432,15 @@ void ReadSmartEntry( modelEntry.Preview = FindFirstValue(collection, sharedEntry.Id); BuildParams(modelEntry, warnings, collectionName, sharedEntry.Key); + if (m_Options.SmartParamTypes == SmartParamTypeMode.Mapping) + { + SmartParameterMapping.Apply( + modelEntry, + sharedEntry.Metadata?.GetMetadata()?.Parameters, + warnings, + collectionName, + sharedEntry.Key); + } ValidateLocales(modelEntry, referenceUsages, referenceLocale, warnings, collectionName, sharedEntry.Key); } diff --git a/Unity-Package/Assets/root/README.md b/Unity-Package/Assets/root/README.md index 569607c..3d7198b 100644 --- a/Unity-Package/Assets/root/README.md +++ b/Unity-Package/Assets/root/README.md @@ -134,7 +134,7 @@ Add the scoped registry and the dependency to `Packages/manifest.json`: } ], "dependencies": { - "com.severnbli.localization-codegen": "1.2.2" + "com.severnbli.localization-codegen": "1.3.0" } } ``` @@ -254,12 +254,43 @@ public static string Greeting(object arg0, int count) - `{}` (the current value inside a formatter) is not a parameter. - Variables provided by a **Global Variables Group** are not parameters; Unity resolves them. - **Smart Parameter Types = Inferred** uses `int` for `plural`, `IEnumerable` for `list`, otherwise `object`. +- **Smart Parameter Types = Mapping** uses the types you set in the entry's [Smart Parameter Types metadata](#parameter-types) and infers the rest like `Inferred`. +- Changing **Smart Strings** or **Smart Parameter Types** asks whether to regenerate, since method signatures change. - Placeholder differences between locales are reported as warnings. Enable **Fail CI On Smart String Mismatch** to make `CheckBatch` fail on them. - **MethodsAndRefs** additionally emits `Ref.Greeting(...)` returning a `LocalizedString` whose arguments and local variables are set. > [!NOTE] > Smart strings are opt-in. Upgraded projects default to `Off`; new projects default to `Methods` when the setup wizard completes. +#### Parameter types + +With **Smart Parameter Types = Mapping**, you choose parameter types per entry. The types are stored as entry metadata, so the text players see never changes. + +1. Open the collection in **Window > Asset Management > Localization Tables** and open the metadata of the key (shared by all locales). +2. Add **Localization Codegen / Smart Parameter Types**. +3. Add one row per parameter: the variable name as written in the string (`count`, or `0` for `{0}`) and a type. + +```csharp +// "{player} has {count:plural:one coin|{} coins}" with player = String, count = Int +public static string Coins(int count, string player) + => LocalizedTables.GetString(TableName, "Coins", + new Dictionary { ["count"] = count, ["player"] = player }); +``` + +| Type | C# type | +|---|---| +| `Object` | `object` | +| `String` | `string` | +| `Int`, `Long`, `Float`, `Double`, `Decimal`, `Bool`, `Char` | `int`, `long`, `float`, `double`, `decimal`, `bool`, `char` | +| `DateTime` | `System.DateTime` | +| `List` | `System.Collections.IEnumerable` | + +Parameters without a row are inferred. These cases are reported as warnings: + +- A type that `plural` cannot format (`String`, `Bool`, `Char`, `DateTime`, `Object`) on a variable used with `plural`. `plural` needs a number or a collection. +- A type other than `List` on a variable used with `list`. +- A row whose name is not a parameter of the entry (for example after renaming a placeholder), a row without a name, and a name listed twice (the first row wins). + ### Reference members The regular members return a **value**: `Ui.HelloWorld` is the text in the current locale at the moment you read it. When the player switches language, a label you filled that way keeps the old text. @@ -326,7 +357,7 @@ Open **Project Settings > Localization Codegen**, or **Window > Localization Cod | Generate Reference Members | off | Emit the nested [`Ref` class](#reference-members). | | XML Documentation | off | Add XML docs with the default locale text and smart string parameters. | | Smart Strings | off (upgraded) / `Methods` (new) | `Off`, `Methods` or `MethodsAndRefs`. | -| Smart Parameter Types | `Object` | `Object` or `Inferred`. | +| Smart Parameter Types | `Object` | `Object`, `Inferred` or [`Mapping`](#parameter-types). | | Naming Convention | `Keep` | `Keep` or `PascalCase`. | | Key Separators | empty | Characters that create nested classes, e.g. `/`. | | UniTask Members | off | Also emit [`…Async` members](#unitask) returning `UniTask`. Requires UniTask. | diff --git a/Unity-Package/Assets/root/Runtime/SmartParameterTypes.cs b/Unity-Package/Assets/root/Runtime/SmartParameterTypes.cs new file mode 100644 index 0000000..bf6306c --- /dev/null +++ b/Unity-Package/Assets/root/Runtime/SmartParameterTypes.cs @@ -0,0 +1,76 @@ +using System; +using System.Collections.Generic; +using UnityEngine; +using UnityEngine.Localization.Metadata; + +namespace Severnbli.LocalizationCodegen +{ + /// Parameter type a generated smart string method uses. + public enum SmartParameterType + { + Object = 0, + String = 1, + Int = 2, + Long = 3, + Float = 4, + Double = 5, + Decimal = 6, + Bool = 7, + Char = 8, + DateTime = 9, + List = 10 + } + + /// + /// Shared entry metadata that sets the parameter types of a generated smart string method when + /// Smart Parameter Types is Mapping. Parameters without a type here are inferred. + /// + /// + /// Only the code generator reads this metadata. It lives in the runtime assembly because table assets + /// serialize it, and a player build must be able to load the type. + /// + [Metadata(AllowedTypes = MetadataType.SharedStringTableEntry, AllowMultiple = false, + MenuItem = "Localization Codegen/Smart Parameter Types")] + [Serializable] + public sealed class SmartParameterTypes : IMetadata + { + /// The type of one smart string variable. + [Serializable] + public sealed class Parameter + { + [SerializeField] + [Tooltip("Variable name as written in the smart string, e.g. count, or an index such as 0 for {0}.")] + string m_Name = ""; + + [SerializeField] + SmartParameterType m_Type = SmartParameterType.Object; + + public Parameter() + { + } + + public Parameter(string name, SmartParameterType type) + { + m_Name = name ?? ""; + m_Type = type; + } + + public string Name + { + get => m_Name ?? ""; + set => m_Name = value ?? ""; + } + + public SmartParameterType Type + { + get => m_Type; + set => m_Type = value; + } + } + + [SerializeField] + List m_Parameters = new List(); + + public List Parameters => m_Parameters ?? (m_Parameters = new List()); + } +} diff --git a/Unity-Package/Assets/root/Runtime/SmartParameterTypes.cs.meta b/Unity-Package/Assets/root/Runtime/SmartParameterTypes.cs.meta new file mode 100644 index 0000000..3a08cef --- /dev/null +++ b/Unity-Package/Assets/root/Runtime/SmartParameterTypes.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 7cf0aaa1e2e74ec7b338858e34210224 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Unity-Package/Assets/root/Tests/Editor/GeneratedCodeCompilationTests.cs b/Unity-Package/Assets/root/Tests/Editor/GeneratedCodeCompilationTests.cs index 1e68118..a194485 100644 --- a/Unity-Package/Assets/root/Tests/Editor/GeneratedCodeCompilationTests.cs +++ b/Unity-Package/Assets/root/Tests/Editor/GeneratedCodeCompilationTests.cs @@ -216,6 +216,14 @@ static List BuildModels() }); strings.Entries.Add(mixed); + // Types from Smart Parameter Types metadata, including a typed positional parameter. + var mapped = new EntryModel { Id = 11, Key = "Mapped" }; + mapped.Params.Add(new SmartParam { IsPositional = true, Index = 0, SourceName = "0", ClrName = "arg0", TypeName = "int" }); + mapped.Params.Add(new SmartParam { SourceName = "name", ClrName = "name", TypeName = "string" }); + mapped.Params.Add(new SmartParam { SourceName = "price", ClrName = "price", TypeName = "decimal" }); + mapped.Params.Add(new SmartParam { SourceName = "when", ClrName = "when", TypeName = "System.DateTime" }); + strings.Entries.Add(mapped); + var assets = new TableModel { Name = "Ui", IsAsset = true }; assets.Entries.Add(new EntryModel { Id = 1, Key = "Logo", AssetTypeName = "UnityEngine.Sprite" }); assets.Entries.Add(new EntryModel { Id = 2, Key = "Theme", AssetTypeName = "UnityEngine.AudioClip" }); diff --git a/Unity-Package/Assets/root/Tests/Editor/SmartParameterMappingTests.cs b/Unity-Package/Assets/root/Tests/Editor/SmartParameterMappingTests.cs new file mode 100644 index 0000000..6fcd4f3 --- /dev/null +++ b/Unity-Package/Assets/root/Tests/Editor/SmartParameterMappingTests.cs @@ -0,0 +1,180 @@ +using System.Collections.Generic; +using System.Linq; +using NUnit.Framework; + +namespace Severnbli.LocalizationCodegen.Editor.Tests +{ + public class SmartParameterMappingTests + { + static EntryModel Entry() + { + // "{0} {player} has {count:plural:one coin|{} coins}: {items:list:{}|, }" + var entry = new EntryModel { Id = 1, Key = "Coins" }; + entry.Params.Add(new SmartParam { IsPositional = true, Index = 0, SourceName = "0", ClrName = "arg0", TypeName = "object" }); + entry.Params.Add(new SmartParam { SourceName = "count", ClrName = "count", TypeName = "int", FormatterName = "plural" }); + entry.Params.Add(new SmartParam + { + SourceName = "items", ClrName = "items", TypeName = "System.Collections.IEnumerable", FormatterName = "list" + }); + entry.Params.Add(new SmartParam { SourceName = "player", ClrName = "player", TypeName = "object" }); + + foreach (var locale in new[] { "en", "de" }) + { + entry.Usages.Add(new SmartVariableUsage { Locale = locale, IsPositional = true, Index = 0 }); + entry.Usages.Add(new SmartVariableUsage { Locale = locale, SourceName = "player" }); + entry.Usages.Add(new SmartVariableUsage { Locale = locale, SourceName = "count", FormatterName = "plural" }); + entry.Usages.Add(new SmartVariableUsage { Locale = locale, SourceName = "items", FormatterName = "list" }); + } + return entry; + } + + static List Apply(EntryModel entry, params SmartParameterTypes.Parameter[] hints) + { + var warnings = new List(); + SmartParameterMapping.Apply(entry, hints.ToList(), warnings, "Ui", "Coins"); + return warnings; + } + + static string TypeOf(EntryModel entry, string sourceName) => + entry.Params.Single(p => p.SourceName == sourceName).TypeName; + + static SmartParameterTypes.Parameter Hint(string name, SmartParameterType type) => + new SmartParameterTypes.Parameter(name, type); + + [Test] + public void Hints_SetNamedAndPositionalTypes() + { + var entry = Entry(); + var warnings = Apply(entry, + Hint("player", SmartParameterType.String), + Hint("count", SmartParameterType.Long), + Hint("0", SmartParameterType.DateTime)); + + CollectionAssert.IsEmpty(warnings); + Assert.AreEqual("string", TypeOf(entry, "player")); + Assert.AreEqual("long", TypeOf(entry, "count")); + Assert.AreEqual("System.DateTime", TypeOf(entry, "0")); + } + + [Test] + public void ParametersWithoutHint_KeepTheInferredType() + { + var entry = Entry(); + Apply(entry, Hint("player", SmartParameterType.String)); + + Assert.AreEqual("int", TypeOf(entry, "count")); + Assert.AreEqual("System.Collections.IEnumerable", TypeOf(entry, "items")); + Assert.AreEqual("object", TypeOf(entry, "0")); + } + + [Test] + public void NoHints_ChangeNothing() + { + var entry = Entry(); + var warnings = new List(); + SmartParameterMapping.Apply(entry, null, warnings, "Ui", "Coins"); + + CollectionAssert.IsEmpty(warnings); + Assert.AreEqual("object", TypeOf(entry, "player")); + Assert.AreEqual("int", TypeOf(entry, "count")); + } + + [Test] + public void BracedIndex_MatchesPositionalParameter() + { + var entry = Entry(); + var warnings = Apply(entry, Hint(" {0} ", SmartParameterType.Int)); + + CollectionAssert.IsEmpty(warnings); + Assert.AreEqual("int", TypeOf(entry, "0")); + } + + [TestCase(SmartParameterType.String)] + [TestCase(SmartParameterType.Bool)] + [TestCase(SmartParameterType.Char)] + [TestCase(SmartParameterType.DateTime)] + [TestCase(SmartParameterType.Object)] + public void PluralWithWrongType_Warns(SmartParameterType type) + { + var entry = Entry(); + var warnings = Apply(entry, Hint("count", type)); + + Assert.AreEqual(1, warnings.Count, string.Join("\n", warnings)); + StringAssert.Contains($"variable 'count' is declared as {type} but used with plural", warnings[0]); + StringAssert.StartsWith("Collection 'Ui', key 'Coins': ", warnings[0]); + // The declared type is still used. + Assert.AreEqual(SmartParameterMapping.TypeName(type), TypeOf(entry, "count")); + } + + [TestCase(SmartParameterType.Int)] + [TestCase(SmartParameterType.Long)] + [TestCase(SmartParameterType.Float)] + [TestCase(SmartParameterType.Double)] + [TestCase(SmartParameterType.Decimal)] + [TestCase(SmartParameterType.List)] + public void PluralWithNumberOrCollection_DoesNotWarn(SmartParameterType type) + { + CollectionAssert.IsEmpty(Apply(Entry(), Hint("count", type))); + } + + [Test] + public void PluralShortName_IsChecked() + { + var entry = Entry(); + foreach (var usage in entry.Usages.Where(u => u.SourceName == "count")) + usage.FormatterName = "p"; + + var warnings = Apply(entry, Hint("count", SmartParameterType.String)); + Assert.AreEqual(1, warnings.Count, string.Join("\n", warnings)); + StringAssert.Contains("used with plural", warnings[0]); + } + + [Test] + public void ListWithNonCollectionType_Warns() + { + var warnings = Apply(Entry(), Hint("items", SmartParameterType.String)); + + Assert.AreEqual(1, warnings.Count, string.Join("\n", warnings)); + StringAssert.Contains("variable 'items' is declared as String but used with list", warnings[0]); + } + + [Test] + public void UnknownName_Warns() + { + var entry = Entry(); + var warnings = Apply(entry, Hint("score", SmartParameterType.Int)); + + Assert.AreEqual(1, warnings.Count); + StringAssert.Contains("lists 'score', which is not a parameter of this entry", warnings[0]); + } + + [Test] + public void DuplicateName_WarnsAndKeepsTheFirstType() + { + var entry = Entry(); + var warnings = Apply(entry, + Hint("player", SmartParameterType.String), + Hint("player", SmartParameterType.Int)); + + Assert.AreEqual(1, warnings.Count); + StringAssert.Contains("lists 'player' more than once", warnings[0]); + Assert.AreEqual("string", TypeOf(entry, "player")); + } + + [Test] + public void EmptyName_Warns() + { + var warnings = Apply(Entry(), Hint(" ", SmartParameterType.Int)); + + Assert.AreEqual(1, warnings.Count); + StringAssert.Contains("parameter without a name", warnings[0]); + } + + [Test] + public void EveryType_HasATypeName() + { + foreach (SmartParameterType type in System.Enum.GetValues(typeof(SmartParameterType))) + Assert.IsFalse(string.IsNullOrEmpty(SmartParameterMapping.TypeName(type)), type.ToString()); + } + } +} diff --git a/Unity-Package/Assets/root/Tests/Editor/SmartParameterMappingTests.cs.meta b/Unity-Package/Assets/root/Tests/Editor/SmartParameterMappingTests.cs.meta new file mode 100644 index 0000000..f4415f6 --- /dev/null +++ b/Unity-Package/Assets/root/Tests/Editor/SmartParameterMappingTests.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 6b10e12282ea435aa2cc39d95038c777 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Unity-Package/Assets/root/package.json b/Unity-Package/Assets/root/package.json index 36878e5..65458fa 100644 --- a/Unity-Package/Assets/root/package.json +++ b/Unity-Package/Assets/root/package.json @@ -10,7 +10,7 @@ "Generation", "Code Generation" ], - "version": "1.2.2", + "version": "1.3.0", "unity": "2021.3", "description": "C# classes and properties generator from Unity Localization tables", "documentationUrl": "https://github.com/Severnbli/localization-codegen/blob/main/README.md",