Skip to content
Merged
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
11 changes: 11 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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()
{
Expand Down
35 changes: 33 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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"
}
}
```
Expand Down Expand Up @@ -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<string, object> { ["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.
Expand Down Expand Up @@ -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. |
Expand Down
11 changes: 11 additions & 0 deletions Unity-Package/Assets/root/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -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
Expand Down
5 changes: 4 additions & 1 deletion Unity-Package/Assets/root/Editor/CodegenModel.cs
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,10 @@ public enum NamingConvention
public enum SmartParamTypeMode
{
Object = 0,
Inferred = 1
Inferred = 1,

/// <summary>Types from <see cref="SmartParameterTypes"/> entry metadata; other parameters are inferred.</summary>
Mapping = 2
}

/// <summary>A table collection reduced to the information the emitter needs.</summary>
Expand Down
2 changes: 1 addition & 1 deletion Unity-Package/Assets/root/Editor/CodegenSettings.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}

Expand Down
38 changes: 36 additions & 2 deletions Unity-Package/Assets/root/Editor/SettingsGui.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down Expand Up @@ -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();
Expand All @@ -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();
Expand All @@ -110,6 +118,32 @@ public static bool Draw()
return changed;
}

static bool s_RegeneratePromptPending;

/// <summary>
/// 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.
/// </summary>
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 });
}
};
}

/// <summary>A collapsible section whose open state is remembered per user.</summary>
static void Section(string id, GUIContent title, System.Action body)
{
Expand Down
141 changes: 141 additions & 0 deletions Unity-Package/Assets/root/Editor/SmartParameterMapping.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,141 @@
using System;
using System.Collections.Generic;
using System.Linq;

namespace Severnbli.LocalizationCodegen.Editor
{
/// <summary>
/// Applies <see cref="SmartParameterTypes"/> metadata to the parameters of a smart string entry
/// (<see cref="SmartParamTypeMode.Mapping"/>).
/// </summary>
internal static class SmartParameterMapping
{
/// <summary>C# type name emitted for a mapped type.</summary>
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";
}
}

/// <summary>
/// Whether the plural formatter can format a value of this type. It takes numbers and collections; strings,
/// booleans, dates and characters (whose <c>ToDecimal</c> throws) make it fail at runtime.
/// </summary>
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;
}
}

/// <summary>Whether the list formatter can format a value of this type.</summary>
public static bool AcceptsList(SmartParameterType type) => type == SmartParameterType.List;

/// <summary>
/// Sets the type of every parameter named in <paramref name="hints"/> and reports duplicate hints, hints
/// without a parameter, and types the plural or list formatter cannot format.
/// </summary>
public static void Apply(
EntryModel entry,
IList<SmartParameterTypes.Parameter> hints,
List<string> warnings,
string collectionName,
string key)
{
if (hints == null || hints.Count == 0)
return;

var prefix = $"Collection '{collectionName}', key '{key}': ";
var seen = new HashSet<string>(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.");
}
}
}

/// <summary>Accepts <c>count</c>, <c>0</c> and <c>{0}</c>.</summary>
static string NormalizeName(string name)
{
return (name ?? "").Trim().TrimStart('{').TrimEnd('}').Trim();
}

static List<string> 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);
}
}
11 changes: 11 additions & 0 deletions Unity-Package/Assets/root/Editor/SmartParameterMapping.cs.meta

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

9 changes: 9 additions & 0 deletions Unity-Package/Assets/root/Editor/TableReader.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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<SmartParameterTypes>()?.Parameters,
warnings,
collectionName,
sharedEntry.Key);
}
ValidateLocales(modelEntry, referenceUsages, referenceLocale, warnings, collectionName, sharedEntry.Key);
}

Expand Down
Loading
Loading