diff --git a/CHANGELOG.md b/CHANGELOG.md index 7479219..df964aa 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,19 @@ # Changelog +## [1.2.2] - 2026-10-26 + +### Changed +- Generated files import namespaces with ordinary `using` directives at the top of the file and refer to types by + their short names (`LocalizedTables.GetString(...)`, `LocalizedString`, `Sprite`, `Dictionary`) + instead of `global::`-qualified names. A type stays `global::`-qualified only when its short name could bind to + another type (two asset types with the same name, a nested class from a key separator, or a type with that name + in the generated namespace or its parents). +- Table classes no longer take the name of a type the generated code refers to (`Dictionary`, `UniTask`, an asset + type such as `Sprite`, …); such a class gets a `Table` suffix. + +### Removed +- The **Use Runtime Alias** setting and the `using __LT = ...;` alias, which the regular `using` directives replace. + ## [1.2.1] - 2026-10-24 ### Added diff --git a/Installer/Assets/Editor/Localization Codegen Installer/Installer.cs b/Installer/Assets/Editor/Localization Codegen Installer/Installer.cs index d763a12..62647bd 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.1"; + public const string Version = "1.2.2"; static Installer() { diff --git a/README.md b/README.md index 583083b..569607c 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.1" + "com.severnbli.localization-codegen": "1.2.2" } } ``` @@ -195,7 +195,7 @@ Given a string table collection named `Ui` containing the key `HelloWorld`, the ```csharp // // Table collection: Ui -using __LT = global::Severnbli.LocalizationCodegen.LocalizedTables; +using Severnbli.LocalizationCodegen; namespace Localization { @@ -203,12 +203,12 @@ namespace Localization { public const string TableName = "Ui"; - public static string HelloWorld => __LT.GetString(TableName, "HelloWorld"); + public static string HelloWorld => LocalizedTables.GetString(TableName, "HelloWorld"); } } ``` -The `__LT` alias is declared once per file. All other types (`LocalizedString`, asset types, `Dictionary<,>`) stay fully `global::`-qualified, so your own types can never shadow them. +Each file imports the namespaces it needs with ordinary `using` directives at the top and refers to every type (`LocalizedTables`, `LocalizedString`, asset types, `Dictionary<,>`) by its short name. When a short name could bind to another type – two asset types with the same name, a nested class created by a key separator, or a type with that name in your namespace – only that type stays `global::`-qualified. Use it anywhere from your game code: @@ -233,7 +233,7 @@ Generated identifiers always stay valid C#: - C# keywords get an `@` prefix. - Collisions get a numeric suffix, assigned by entry id so older keys keep their names. - Class names collide case-insensitively (`Ui` and `UI` get separate files on Windows/macOS). -- Reserved names (`System`, `UnityEngine`, `Unity`, the first namespace segment, …) get a `Table` suffix. +- Reserved names (`System`, `UnityEngine`, `Unity`, the first namespace segment, …) and the names of types the generated code refers to (`LocalizedTables`, `Dictionary`, `Sprite`, …) get a `Table` suffix. - Windows device names (`CON`, `NUL`, `COM1`, …) get a trailing `_`. With **Naming Convention = PascalCase** and optional **Key Separators**, `player name` becomes `PlayerName` and `Menu/Start` becomes the nested class `Menu.Start`. These options are off by default, so upgraded projects keep their existing API. @@ -245,8 +245,8 @@ Enable **Smart Strings = Methods** to turn entries that need arguments into meth ```csharp // "{0}, you have {count:plural:one item|{} items}" public static string Greeting(object arg0, int count) - => __LT.GetStringMixed(TableName, "Greeting", new object[] { arg0 }, - new global::System.Collections.Generic.Dictionary { ["count"] = count }); + => LocalizedTables.GetStringMixed(TableName, "Greeting", new object[] { arg0 }, + new Dictionary { ["count"] = count }); ``` - Positional placeholders (`{0}`) become `arg0`, `arg1`, … (gaps are filled). @@ -269,8 +269,8 @@ Enable **Generate Reference Members** to also get a nested `Ref` class that retu ```csharp public static class Ref { - public static global::UnityEngine.Localization.LocalizedString HelloWorld - => new global::UnityEngine.Localization.LocalizedString(TableName, "HelloWorld"); + public static LocalizedString HelloWorld + => new LocalizedString(TableName, "HelloWorld"); } ``` @@ -292,10 +292,10 @@ Asset entries use `LocalizedSprite`, `LocalizedAudioClip`, `LocalizedAsset` a Install [UniTask](https://github.com/Cysharp/UniTask) (`com.cysharp.unitask` 2.x) and enable **UniTask Members** to emit an awaitable variant next to every member: ```csharp -public static string HelloWorld => __LT.GetString(TableName, "HelloWorld"); +public static string HelloWorld => LocalizedTables.GetString(TableName, "HelloWorld"); -public static global::Cysharp.Threading.Tasks.UniTask HelloWorldAsync(global::System.Threading.CancellationToken cancellationToken = default) - => global::Severnbli.LocalizationCodegen.LocalizedTablesUniTask.GetStringAsync(TableName, "HelloWorld", cancellationToken); +public static UniTask HelloWorldAsync(CancellationToken cancellationToken = default) + => LocalizedTablesUniTask.GetStringAsync(TableName, "HelloWorld", cancellationToken); ``` ```csharp @@ -323,7 +323,6 @@ Open **Project Settings > Localization Codegen**, or **Window > Localization Cod | String Tables | on | Generate classes for string table collections. Disabling deletes the matching files on the next run. | | Asset Tables | on | Generate classes for asset table collections. Disabling deletes the matching files on the next run. | | Regenerate On Changes | on | Debounced automatic regeneration after table edits and external (VCS) changes. | -| Use Runtime Alias | on | Emit one `using __LT = ...;` instead of repeating the runtime type on every member. | | 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`. | diff --git a/Unity-Package/Assets/root/CHANGELOG.md b/Unity-Package/Assets/root/CHANGELOG.md index 7479219..df964aa 100644 --- a/Unity-Package/Assets/root/CHANGELOG.md +++ b/Unity-Package/Assets/root/CHANGELOG.md @@ -1,5 +1,19 @@ # Changelog +## [1.2.2] - 2026-10-26 + +### Changed +- Generated files import namespaces with ordinary `using` directives at the top of the file and refer to types by + their short names (`LocalizedTables.GetString(...)`, `LocalizedString`, `Sprite`, `Dictionary`) + instead of `global::`-qualified names. A type stays `global::`-qualified only when its short name could bind to + another type (two asset types with the same name, a nested class from a key separator, or a type with that name + in the generated namespace or its parents). +- Table classes no longer take the name of a type the generated code refers to (`Dictionary`, `UniTask`, an asset + type such as `Sprite`, …); such a class gets a `Table` suffix. + +### Removed +- The **Use Runtime Alias** setting and the `using __LT = ...;` alias, which the regular `using` directives replace. + ## [1.2.1] - 2026-10-24 ### Added diff --git a/Unity-Package/Assets/root/Editor/CodeEmitter.cs b/Unity-Package/Assets/root/Editor/CodeEmitter.cs index 913109c..0bbb365 100644 --- a/Unity-Package/Assets/root/Editor/CodeEmitter.cs +++ b/Unity-Package/Assets/root/Editor/CodeEmitter.cs @@ -11,13 +11,26 @@ namespace Severnbli.LocalizationCodegen.Editor /// internal static class CodeEmitter { - const string AssetObject = "global::UnityEngine.Object"; - const string LocalizedStringType = "global::UnityEngine.Localization.LocalizedString"; - const string LocalizedAssetType = "global::UnityEngine.Localization.LocalizedAsset"; - const string UniTaskType = "global::Cysharp.Threading.Tasks.UniTask"; - const string CancellationTokenType = "global::System.Threading.CancellationToken"; + const string AssetObject = "UnityEngine.Object"; + const string LocalizedStringType = "UnityEngine.Localization.LocalizedString"; + const string LocalizedAssetType = "UnityEngine.Localization.LocalizedAsset"; + const string UniTaskType = "Cysharp.Threading.Tasks.UniTask"; + const string CancellationTokenType = "System.Threading.CancellationToken"; + const string DictionaryType = "System.Collections.Generic.Dictionary"; const string CancellationTokenName = "cancellationToken"; + /// + /// Simple names of every type the emitter itself can reference. Generated classes in the same namespace would + /// hide them, so table classes never take these names. + /// + static readonly string[] s_ReferencedTypeNames = + { + "LocalizedTables", "LocalizedTablesUniTask", "Object", "LocalizedString", "LocalizedAsset", + "LocalizedAudioClip", "LocalizedGameObject", "LocalizedMesh", "LocalizedMaterial", "LocalizedObject", + "LocalizedSprite", "LocalizedTexture", "LocalizedFont", "LocalizedTmpFont", "LocalizedTextCoreFontAsset", + "UniTask", "CancellationToken", "Dictionary", "IEnumerable" + }; + /// Assigns deterministic, collision-free class names to every model. public static void AssignClassNames(IList models, EmitOptions options) { @@ -26,11 +39,8 @@ public static void AssignClassNames(IList models, EmitOptions option if (!model.IsAsset) stringNames.Add(model.Name ?? ""); - var used = new HashSet(StringComparer.OrdinalIgnoreCase) { "LocalizedTables" }; - if (options.UseRuntimeAlias) - used.Add(options.RuntimeAlias ?? EmitOptions.DefaultRuntimeAlias); - - var reserved = ReservedClassNames(options); + var used = new HashSet(StringComparer.OrdinalIgnoreCase) { "LocalizedTables", "LocalizedTablesUniTask" }; + var reserved = ReservedClassNames(models, options); var ordered = models .OrderBy(m => m.Name ?? "", StringComparer.Ordinal) .ThenBy(m => m.IsAsset ? 1 : 0) @@ -55,13 +65,27 @@ public static void AssignClassNames(IList models, EmitOptions option } } - static HashSet ReservedClassNames(EmitOptions options) + static HashSet ReservedClassNames(IList models, EmitOptions options) { var set = new HashSet(StringComparer.Ordinal) { - "System", "UnityEngine", "UnityEditor", "Unity", "Microsoft", "Mono", "Severnbli" + "System", "UnityEngine", "UnityEditor", "Unity", "Microsoft", "Mono", "Severnbli", "Cysharp", "TMPro" }; + // Generated files refer to types by their simple names, which a table class must not hide. + set.UnionWith(s_ReferencedTypeNames); + foreach (var model in models) + { + foreach (var entry in model.Entries) + { + if (!string.IsNullOrEmpty(entry.AssetTypeName)) + set.Add(TypeNames.FirstSegment(TypeNames.SimpleName(entry.AssetTypeName, entry.AssetTypeNamespace))); + foreach (var param in entry.Params) + if (param.TypeName != null && param.TypeName.IndexOf('.') >= 0) + set.Add(TypeNames.FirstSegment(TypeNames.SimpleName(param.TypeName, null))); + } + } + var first = NamespaceUtil.FirstSegment(options.Namespace); if (!string.IsNullOrEmpty(first)) set.Add(first.TrimStart('@')); @@ -78,31 +102,38 @@ public static string Emit(TableModel model, EmitOptions options) ? CodegenText.ToIdentifier(model.Name) : model.ClassName; + var root = BuildScopeTree(model, options); + root.ClassName = className; + AssignMemberNames(root, options); + + var hasNamespace = !string.IsNullOrEmpty(options.Namespace); + var rootLevel = hasNamespace ? 1 : 0; + + // The first pass only records which types the file refers to, so the second can pick their names. + var types = new TypeNames(); + EmitScope(new StringBuilder(), root, model, options, types, rootLevel, true); + var declared = new HashSet(StringComparer.Ordinal); + CollectClassNames(root, declared); + if (options.Refs) + declared.Add("Ref"); + var usings = types.Resolve(options, declared); + var sb = new StringBuilder(); sb.Append(CodegenText.Marker).Append('\n'); sb.Append("// Table collection: ").Append(CodegenText.SanitizeComment(model.Name)).Append('\n'); - if (options.UseRuntimeAlias) - { - sb.Append("using ").Append(options.RuntimeAlias).Append(" = ") - .Append(EmitOptions.RuntimeTypeName).Append(";\n"); - } + foreach (var ns in usings) + sb.Append("using ").Append(ns).Append(";\n"); - var hasNamespace = !string.IsNullOrEmpty(options.Namespace); if (hasNamespace) { - if (options.UseRuntimeAlias) + if (usings.Count > 0) sb.Append('\n'); sb.Append("namespace ").Append(NamespaceUtil.Declaration(options.Namespace)).Append('\n'); sb.Append("{\n"); } - var root = BuildScopeTree(model, options); - root.ClassName = className; - AssignMemberNames(root, options); - - var rootLevel = hasNamespace ? 1 : 0; - EmitScope(sb, root, model, options, rootLevel, true); + EmitScope(sb, root, model, options, types, rootLevel, true); if (hasNamespace) sb.Append("}\n"); @@ -110,6 +141,13 @@ public static string Emit(TableModel model, EmitOptions options) return sb.ToString(); } + static void CollectClassNames(Scope scope, HashSet names) + { + names.Add(scope.ClassName.TrimStart('@')); + foreach (var child in scope.Children) + CollectClassNames(child, names); + } + sealed class Scope { public string RawSegment; @@ -177,13 +215,14 @@ static void AssignMemberNames(Scope scope, EmitOptions options) child.ClassName = CodegenText.Unique(baseName, childClassNames); } - // Members must not hide TableName, Ref, the runtime alias, object members, nested classes or the + // Members must not hide TableName, Ref, the runtime classes, object members, nested classes or the // enclosing type name. scope.MemberUsed.Clear(); scope.MemberUsed.Add("TableName"); scope.MemberUsed.Add("Ref"); - if (options.UseRuntimeAlias) - scope.MemberUsed.Add(options.RuntimeAlias ?? EmitOptions.DefaultRuntimeAlias); + scope.MemberUsed.Add("LocalizedTables"); + if (options.UniTask) + scope.MemberUsed.Add("LocalizedTablesUniTask"); foreach (var name in CodegenText.ObjectMemberNames) scope.MemberUsed.Add(name); foreach (var name in childClassNames) @@ -238,7 +277,7 @@ static string BaseMemberName(string key, EmitOptions options, bool strict) return CodegenText.ToIdentifier(key, strict); } - static void EmitScope(StringBuilder sb, Scope scope, TableModel model, EmitOptions options, int level, bool isRoot) + static void EmitScope(StringBuilder sb, Scope scope, TableModel model, EmitOptions options, TypeNames types, int level, bool isRoot) { sb.Append(Indent(level)).Append("public static class ").Append(scope.ClassName).Append('\n'); sb.Append(Indent(level)).Append("{\n"); @@ -257,37 +296,37 @@ static void EmitScope(StringBuilder sb, Scope scope, TableModel model, EmitOptio foreach (var entry in orderedEntries) { sb.Append('\n'); - EmitEntry(sb, entry, scope.MemberNames[entry], options, level + 1); + EmitEntry(sb, entry, scope.MemberNames[entry], options, types, level + 1); string asyncName; if (scope.AsyncMemberNames.TryGetValue(entry, out asyncName)) { sb.Append('\n'); - EmitAsyncEntry(sb, entry, asyncName, options, level + 1); + EmitAsyncEntry(sb, entry, asyncName, options, types, level + 1); } } if (isRoot && options.Refs) { sb.Append('\n'); - EmitRefClass(sb, model, options, level + 1); + EmitRefClass(sb, model, options, types, level + 1); } foreach (var child in scope.Children.OrderBy(c => c.ClassName, StringComparer.Ordinal)) { sb.Append('\n'); - EmitScope(sb, child, model, options, level + 1, false); + EmitScope(sb, child, model, options, types, level + 1, false); } sb.Append(Indent(level)).Append("}\n"); } - static void EmitEntry(StringBuilder sb, EntryModel entry, string name, EmitOptions options, int level) + static void EmitEntry(StringBuilder sb, EntryModel entry, string name, EmitOptions options, TypeNames types, int level) { if (options.XmlDocs && !string.IsNullOrEmpty(entry.Preview)) EmitSummary(sb, entry.Preview, level); - var runtime = RuntimeType(options); + var runtime = types.Name(EmitOptions.RuntimeTypeName); if (!IsAssetEntry(entry)) { var positional = entry.Params.Where(p => p.IsPositional).OrderBy(p => p.Index).ToList(); @@ -297,9 +336,9 @@ static void EmitEntry(StringBuilder sb, EntryModel entry, string name, EmitOptio { EmitParameterDocs(sb, positional, named, level); sb.Append(Indent(level)).Append("public static string ").Append(name) - .Append('(').Append(ParameterList(positional, named)).Append(")\n"); + .Append('(').Append(ParameterList(positional, named, types)).Append(")\n"); sb.Append(Indent(level)).Append(" => ").Append(runtime).Append('.') - .Append(BuildStringCall(entry.Key, positional, named)).Append(";\n"); + .Append(BuildStringCall(entry.Key, positional, named, types)).Append(";\n"); } else { @@ -310,7 +349,7 @@ static void EmitEntry(StringBuilder sb, EntryModel entry, string name, EmitOptio } else { - var type = string.IsNullOrEmpty(entry.AssetTypeName) ? AssetObject : entry.AssetTypeName; + var type = AssetType(entry, types); sb.Append(Indent(level)).Append("public static ").Append(type).Append(' ').Append(name) .Append(" => ").Append(runtime).Append(".GetAsset<").Append(type) .Append(">(TableName, ").Append(CodegenText.Literal(entry.Key)).Append(");\n"); @@ -319,18 +358,27 @@ static void EmitEntry(StringBuilder sb, EntryModel entry, string name, EmitOptio static bool IsAssetEntry(EntryModel entry) => entry.AssetTypeName != null; + static string AssetType(EntryModel entry, TypeNames types) + { + return string.IsNullOrEmpty(entry.AssetTypeName) + ? types.Name(AssetObject) + : types.Name(entry.AssetTypeName, entry.AssetTypeNamespace); + } + /// Emits the UniTask variant of an entry, mirroring the parameters of its synchronous member. - static void EmitAsyncEntry(StringBuilder sb, EntryModel entry, string name, EmitOptions options, int level) + static void EmitAsyncEntry(StringBuilder sb, EntryModel entry, string name, EmitOptions options, TypeNames types, int level) { if (options.XmlDocs && !string.IsNullOrEmpty(entry.Preview)) EmitSummary(sb, entry.Preview, level); - var runtime = EmitOptions.UniTaskRuntimeTypeName; + var runtime = types.Name(EmitOptions.UniTaskRuntimeTypeName); + var uniTask = types.Name(UniTaskType); + var cancellationToken = types.Name(CancellationTokenType); if (IsAssetEntry(entry)) { - var type = string.IsNullOrEmpty(entry.AssetTypeName) ? AssetObject : entry.AssetTypeName; - sb.Append(Indent(level)).Append("public static ").Append(UniTaskType).Append('<').Append(type).Append("> ") - .Append(name).Append('(').Append(CancellationTokenType).Append(' ').Append(CancellationTokenName) + var type = AssetType(entry, types); + sb.Append(Indent(level)).Append("public static ").Append(uniTask).Append('<').Append(type).Append("> ") + .Append(name).Append('(').Append(cancellationToken).Append(' ').Append(CancellationTokenName) .Append(" = default)\n"); sb.Append(Indent(level)).Append(" => ").Append(runtime).Append(".GetAssetAsync<").Append(type) .Append(">(TableName, ").Append(CodegenText.Literal(entry.Key)).Append(", ") @@ -357,24 +405,24 @@ static void EmitAsyncEntry(StringBuilder sb, EntryModel entry, string name, Emit .Append("\">Stops waiting for the table to load.\n"); } - var parameters = ParameterList(positional, named); - sb.Append(Indent(level)).Append("public static ").Append(UniTaskType).Append(" ").Append(name).Append('(') + var parameters = ParameterList(positional, named, types); + sb.Append(Indent(level)).Append("public static ").Append(uniTask).Append(" ").Append(name).Append('(') .Append(parameters).Append(parameters.Length > 0 ? ", " : "") - .Append(CancellationTokenType).Append(' ').Append(tokenName).Append(" = default)\n"); + .Append(cancellationToken).Append(' ').Append(tokenName).Append(" = default)\n"); sb.Append(Indent(level)).Append(" => ").Append(runtime).Append(".GetStringAsync(TableName, ") .Append(CodegenText.Literal(entry.Key)).Append(", "); if (withParams) - sb.Append(PositionalArray(positional)).Append(", ").Append(NamedDictionary(named)).Append(", "); + sb.Append(PositionalArray(positional)).Append(", ").Append(NamedDictionary(named, types)).Append(", "); sb.Append(tokenName).Append(");\n"); } - static void EmitRefClass(StringBuilder sb, TableModel model, EmitOptions options, int level) + static void EmitRefClass(StringBuilder sb, TableModel model, EmitOptions options, TypeNames types, int level) { var strict = !string.IsNullOrEmpty(options.KeySeparators); sb.Append(Indent(level)).Append("public static class Ref\n"); sb.Append(Indent(level)).Append("{\n"); - var used = new HashSet(StringComparer.Ordinal) { "TableName", "Ref" }; + var used = new HashSet(StringComparer.Ordinal) { "TableName", "Ref", "LocalizedTables" }; foreach (var objectMember in CodegenText.ObjectMemberNames) used.Add(objectMember); @@ -400,17 +448,18 @@ static void EmitRefClass(StringBuilder sb, TableModel model, EmitOptions options if (entry.Params.Count > 0 && options.SmartStrings == SmartStringMode.MethodsAndRefs) { EmitParameterDocs(sb, positional, named, level + 1); - sb.Append(Indent(level + 1)).Append("public static ").Append(LocalizedStringType).Append(' ') - .Append(name).Append('(').Append(ParameterList(positional, named)).Append(")\n"); - sb.Append(Indent(level + 1)).Append(" => ").Append(RuntimeType(options)) + sb.Append(Indent(level + 1)).Append("public static ").Append(types.Name(LocalizedStringType)).Append(' ') + .Append(name).Append('(').Append(ParameterList(positional, named, types)).Append(")\n"); + sb.Append(Indent(level + 1)).Append(" => ").Append(types.Name(EmitOptions.RuntimeTypeName)) .Append(".CreateReference(TableName, ").Append(CodegenText.Literal(entry.Key)) .Append(", ").Append(PositionalArray(positional)).Append(", ") - .Append(NamedDictionary(named)).Append(");\n"); + .Append(NamedDictionary(named, types)).Append(");\n"); } else if (entry.Params.Count == 0) { - sb.Append(Indent(level + 1)).Append("public static ").Append(LocalizedStringType).Append(' ') - .Append(name).Append(" => new ").Append(LocalizedStringType) + var localizedString = types.Name(LocalizedStringType); + sb.Append(Indent(level + 1)).Append("public static ").Append(localizedString).Append(' ') + .Append(name).Append(" => new ").Append(localizedString) .Append("(TableName, ").Append(CodegenText.Literal(entry.Key)).Append(");\n"); } else @@ -422,9 +471,9 @@ static void EmitRefClass(StringBuilder sb, TableModel model, EmitOptions options else { // Unlike LocalizedString, LocalizedAsset types only have a parameterless constructor. - var type = string.IsNullOrEmpty(entry.AssetTypeName) ? AssetObject : entry.AssetTypeName; - sb.Append(Indent(level + 1)).Append("public static ").Append(GetLocalizedAssetType(type)).Append(' ') - .Append(name).Append(" => new ").Append(GetLocalizedAssetType(type)) + var type = GetLocalizedAssetType(entry, types); + sb.Append(Indent(level + 1)).Append("public static ").Append(type).Append(' ') + .Append(name).Append(" => new ").Append(type) .Append(" { TableReference = TableName, TableEntryReference = ") .Append(CodegenText.Literal(entry.Key)).Append(" };\n"); } @@ -433,42 +482,44 @@ static void EmitRefClass(StringBuilder sb, TableModel model, EmitOptions options sb.Append(Indent(level)).Append("}\n"); } - static string GetLocalizedAssetType(string assetType) + static string GetLocalizedAssetType(EntryModel entry, TypeNames types) { - switch (assetType) + string localized; + switch (string.IsNullOrEmpty(entry.AssetTypeName) ? AssetObject : entry.AssetTypeName) { - case "global::UnityEngine.AudioClip": return "global::UnityEngine.Localization.LocalizedAudioClip"; - case "global::UnityEngine.GameObject": return "global::UnityEngine.Localization.LocalizedGameObject"; - case "global::UnityEngine.Mesh": return "global::UnityEngine.Localization.LocalizedMesh"; - case "global::UnityEngine.Material": return "global::UnityEngine.Localization.LocalizedMaterial"; - case "global::UnityEngine.Object": return "global::UnityEngine.Localization.LocalizedObject"; - case "global::UnityEngine.Sprite": return "global::UnityEngine.Localization.LocalizedSprite"; - case "global::UnityEngine.Texture": return "global::UnityEngine.Localization.LocalizedTexture"; - case "global::UnityEngine.Font": return "global::UnityEngine.Localization.LocalizedFont"; - case "global::TMPro.TMP_FontAsset": return "global::UnityEngine.Localization.LocalizedTmpFont"; - case "global::UnityEngine.TextCore.Text.FontAsset": return "global::UnityEngine.Localization.LocalizedTextCoreFontAsset"; - default: return LocalizedAssetType + "<" + assetType + ">"; + case "UnityEngine.AudioClip": localized = "UnityEngine.Localization.LocalizedAudioClip"; break; + case "UnityEngine.GameObject": localized = "UnityEngine.Localization.LocalizedGameObject"; break; + case "UnityEngine.Mesh": localized = "UnityEngine.Localization.LocalizedMesh"; break; + case "UnityEngine.Material": localized = "UnityEngine.Localization.LocalizedMaterial"; break; + case "UnityEngine.Object": localized = "UnityEngine.Localization.LocalizedObject"; break; + case "UnityEngine.Sprite": localized = "UnityEngine.Localization.LocalizedSprite"; break; + case "UnityEngine.Texture": localized = "UnityEngine.Localization.LocalizedTexture"; break; + case "UnityEngine.Font": localized = "UnityEngine.Localization.LocalizedFont"; break; + case "TMPro.TMP_FontAsset": localized = "UnityEngine.Localization.LocalizedTmpFont"; break; + case "UnityEngine.TextCore.Text.FontAsset": localized = "UnityEngine.Localization.LocalizedTextCoreFontAsset"; break; + default: return types.Name(LocalizedAssetType) + "<" + AssetType(entry, types) + ">"; } + return types.Name(localized); } - static string ParameterList(List positional, List named) + static string ParameterList(List positional, List named, TypeNames types) { var parts = new List(); foreach (var p in positional) - parts.Add(p.TypeName + " " + p.ClrName); + parts.Add(types.Name(p.TypeName) + " " + p.ClrName); foreach (var p in named) - parts.Add(p.TypeName + " " + p.ClrName); + parts.Add(types.Name(p.TypeName) + " " + p.ClrName); return string.Join(", ", parts.ToArray()); } - static string BuildStringCall(string key, List positional, List named) + static string BuildStringCall(string key, List positional, List named, TypeNames types) { var keyLiteral = CodegenText.Literal(key); if (positional.Count == 0 && named.Count == 0) return "GetString(TableName, " + keyLiteral + ")"; if (positional.Count == 0) - return "GetString(TableName, " + keyLiteral + ", " + NamedDictionary(named) + ")"; + return "GetString(TableName, " + keyLiteral + ", " + NamedDictionary(named, types) + ")"; if (named.Count == 0) { @@ -477,7 +528,7 @@ static string BuildStringCall(string key, List positional, List positional) @@ -488,13 +539,13 @@ static string PositionalArray(List positional) return "new object[] { " + args + " }"; } - static string NamedDictionary(List named) + static string NamedDictionary(List named, TypeNames types) { if (named.Count == 0) return "null"; var sb = new StringBuilder(); - sb.Append("new global::System.Collections.Generic.Dictionary { "); + sb.Append("new ").Append(types.Name(DictionaryType)).Append(" { "); for (var i = 0; i < named.Count; i++) { if (i > 0) @@ -524,11 +575,109 @@ static void EmitSummary(StringBuilder sb, string preview, int level) sb.Append(Indent(level)).Append("/// ").Append(text).Append("\n"); } - static string RuntimeType(EmitOptions options) + static string Indent(int level) => new string(' ', level * 4); + + /// + /// Decides how one file writes the types it refers to. A type is written by its simple name and its namespace + /// is imported with a using directive, unless that name could bind to another type; then it stays + /// global:: qualified. + /// + internal sealed class TypeNames { - return options.UseRuntimeAlias ? options.RuntimeAlias : EmitOptions.RuntimeTypeName; - } + // Full name -> namespace of every type the file refers to. + readonly Dictionary m_Namespaces = new Dictionary(StringComparer.Ordinal); - static string Indent(int level) => new string(' ', level * 4); + // Full name -> written name; null while recording. + Dictionary m_Written; + + /// + /// Returns the name to write for a type. is the type's namespace; when null it is + /// everything before the last dot. Names without a dot and namespace (keywords such as object) pass through. + /// + public string Name(string fullName, string ns = null) + { + if (ns == null) + { + var dot = fullName.LastIndexOf('.'); + if (dot < 0) + return fullName; + ns = fullName.Substring(0, dot); + } + + if (m_Written == null) + { + m_Namespaces[fullName] = ns; + return fullName; + } + return m_Written[fullName]; + } + + /// + /// Picks the written name of every recorded type and returns the namespaces to import, sorted with System + /// namespaces first. holds the type names the file itself declares. + /// + public List Resolve(EmitOptions options, HashSet declared) + { + // Namespaces whose types a simple name can bind to: the generated namespace, its parents and the imports. + var enclosing = new List { "" }; + if (!string.IsNullOrEmpty(options.Namespace)) + { + var segments = options.Namespace.Split('.').Select(s => s.TrimStart('@')).ToArray(); + for (var i = 1; i <= segments.Length; i++) + enclosing.Add(string.Join(".", segments, 0, i)); + // A simple name that matches a segment of the generated namespace binds to that namespace. + declared = new HashSet(declared, StringComparer.Ordinal); + declared.UnionWith(segments); + } + + var lookup = new HashSet(enclosing, StringComparer.Ordinal); + lookup.UnionWith(m_Namespaces.Values); + + m_Written = new Dictionary(StringComparer.Ordinal); + var usings = new HashSet(StringComparer.Ordinal); + foreach (var pair in m_Namespaces) + { + var ns = pair.Value; + var simple = SimpleName(pair.Key, ns); + var first = FirstSegment(simple); + + var conflict = declared.Contains(first) || + m_Namespaces.Any(o => o.Value != ns && FirstSegment(SimpleName(o.Key, o.Value)) == first) || + (options.TypeExists != null && lookup.Any(n => n != ns && options.TypeExists(n, first))); + + if (conflict) + { + m_Written[pair.Key] = "global::" + pair.Key; + continue; + } + + m_Written[pair.Key] = simple; + if (!enclosing.Contains(ns)) + usings.Add(ns); + } + + return usings + .OrderBy(n => n == "System" || n.StartsWith("System.", StringComparison.Ordinal) ? 0 : 1) + .ThenBy(n => n, StringComparer.Ordinal) + .ToList(); + } + + /// The name of a type relative to its namespace, e.g. Outer.Inner for a nested type. + public static string SimpleName(string fullName, string ns) + { + if (ns == null) + { + var dot = fullName.LastIndexOf('.'); + return dot < 0 ? fullName : fullName.Substring(dot + 1); + } + return ns.Length == 0 ? fullName : fullName.Substring(ns.Length + 1); + } + + public static string FirstSegment(string simpleName) + { + var dot = simpleName.IndexOf('.'); + return dot < 0 ? simpleName : simpleName.Substring(0, dot); + } + } } } diff --git a/Unity-Package/Assets/root/Editor/CodeGenerator.cs b/Unity-Package/Assets/root/Editor/CodeGenerator.cs index d8080af..61b65ad 100644 --- a/Unity-Package/Assets/root/Editor/CodeGenerator.cs +++ b/Unity-Package/Assets/root/Editor/CodeGenerator.cs @@ -282,7 +282,6 @@ static EmitOptions BuildEmitOptions(CodegenSettings settings) return new EmitOptions { Namespace = NamespaceUtil.Normalize(settings.Namespace), - UseRuntimeAlias = settings.UseRuntimeAlias, Refs = settings.GenerateReferences || smart == SmartStringMode.MethodsAndRefs, XmlDocs = settings.GenerateXmlDocs, SmartStrings = smart, @@ -291,10 +290,53 @@ static EmitOptions BuildEmitOptions(CodegenSettings settings) SmartParamTypes = settings.SmartParamTypes, GenerateAsmdef = settings.GenerateAsmdef, // Generated code must compile, so the option only takes effect when the add-on is compiled. - UniTask = settings.GenerateUniTask && UniTaskSupport.IsAvailable + UniTask = settings.GenerateUniTask && UniTaskSupport.IsAvailable, + TypeExists = LoadedTypeExists }; } + static HashSet s_LoadedTypes; + + /// + /// True when a loaded assembly has a public top-level type with this simple name (any generic arity) in the + /// namespace. Domain reloads reset the cache, so it always reflects the compiled project. + /// + static bool LoadedTypeExists(string ns, string name) + { + if (s_LoadedTypes == null) + { + var types = new HashSet(StringComparer.Ordinal); + foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies()) + { + if (assembly.IsDynamic) + continue; + + Type[] exported; + try + { + exported = assembly.GetExportedTypes(); + } + catch (Exception) + { + continue; + } + + foreach (var type in exported) + { + if (type.IsNested) + continue; + var simple = type.Name; + var tick = simple.IndexOf('`'); + if (tick >= 0) + simple = simple.Substring(0, tick); + types.Add((type.Namespace ?? "") + "|" + simple); + } + } + s_LoadedTypes = types; + } + return s_LoadedTypes.Contains(ns + "|" + name); + } + /// Warns when the output folder compiles into an asmdef that lacks the references the code needs. static void WarnAboutOwningAssembly(string folder, EmitOptions options, CodegenSettings settings, GenerateResult result) { diff --git a/Unity-Package/Assets/root/Editor/CodegenModel.cs b/Unity-Package/Assets/root/Editor/CodegenModel.cs index 2a2d710..4ff1c8e 100644 --- a/Unity-Package/Assets/root/Editor/CodegenModel.cs +++ b/Unity-Package/Assets/root/Editor/CodegenModel.cs @@ -40,7 +40,11 @@ internal sealed class EntryModel { public long Id; public string Key; + /// Full name of the asset type without global::, e.g. UnityEngine.Sprite. public string AssetTypeName; + + /// Namespace of ; when null, everything before its last dot. + public string AssetTypeNamespace; public string Preview; public readonly List Params = new List(); public readonly List Usages = new List(); @@ -72,15 +76,12 @@ internal sealed class SmartVariableUsage /// Options controlling the pure emitter. internal sealed class EmitOptions { - public const string DefaultRuntimeAlias = "__LT"; - public const string RuntimeTypeName = "global::Severnbli.LocalizationCodegen.LocalizedTables"; - public const string UniTaskRuntimeTypeName = "global::Severnbli.LocalizationCodegen.LocalizedTablesUniTask"; + public const string RuntimeTypeName = "Severnbli.LocalizationCodegen.LocalizedTables"; + public const string UniTaskRuntimeTypeName = "Severnbli.LocalizationCodegen.LocalizedTablesUniTask"; /// Normalized namespace, or for the global namespace. public string Namespace; - public bool UseRuntimeAlias = true; - public string RuntimeAlias = DefaultRuntimeAlias; public bool Refs; public bool XmlDocs; public SmartStringMode SmartStrings = SmartStringMode.Off; @@ -94,6 +95,12 @@ internal sealed class EmitOptions /// When true, every member also gets a UniTask-returning ...Async variant. public bool UniTask; + /// + /// Optional check whether a namespace (empty for the global namespace) contains a type with the given simple + /// name. Generated files keep a type global:: qualified when its simple name could bind to another type. + /// + public Func TypeExists; + /// Stable signature of every option that can change output. public string Signature() { @@ -101,8 +108,7 @@ public string Signature() return (UniTask ? "unitask|" : "") + string.Join("|", new[] { Namespace ?? "", - UseRuntimeAlias ? "alias" : "noalias", - RuntimeAlias ?? DefaultRuntimeAlias, + "usings", RuntimeTypeName, Refs ? "refs" : "norefs", XmlDocs ? "docs" : "nodocs", diff --git a/Unity-Package/Assets/root/Editor/CodegenSettings.cs b/Unity-Package/Assets/root/Editor/CodegenSettings.cs index 0a4b6e4..ab3bc71 100644 --- a/Unity-Package/Assets/root/Editor/CodegenSettings.cs +++ b/Unity-Package/Assets/root/Editor/CodegenSettings.cs @@ -28,7 +28,6 @@ public sealed class CodegenSettings : ScriptableSingleton [SerializeField] private string[] collectionHashes = new string[0]; // Options introduced in 1.1.0. Defaults are intentionally "old output" and are migrated explicitly. - [SerializeField] private bool useRuntimeAlias; [SerializeField] private bool generateReferences; [SerializeField] private bool generateXmlDocs; [SerializeField] private int smartStrings; @@ -54,7 +53,6 @@ public sealed class CodegenSettings : ScriptableSingleton public string LastModelHash { get => lastModelHash; set => lastModelHash = value; } public string[] CollectionHashes { get => collectionHashes ?? (collectionHashes = new string[0]); set => collectionHashes = value; } - public bool UseRuntimeAlias { get => useRuntimeAlias; set => useRuntimeAlias = value; } public bool GenerateReferences { get => generateReferences; set => generateReferences = value; } public bool GenerateXmlDocs { get => generateXmlDocs; set => generateXmlDocs = value; } public bool GenerateAsmdef { get => generateAsmdef; set => generateAsmdef = value; } @@ -87,10 +85,7 @@ public string KeySeparators public int SettingsVersion { get => settingsVersion; set => settingsVersion = value; } - /// - /// Upgrades settings created by older versions. Missing boolean fields deserialize as false, so the alias - /// option (which is safe to enable for existing projects) is turned on explicitly. - /// + /// Upgrades settings created by older versions. public void EnsureMigrated() { if (settingsVersion >= CurrentVersion) @@ -98,7 +93,6 @@ public void EnsureMigrated() if (settingsVersion < 2) { - useRuntimeAlias = true; if (generatedPaths == null) generatedPaths = new string[0]; if (collectionHashes == null) diff --git a/Unity-Package/Assets/root/Editor/SettingsGui.cs b/Unity-Package/Assets/root/Editor/SettingsGui.cs index 6e00da2..8d4e35d 100644 --- a/Unity-Package/Assets/root/Editor/SettingsGui.cs +++ b/Unity-Package/Assets/root/Editor/SettingsGui.cs @@ -48,8 +48,6 @@ internal static class Content "Keep preserves the 1.0 names. PascalCase turns 'player name' into 'PlayerName'."); public static readonly GUIContent KeySeparators = new GUIContent("Key Separators", "Optional characters that create nested classes, e.g. '/' makes 'Menu/Start' become Menu.Start."); - public static readonly GUIContent RuntimeAlias = new GUIContent("Use Runtime Alias", - "Reference the runtime helper through one file-level alias (__LT) instead of repeating the fully qualified name on every member."); public static readonly GUIContent GenerateAsmdef = new GUIContent("Generate .asmdef", "Write an assembly definition into the output folder, so the generated code gets its own assembly."); @@ -339,7 +337,6 @@ static void DrawNaming(CodegenSettings s) { s.Naming = (NamingConvention)EditorGUILayout.EnumPopup(Content.Naming, s.Naming); s.KeySeparators = EditorGUILayout.TextField(Content.KeySeparators, s.KeySeparators); - s.UseRuntimeAlias = EditorGUILayout.Toggle(Content.RuntimeAlias, s.UseRuntimeAlias); } static void DrawAdvanced(CodegenSettings s) diff --git a/Unity-Package/Assets/root/Editor/TableReader.cs b/Unity-Package/Assets/root/Editor/TableReader.cs index 761c227..d9d5c9d 100644 --- a/Unity-Package/Assets/root/Editor/TableReader.cs +++ b/Unity-Package/Assets/root/Editor/TableReader.cs @@ -140,7 +140,7 @@ TableModel ReadCollection(LocalizationTableCollection collection, bool isAsset, var type = ResolveAssetType(assetCollection, entry, ref assetTypeError); if (type == null) { - modelEntry.AssetTypeName = "global::UnityEngine.Object"; + modelEntry.AssetTypeName = "UnityEngine.Object"; fallbackEntries++; if (fallbackReason == null) fallbackReason = assetTypeError ?? "the entry has no asset type"; @@ -148,14 +148,15 @@ TableModel ReadCollection(LocalizationTableCollection collection, bool isAsset, else if (!m_Options.GenerateAsmdef && !IsAssemblyReachableFromAssemblyCSharp(type.Assembly.GetName().Name)) { - modelEntry.AssetTypeName = "global::UnityEngine.Object"; + modelEntry.AssetTypeName = "UnityEngine.Object"; fallbackEntries++; if (fallbackReason == null) fallbackReason = $"assembly '{type.Assembly.GetName().Name}' is not referenced by Assembly-CSharp"; } else { - modelEntry.AssetTypeName = "global::" + type.FullName.Replace('+', '.'); + modelEntry.AssetTypeName = type.FullName.Replace('+', '.'); + modelEntry.AssetTypeNamespace = type.Namespace ?? ""; model.AssetAssemblies.Add(type.Assembly.GetName().Name); } } @@ -569,7 +570,7 @@ string InferType(List usages) if (allPlural && formatters.Count > 0) return "int"; if (allList && formatters.Count > 0) - return "global::System.Collections.IEnumerable"; + return "System.Collections.IEnumerable"; return "object"; } diff --git a/Unity-Package/Assets/root/README.md b/Unity-Package/Assets/root/README.md index 583083b..569607c 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.1" + "com.severnbli.localization-codegen": "1.2.2" } } ``` @@ -195,7 +195,7 @@ Given a string table collection named `Ui` containing the key `HelloWorld`, the ```csharp // // Table collection: Ui -using __LT = global::Severnbli.LocalizationCodegen.LocalizedTables; +using Severnbli.LocalizationCodegen; namespace Localization { @@ -203,12 +203,12 @@ namespace Localization { public const string TableName = "Ui"; - public static string HelloWorld => __LT.GetString(TableName, "HelloWorld"); + public static string HelloWorld => LocalizedTables.GetString(TableName, "HelloWorld"); } } ``` -The `__LT` alias is declared once per file. All other types (`LocalizedString`, asset types, `Dictionary<,>`) stay fully `global::`-qualified, so your own types can never shadow them. +Each file imports the namespaces it needs with ordinary `using` directives at the top and refers to every type (`LocalizedTables`, `LocalizedString`, asset types, `Dictionary<,>`) by its short name. When a short name could bind to another type – two asset types with the same name, a nested class created by a key separator, or a type with that name in your namespace – only that type stays `global::`-qualified. Use it anywhere from your game code: @@ -233,7 +233,7 @@ Generated identifiers always stay valid C#: - C# keywords get an `@` prefix. - Collisions get a numeric suffix, assigned by entry id so older keys keep their names. - Class names collide case-insensitively (`Ui` and `UI` get separate files on Windows/macOS). -- Reserved names (`System`, `UnityEngine`, `Unity`, the first namespace segment, …) get a `Table` suffix. +- Reserved names (`System`, `UnityEngine`, `Unity`, the first namespace segment, …) and the names of types the generated code refers to (`LocalizedTables`, `Dictionary`, `Sprite`, …) get a `Table` suffix. - Windows device names (`CON`, `NUL`, `COM1`, …) get a trailing `_`. With **Naming Convention = PascalCase** and optional **Key Separators**, `player name` becomes `PlayerName` and `Menu/Start` becomes the nested class `Menu.Start`. These options are off by default, so upgraded projects keep their existing API. @@ -245,8 +245,8 @@ Enable **Smart Strings = Methods** to turn entries that need arguments into meth ```csharp // "{0}, you have {count:plural:one item|{} items}" public static string Greeting(object arg0, int count) - => __LT.GetStringMixed(TableName, "Greeting", new object[] { arg0 }, - new global::System.Collections.Generic.Dictionary { ["count"] = count }); + => LocalizedTables.GetStringMixed(TableName, "Greeting", new object[] { arg0 }, + new Dictionary { ["count"] = count }); ``` - Positional placeholders (`{0}`) become `arg0`, `arg1`, … (gaps are filled). @@ -269,8 +269,8 @@ Enable **Generate Reference Members** to also get a nested `Ref` class that retu ```csharp public static class Ref { - public static global::UnityEngine.Localization.LocalizedString HelloWorld - => new global::UnityEngine.Localization.LocalizedString(TableName, "HelloWorld"); + public static LocalizedString HelloWorld + => new LocalizedString(TableName, "HelloWorld"); } ``` @@ -292,10 +292,10 @@ Asset entries use `LocalizedSprite`, `LocalizedAudioClip`, `LocalizedAsset` a Install [UniTask](https://github.com/Cysharp/UniTask) (`com.cysharp.unitask` 2.x) and enable **UniTask Members** to emit an awaitable variant next to every member: ```csharp -public static string HelloWorld => __LT.GetString(TableName, "HelloWorld"); +public static string HelloWorld => LocalizedTables.GetString(TableName, "HelloWorld"); -public static global::Cysharp.Threading.Tasks.UniTask HelloWorldAsync(global::System.Threading.CancellationToken cancellationToken = default) - => global::Severnbli.LocalizationCodegen.LocalizedTablesUniTask.GetStringAsync(TableName, "HelloWorld", cancellationToken); +public static UniTask HelloWorldAsync(CancellationToken cancellationToken = default) + => LocalizedTablesUniTask.GetStringAsync(TableName, "HelloWorld", cancellationToken); ``` ```csharp @@ -323,7 +323,6 @@ Open **Project Settings > Localization Codegen**, or **Window > Localization Cod | String Tables | on | Generate classes for string table collections. Disabling deletes the matching files on the next run. | | Asset Tables | on | Generate classes for asset table collections. Disabling deletes the matching files on the next run. | | Regenerate On Changes | on | Debounced automatic regeneration after table edits and external (VCS) changes. | -| Use Runtime Alias | on | Emit one `using __LT = ...;` instead of repeating the runtime type on every member. | | 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`. | diff --git a/Unity-Package/Assets/root/Tests/Editor/EmitterTests.cs b/Unity-Package/Assets/root/Tests/Editor/EmitterTests.cs index 3315221..c3ef2c7 100644 --- a/Unity-Package/Assets/root/Tests/Editor/EmitterTests.cs +++ b/Unity-Package/Assets/root/Tests/Editor/EmitterTests.cs @@ -30,7 +30,7 @@ static TableModel Model(string name, bool isAsset, params (long Id, string Key)[ { Id = entry.Id, Key = entry.Key, - AssetTypeName = isAsset ? "global::UnityEngine.Object" : null + AssetTypeName = isAsset ? "UnityEngine.Object" : null }); } return model; @@ -41,14 +41,13 @@ static EmitOptions LegacyOptions() return new EmitOptions { Namespace = "Localization", - UseRuntimeAlias = false, SmartStrings = SmartStringMode.Off, Naming = NamingConvention.Keep }; } [Test] - public void DefaultOptions_ReproduceLegacyOutput() + public void DefaultOptions_EmitPlainUsings() { var model = Model("Ui", false, (2L, "Title"), (1L, "Greeting")); var options = LegacyOptions(); @@ -57,15 +56,17 @@ public void DefaultOptions_ReproduceLegacyOutput() var expected = "// \n" + "// Table collection: Ui\n" + + "using Severnbli.LocalizationCodegen;\n" + + "\n" + "namespace Localization\n" + "{\n" + " public static class Ui\n" + " {\n" + " public const string TableName = \"Ui\";\n" + "\n" + - " public static string Greeting => global::Severnbli.LocalizationCodegen.LocalizedTables.GetString(TableName, \"Greeting\");\n" + + " public static string Greeting => LocalizedTables.GetString(TableName, \"Greeting\");\n" + "\n" + - " public static string Title => global::Severnbli.LocalizationCodegen.LocalizedTables.GetString(TableName, \"Title\");\n" + + " public static string Title => LocalizedTables.GetString(TableName, \"Title\");\n" + " }\n" + "}\n"; @@ -73,22 +74,102 @@ public void DefaultOptions_ReproduceLegacyOutput() } [Test] - public void RuntimeAlias_IsDeclaredOnceAndUsedByEveryMember() + public void Usings_ImportEveryReferencedNamespaceOnce() { - var model = Model("Ui", false, (1L, "Greeting"), (2L, "Title")); + var model = new TableModel { Name = "Ui" }; + model.Entries.Add(new EntryModel { Id = 1, Key = "Title" }); + model.Entries.Add(new EntryModel { Id = 2, Key = "Logo", AssetTypeName = "UnityEngine.Sprite" }); + var named = new EntryModel { Id = 3, Key = "Greeting" }; + named.Params.Add(new SmartParam { SourceName = "count", ClrName = "count", TypeName = "int" }); + model.Entries.Add(named); + var options = new EmitOptions { Namespace = "Localization", - UseRuntimeAlias = true, - SmartStrings = SmartStringMode.Off + SmartStrings = SmartStringMode.Methods, + Refs = true, + UniTask = true + }; + CodeEmitter.AssignClassNames(new[] { model }, options); + var output = CodeEmitter.Emit(model, options); + + StringAssert.Contains( + "using System.Collections.Generic;\n" + + "using System.Threading;\n" + + "using Cysharp.Threading.Tasks;\n" + + "using Severnbli.LocalizationCodegen;\n" + + "using UnityEngine;\n" + + "using UnityEngine.Localization;\n" + + "\n" + + "namespace Localization\n", + output); + StringAssert.DoesNotContain("global::", output); + } + + [Test] + public void Usings_KeepAmbiguousTypesQualified() + { + var model = new TableModel { Name = "Items", IsAsset = true }; + model.Entries.Add(new EntryModel { Id = 1, Key = "Logo", AssetTypeName = "UnityEngine.Sprite" }); + model.Entries.Add(new EntryModel { Id = 2, Key = "Icon", AssetTypeName = "Game.Sprite" }); + model.Entries.Add(new EntryModel { Id = 3, Key = "Clip", AssetTypeName = "UnityEngine.AudioClip" }); + + var options = new EmitOptions { Namespace = "Localization" }; + CodeEmitter.AssignClassNames(new[] { model }, options); + var output = CodeEmitter.Emit(model, options); + + StringAssert.Contains("public static global::UnityEngine.Sprite Logo =>", output); + StringAssert.Contains("public static global::Game.Sprite Icon =>", output); + StringAssert.Contains("public static AudioClip Clip =>", output); + StringAssert.DoesNotContain("using Game;", output); + } + + [Test] + public void Usings_KeepTypesQualifiedWhenAnEnclosingNamespaceHasTheSameName() + { + var model = new TableModel { Name = "Items", IsAsset = true }; + model.Entries.Add(new EntryModel { Id = 1, Key = "Logo", AssetTypeName = "UnityEngine.Sprite" }); + model.Entries.Add(new EntryModel { Id = 2, Key = "Clip", AssetTypeName = "UnityEngine.AudioClip" }); + + var options = new EmitOptions + { + Namespace = "Game.Localization", + TypeExists = (ns, name) => ns == "Game" && name == "Sprite" }; CodeEmitter.AssignClassNames(new[] { model }, options); + var output = CodeEmitter.Emit(model, options); + + StringAssert.Contains("public static global::UnityEngine.Sprite Logo =>", output); + StringAssert.Contains("public static AudioClip Clip =>", output); + } + + [Test] + public void Usings_KeepTypesQualifiedWhenANestedClassHasTheSameName() + { + var model = new TableModel { Name = "Items", IsAsset = true }; + model.Entries.Add(new EntryModel { Id = 1, Key = "Sprite/Logo", AssetTypeName = "UnityEngine.Sprite" }); + var options = new EmitOptions { Namespace = "Localization", KeySeparators = "/" }; + CodeEmitter.AssignClassNames(new[] { model }, options); var output = CodeEmitter.Emit(model, options); - StringAssert.Contains("using __LT = global::Severnbli.LocalizationCodegen.LocalizedTables;\n", output); - StringAssert.Contains("public static string Greeting => __LT.GetString(TableName, \"Greeting\");", output); - StringAssert.DoesNotContain("global::Severnbli.LocalizationCodegen.LocalizedTables.GetString", output); + StringAssert.Contains("public static class Sprite", output); + StringAssert.Contains("public static global::UnityEngine.Sprite Logo =>", output); + } + + [Test] + public void ClassNames_AvoidReferencedTypeNames() + { + var dictionary = Model("Dictionary", false, (1L, "A")); + var sprite = Model("Sprite", false, (1L, "A")); + var icons = new TableModel { Name = "Icons", IsAsset = true }; + icons.Entries.Add(new EntryModel { Id = 1, Key = "Logo", AssetTypeName = "UnityEngine.Sprite" }); + var options = new EmitOptions { Namespace = "Localization" }; + + CodeEmitter.AssignClassNames(new[] { dictionary, sprite, icons }, options); + + Assert.AreEqual("DictionaryTable", dictionary.ClassName); + Assert.AreEqual("SpriteTable", sprite.ClassName); } [Test] @@ -99,16 +180,18 @@ public void AssetType_SupportsNestedPublicTypes() { Id = 1, Key = "Icon", - AssetTypeName = "global::Game.Outer.Inner" + AssetTypeName = "Game.Outer.Inner", + AssetTypeNamespace = "Game" }); - var options = new EmitOptions { Namespace = "Localization", UseRuntimeAlias = true }; + var options = new EmitOptions { Namespace = "Localization" }; CodeEmitter.AssignClassNames(new[] { model }, options); var output = CodeEmitter.Emit(model, options); StringAssert.Contains( - "public static global::Game.Outer.Inner Icon => __LT.GetAsset(TableName, \"Icon\");", + "public static Outer.Inner Icon => LocalizedTables.GetAsset(TableName, \"Icon\");", output); + StringAssert.Contains("using Game;\n", output); } [Test] @@ -164,21 +247,21 @@ public void ClassNames_AssetCollectionWithSameNameAsStringCollectionGetsAssetsSu public void MemberCollisions_KeepTheOldestEntryNameAndWarnDeterministically() { var model = Model("Ui", false, (2L, "Player Name"), (1L, "Player/Name")); - var options = new EmitOptions { Namespace = "Localization", UseRuntimeAlias = true }; + var options = new EmitOptions { Namespace = "Localization" }; CodeEmitter.AssignClassNames(new[] { model }, options); var output = CodeEmitter.Emit(model, options); StringAssert.Contains("public static string Player_Name =>", output); StringAssert.Contains("public static string Player_Name_2 =>", output); // The older id (1) keeps the base name even though its key sorts later. - StringAssert.Contains("Player_Name => __LT.GetString(TableName, \"Player/Name\");", output); + StringAssert.Contains("Player_Name => LocalizedTables.GetString(TableName, \"Player/Name\");", output); } [Test] public void MemberNames_AvoidObjectMembers() { var model = Model("Ui", false, (1L, "Equals"), (2L, "ToString")); - var options = new EmitOptions { Namespace = "Localization", UseRuntimeAlias = true }; + var options = new EmitOptions { Namespace = "Localization" }; CodeEmitter.AssignClassNames(new[] { model }, options); var output = CodeEmitter.Emit(model, options); @@ -200,7 +283,6 @@ public void XmlDocs_AreEscapedAndSanitized() var options = new EmitOptions { Namespace = "Localization", - UseRuntimeAlias = true, XmlDocs = true }; CodeEmitter.AssignClassNames(new[] { model }, options); @@ -216,7 +298,7 @@ public void XmlDocs_TruncationNeverSplitsAnEscapedEntity() var model = new TableModel { Name = "Ui" }; model.Entries.Add(new EntryModel { Id = 1, Key = "Title", Preview = new string('a', 119) + "&&&" }); - var options = new EmitOptions { Namespace = "Localization", UseRuntimeAlias = true, XmlDocs = true }; + var options = new EmitOptions { Namespace = "Localization", XmlDocs = true }; CodeEmitter.AssignClassNames(new[] { model }, options); var output = CodeEmitter.Emit(model, options); @@ -244,7 +326,6 @@ public void SmartString_EmitsMethodWithPositionalParameters() var options = new EmitOptions { Namespace = "Localization", - UseRuntimeAlias = true, SmartStrings = SmartStringMode.Methods, SmartParamTypes = SmartParamTypeMode.Inferred }; @@ -253,7 +334,7 @@ public void SmartString_EmitsMethodWithPositionalParameters() StringAssert.Contains( "public static string Greeting(object arg0)\n" + - " => __LT.GetString(TableName, \"Greeting\", arg0);", + " => LocalizedTables.GetString(TableName, \"Greeting\", arg0);", output); StringAssert.Contains("/// positional {0}", output); } @@ -275,15 +356,14 @@ public void SmartString_NamedOnlyUsesDictionary() var options = new EmitOptions { Namespace = "Localization", - UseRuntimeAlias = true, SmartStrings = SmartStringMode.Methods }; CodeEmitter.AssignClassNames(new[] { model }, options); var output = CodeEmitter.Emit(model, options); StringAssert.Contains( - "__LT.GetString(TableName, \"Greeting\", " + - "new global::System.Collections.Generic.Dictionary { [\"player-name\"] = playerName });", + "LocalizedTables.GetString(TableName, \"Greeting\", " + + "new Dictionary { [\"player-name\"] = playerName });", output); } @@ -299,14 +379,13 @@ public void SmartString_MixedUsesGetStringMixed() var options = new EmitOptions { Namespace = "Localization", - UseRuntimeAlias = true, SmartStrings = SmartStringMode.Methods }; CodeEmitter.AssignClassNames(new[] { model }, options); var output = CodeEmitter.Emit(model, options); - StringAssert.Contains("__LT.GetStringMixed(TableName, \"Greeting\", new object[] { arg0 }, " + - "new global::System.Collections.Generic.Dictionary { [\"count\"] = count });", + StringAssert.Contains("LocalizedTables.GetStringMixed(TableName, \"Greeting\", new object[] { arg0 }, " + + "new Dictionary { [\"count\"] = count });", output); } @@ -315,12 +394,11 @@ public void Refs_EmitLocalizedStringAndLocalizedAssetMembers() { var model = new TableModel { Name = "Ui" }; model.Entries.Add(new EntryModel { Id = 1, Key = "Title" }); - model.Entries.Add(new EntryModel { Id = 2, Key = "Sprite", AssetTypeName = "global::UnityEngine.Sprite" }); + model.Entries.Add(new EntryModel { Id = 2, Key = "Sprite", AssetTypeName = "UnityEngine.Sprite" }); var options = new EmitOptions { Namespace = "Localization", - UseRuntimeAlias = true, Refs = true }; CodeEmitter.AssignClassNames(new[] { model }, options); @@ -328,12 +406,11 @@ public void Refs_EmitLocalizedStringAndLocalizedAssetMembers() StringAssert.Contains("public static class Ref", output); StringAssert.Contains( - "public static global::UnityEngine.Localization.LocalizedString Title => " + - "new global::UnityEngine.Localization.LocalizedString(TableName, \"Title\");", + "public static LocalizedString Title => new LocalizedString(TableName, \"Title\");", output); StringAssert.Contains( - "public static global::UnityEngine.Localization.LocalizedSprite Sprite => " + - "new global::UnityEngine.Localization.LocalizedSprite { TableReference = TableName, TableEntryReference = \"Sprite\" };", + "public static LocalizedSprite Sprite => " + + "new LocalizedSprite { TableReference = TableName, TableEntryReference = \"Sprite\" };", output); } @@ -341,7 +418,7 @@ public void Refs_EmitLocalizedStringAndLocalizedAssetMembers() public void Refs_AvoidObjectMembers() { var model = Model("Ui", false, (1L, "ToString")); - var options = new EmitOptions { Namespace = "Localization", UseRuntimeAlias = true, Refs = true }; + var options = new EmitOptions { Namespace = "Localization", Refs = true }; CodeEmitter.AssignClassNames(new[] { model }, options); var output = CodeEmitter.Emit(model, options); @@ -355,7 +432,6 @@ static EmitOptions UniTaskOptions() return new EmitOptions { Namespace = "Localization", - UseRuntimeAlias = true, SmartStrings = SmartStringMode.Methods, UniTask = true }; @@ -365,7 +441,7 @@ static EmitOptions UniTaskOptions() public void UniTask_IsNotEmittedByDefault() { var model = Model("Ui", false, (1L, "Title")); - var options = new EmitOptions { Namespace = "Localization", UseRuntimeAlias = true }; + var options = new EmitOptions { Namespace = "Localization" }; CodeEmitter.AssignClassNames(new[] { model }, options); var output = CodeEmitter.Emit(model, options); @@ -381,11 +457,11 @@ public void UniTask_StringEntryGetsAsyncMethod() CodeEmitter.AssignClassNames(new[] { model }, options); var output = CodeEmitter.Emit(model, options); - StringAssert.Contains("public static string Title => __LT.GetString(TableName, \"Title\");", output); + StringAssert.Contains("public static string Title => LocalizedTables.GetString(TableName, \"Title\");", output); StringAssert.Contains( - "public static global::Cysharp.Threading.Tasks.UniTask TitleAsync(" + - "global::System.Threading.CancellationToken cancellationToken = default)\n" + - " => global::Severnbli.LocalizationCodegen.LocalizedTablesUniTask.GetStringAsync(" + + "public static UniTask TitleAsync(" + + "CancellationToken cancellationToken = default)\n" + + " => LocalizedTablesUniTask.GetStringAsync(" + "TableName, \"Title\", cancellationToken);", output); } @@ -404,12 +480,12 @@ public void UniTask_SmartStringPassesArgumentsAndToken() var output = CodeEmitter.Emit(model, options); StringAssert.Contains( - "public static global::Cysharp.Threading.Tasks.UniTask GreetingAsync(object arg0, object player, " + - "global::System.Threading.CancellationToken cancellationToken = default)", + "public static UniTask GreetingAsync(object arg0, object player, " + + "CancellationToken cancellationToken = default)", output); StringAssert.Contains( ".GetStringAsync(TableName, \"Greeting\", new object[] { arg0 }, " + - "new global::System.Collections.Generic.Dictionary { [\"player\"] = player }, cancellationToken);", + "new Dictionary { [\"player\"] = player }, cancellationToken);", output); StringAssert.Contains("/// ", output); } @@ -426,7 +502,7 @@ public void UniTask_TokenParameterAvoidsSmartStringParameterNames() CodeEmitter.AssignClassNames(new[] { model }, options); var output = CodeEmitter.Emit(model, options); - StringAssert.Contains("WaitAsync(object cancellationToken, global::System.Threading.CancellationToken cancellationToken_2 = default)", output); + StringAssert.Contains("WaitAsync(object cancellationToken, CancellationToken cancellationToken_2 = default)", output); StringAssert.Contains("[\"cancellationToken\"] = cancellationToken }, cancellationToken_2);", output); } @@ -434,16 +510,16 @@ public void UniTask_TokenParameterAvoidsSmartStringParameterNames() public void UniTask_AssetEntryGetsAsyncMethod() { var model = new TableModel { Name = "Icons", IsAsset = true }; - model.Entries.Add(new EntryModel { Id = 1, Key = "Logo", AssetTypeName = "global::UnityEngine.Sprite" }); + model.Entries.Add(new EntryModel { Id = 1, Key = "Logo", AssetTypeName = "UnityEngine.Sprite" }); var options = UniTaskOptions(); CodeEmitter.AssignClassNames(new[] { model }, options); var output = CodeEmitter.Emit(model, options); StringAssert.Contains( - "public static global::Cysharp.Threading.Tasks.UniTask LogoAsync(" + - "global::System.Threading.CancellationToken cancellationToken = default)\n" + - " => global::Severnbli.LocalizationCodegen.LocalizedTablesUniTask.GetAssetAsync(" + + "public static UniTask LogoAsync(" + + "CancellationToken cancellationToken = default)\n" + + " => LocalizedTablesUniTask.GetAssetAsync(" + "TableName, \"Logo\", cancellationToken);", output); } @@ -457,7 +533,7 @@ public void UniTask_AsyncNamesNeverTakeAnExistingKeyName() CodeEmitter.AssignClassNames(new[] { model }, options); var output = CodeEmitter.Emit(model, options); - StringAssert.Contains("public static string TitleAsync => __LT.GetString(TableName, \"TitleAsync\");", output); + StringAssert.Contains("public static string TitleAsync => LocalizedTables.GetString(TableName, \"TitleAsync\");", output); StringAssert.Contains("UniTask TitleAsync_2(", output); StringAssert.Contains("UniTask TitleAsyncAsync(", output); StringAssert.Contains("UniTask classAsync(", output); @@ -492,7 +568,6 @@ public void KeySeparators_CreateNestedClasses() var options = new EmitOptions { Namespace = "Localization", - UseRuntimeAlias = true, KeySeparators = "/", Naming = NamingConvention.PascalCase }; diff --git a/Unity-Package/Assets/root/Tests/Editor/GeneratedCodeCompilationTests.cs b/Unity-Package/Assets/root/Tests/Editor/GeneratedCodeCompilationTests.cs index 236f29c..1e68118 100644 --- a/Unity-Package/Assets/root/Tests/Editor/GeneratedCodeCompilationTests.cs +++ b/Unity-Package/Assets/root/Tests/Editor/GeneratedCodeCompilationTests.cs @@ -154,7 +154,6 @@ static IEnumerable Variants(bool uniTask) Options = new EmitOptions { Namespace = "CompileCheck.Full", - UseRuntimeAlias = true, Refs = true, XmlDocs = true, SmartStrings = SmartStringMode.MethodsAndRefs, @@ -164,14 +163,13 @@ static IEnumerable Variants(bool uniTask) } }; - // PascalCase names in the global namespace without the alias. + // PascalCase names in the global namespace. yield return new Variant { Name = "Global", Options = new EmitOptions { Namespace = null, - UseRuntimeAlias = false, Refs = true, XmlDocs = true, SmartStrings = SmartStringMode.Methods, @@ -180,11 +178,11 @@ static IEnumerable Variants(bool uniTask) } }; - // The 1.0 output. + // Default options. yield return new Variant { Name = "Legacy", - Options = new EmitOptions { Namespace = "CompileCheck.Legacy", UseRuntimeAlias = false, UniTask = uniTask } + Options = new EmitOptions { Namespace = "CompileCheck.Legacy", UniTask = uniTask } }; } @@ -214,17 +212,19 @@ static List BuildModels() mixed.Params.Add(new SmartParam { IsPositional = true, Index = 0, SourceName = "0", ClrName = "arg0", TypeName = "object" }); mixed.Params.Add(new SmartParam { - SourceName = "items", ClrName = "items", TypeName = "global::System.Collections.IEnumerable", FormatterName = "list" + SourceName = "items", ClrName = "items", TypeName = "System.Collections.IEnumerable", FormatterName = "list" }); strings.Entries.Add(mixed); var assets = new TableModel { Name = "Ui", IsAsset = true }; - assets.Entries.Add(new EntryModel { Id = 1, Key = "Logo", AssetTypeName = "global::UnityEngine.Sprite" }); - assets.Entries.Add(new EntryModel { Id = 2, Key = "Theme", AssetTypeName = "global::UnityEngine.AudioClip" }); - assets.Entries.Add(new EntryModel { Id = 3, Key = "Anything", AssetTypeName = "global::UnityEngine.Object" }); - assets.Entries.Add(new EntryModel { Id = 4, Key = "Mesh", AssetTypeName = "global::UnityEngine.Mesh" }); + assets.Entries.Add(new EntryModel { Id = 1, Key = "Logo", AssetTypeName = "UnityEngine.Sprite" }); + assets.Entries.Add(new EntryModel { Id = 2, Key = "Theme", AssetTypeName = "UnityEngine.AudioClip" }); + assets.Entries.Add(new EntryModel { Id = 3, Key = "Anything", AssetTypeName = "UnityEngine.Object" }); + assets.Entries.Add(new EntryModel { Id = 4, Key = "Mesh", AssetTypeName = "UnityEngine.Mesh" }); // No dedicated Localized* type: uses the generic LocalizedAsset. - assets.Entries.Add(new EntryModel { Id = 5, Key = "Background", AssetTypeName = "global::UnityEngine.Texture2D" }); + assets.Entries.Add(new EntryModel { Id = 5, Key = "Background", AssetTypeName = "UnityEngine.Texture2D" }); + // With key separators this creates a nested class Sprite, so the asset type must stay qualified. + assets.Entries.Add(new EntryModel { Id = 6, Key = "Sprite/Icon", AssetTypeName = "UnityEngine.Sprite" }); return new List { strings, assets }; } diff --git a/Unity-Package/Assets/root/Tests/Editor/GenerationIntegrationTests.cs b/Unity-Package/Assets/root/Tests/Editor/GenerationIntegrationTests.cs index d1de1a7..118e7a7 100644 --- a/Unity-Package/Assets/root/Tests/Editor/GenerationIntegrationTests.cs +++ b/Unity-Package/Assets/root/Tests/Editor/GenerationIntegrationTests.cs @@ -24,7 +24,6 @@ public class GenerationIntegrationTests bool m_AutoRegenerate; bool m_GenerateStringTables; bool m_GenerateAssetTables; - bool m_UseRuntimeAlias; SmartStringMode m_SmartStrings; bool m_GenerateUniTask; string m_LastOutputFolder; @@ -43,7 +42,6 @@ public void SetUp() m_AutoRegenerate = m_Settings.AutoRegenerate; m_GenerateStringTables = m_Settings.GenerateStringTables; m_GenerateAssetTables = m_Settings.GenerateAssetTables; - m_UseRuntimeAlias = m_Settings.UseRuntimeAlias; m_SmartStrings = m_Settings.SmartStrings; m_GenerateUniTask = m_Settings.GenerateUniTask; m_LastOutputFolder = m_Settings.LastOutputFolder; @@ -67,7 +65,6 @@ public void SetUp() m_Settings.AutoRegenerate = false; m_Settings.GenerateStringTables = true; m_Settings.GenerateAssetTables = false; - m_Settings.UseRuntimeAlias = false; m_Settings.SmartStrings = SmartStringMode.Off; m_Settings.GenerateUniTask = false; m_Settings.Namespace = "CodegenIntegrationTests"; @@ -85,7 +82,6 @@ public void TearDown() m_Settings.AutoRegenerate = m_AutoRegenerate; m_Settings.GenerateStringTables = m_GenerateStringTables; m_Settings.GenerateAssetTables = m_GenerateAssetTables; - m_Settings.UseRuntimeAlias = m_UseRuntimeAlias; m_Settings.SmartStrings = m_SmartStrings; m_Settings.GenerateUniTask = m_GenerateUniTask; m_Settings.LastOutputFolder = m_LastOutputFolder; diff --git a/Unity-Package/Assets/root/package.json b/Unity-Package/Assets/root/package.json index f068154..36878e5 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.1", + "version": "1.2.2", "unity": "2021.3", "description": "C# classes and properties generator from Unity Localization tables", "documentationUrl": "https://github.com/Severnbli/localization-codegen/blob/main/README.md",