From 721d0e76a3cdd5725c04949bb42be1b9656abbde Mon Sep 17 00:00:00 2001 From: hatayama Date: Sat, 28 Nov 2026 18:01:41 +0900 Subject: [PATCH 1/3] fix: refuse an internal extension call that a same-named public extension turns into CS1929 or CS1503 The worker binds against the target assembly's public surface only, so an internal extension method declared in a file the reload was not given is missing to it. A call such as `50.Twice(1)` normally fails there with CS1061, which the unresolved-name guard maps to the compiled internal extension and skips when the call runs outside the patched method (lambda, async or iterator body, delegating shim). When a public extension method of the same name exists elsewhere in the assembly and does not take the call, the compiler reports CS1929 (other receiver type, marked on the receiver) or CS1503 (other argument type, marked on the argument) instead. Neither ID was recognized, the guard let the body through, the shim compile bound the internal method directly, and the call threw MethodAccessException after being reported as Patched. - InapplicableCallName recognizes CS1929 / CS1503 and finds the called name from the node the error marks (receiver, through parentheses, or argument). - UnpassedInternalMemberUse looks such a call up only as an internal extension, which is used only for a use outside the patched method, so the new IDs can only refuse a body, never let one through. - UnresolvedBodyNameGuard handles them apart from the missing-name IDs: with no internal extension behind the call, a plain or partial type goes on to the shim compile as before. The out-of-reach check is extracted to keep DescribeSkipOrNull under the complexity limit. Tests: HotReloadSameNameExtensionCallE2ETests (plain and partial callers; lambda, conditional access, member-access receiver, int-taking same-name overload, async, iterator, plus own-statement controls) and a worker test that a CS1929 with no internal extension behind it is not skipped. Fixes #3628 --- .../HotReloadSameNameExtensionCallE2ETests.cs | 267 ++++++++++++++++++ ...eloadSameNameExtensionCallE2ETests.cs.meta | 11 + .../HotReloadSameNameExtensionCaller.cs | 63 +++++ .../HotReloadSameNameExtensionCaller.cs.meta | 11 + ...HotReloadSameNameExtensionPartialCaller.cs | 62 ++++ ...loadSameNameExtensionPartialCaller.cs.meta | 11 + .../HotReloadSameNameInternalExtensionMath.cs | 22 ++ ...eloadSameNameInternalExtensionMath.cs.meta | 11 + .../HotReloadSameNamePublicExtensionMath.cs | 20 ++ ...tReloadSameNamePublicExtensionMath.cs.meta | 11 + ...ormWorkerInapplicableExtensionCallTests.cs | 102 +++++++ ...rkerInapplicableExtensionCallTests.cs.meta | 11 + .../TransformWorker~/InapplicableCallName.cs | 109 +++++++ .../UnpassedInternalMemberUse.cs | 40 ++- .../UnresolvedBodyNameGuard.cs | 76 +++-- 15 files changed, 799 insertions(+), 28 deletions(-) create mode 100644 Assets/Tests/Editor/HotReload/HotReloadSameNameExtensionCallE2ETests.cs create mode 100644 Assets/Tests/Editor/HotReload/HotReloadSameNameExtensionCallE2ETests.cs.meta create mode 100644 Assets/Tests/Editor/HotReload/HotReloadSameNameExtensionCaller.cs create mode 100644 Assets/Tests/Editor/HotReload/HotReloadSameNameExtensionCaller.cs.meta create mode 100644 Assets/Tests/Editor/HotReload/HotReloadSameNameExtensionPartialCaller.cs create mode 100644 Assets/Tests/Editor/HotReload/HotReloadSameNameExtensionPartialCaller.cs.meta create mode 100644 Assets/Tests/Editor/HotReload/HotReloadSameNameInternalExtensionMath.cs create mode 100644 Assets/Tests/Editor/HotReload/HotReloadSameNameInternalExtensionMath.cs.meta create mode 100644 Assets/Tests/Editor/HotReload/HotReloadSameNamePublicExtensionMath.cs create mode 100644 Assets/Tests/Editor/HotReload/HotReloadSameNamePublicExtensionMath.cs.meta create mode 100644 Assets/Tests/Editor/HotReload/TransformWorkerInapplicableExtensionCallTests.cs create mode 100644 Assets/Tests/Editor/HotReload/TransformWorkerInapplicableExtensionCallTests.cs.meta create mode 100644 Packages/src/Editor/FirstPartyTools/HotReload/TransformWorker~/InapplicableCallName.cs diff --git a/Assets/Tests/Editor/HotReload/HotReloadSameNameExtensionCallE2ETests.cs b/Assets/Tests/Editor/HotReload/HotReloadSameNameExtensionCallE2ETests.cs new file mode 100644 index 000000000..f1a7a5098 --- /dev/null +++ b/Assets/Tests/Editor/HotReload/HotReloadSameNameExtensionCallE2ETests.cs @@ -0,0 +1,267 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Threading; +using System.Threading.Tasks; + +using NUnit.Framework; + +using UnityEngine; + +using io.github.hatayama.UnityCliLoop.FirstPartyTools; +using io.github.hatayama.UnityCliLoop.ToolContracts; + +namespace io.github.hatayama.UnityCliLoop.Tests.Editor.HotReload +{ + /// + /// End-to-end EditMode coverage for an edited call to an internal extension method of an + /// internal class the reload was not given, when a public extension method of another class + /// in the same assembly shares its name but never applies to the call. + /// + public class HotReloadSameNameExtensionCallE2ETests + { + private const string OwnStatementsValue = "OwnStatementsValue"; + + // Public only because a test case argument has to be as visible as the test method. + public enum FixtureKind + { + Plain, + Partial + } + + private HotReloadDomainTestScope _scope; + + [SetUp] + public void SetUp() + { + _scope = new HotReloadDomainTestScope(); + HotReloadAutoRefreshHold.SyncToActiveChanges(); + } + + [TearDown] + public void TearDown() + { + _scope.Dispose(); + HotReloadAutoRefreshHold.SyncToActiveChanges(); + VibeLogger.ClearMemoryLogs(); + } + + // Calls the shim assembly compiles as code of its own: in a lambda, through conditional + // access, on a receiver that is itself a member access, beside a same-named public extension + // that takes an int with another argument type, in an async body and in an iterator body. + private static IEnumerable CallsInShimCompiledBodies() + { + yield return new TestCaseData("LambdaValue", "() => 20", "() => 50.AddDouble(1)", 20, 101); + yield return new TestCaseData("ConditionalAccessLambdaValue", "() => 30", "() => ((int?)50)?.AddDouble(1) ?? 0", 30, 101); + yield return new TestCaseData("MemberAccessReceiverLambdaValue", "() => this._seed + 10", "() => this._seed.AddDouble(1)", 60, 101); + yield return new TestCaseData("IntOverloadLambdaValue", "() => 70", "() => 50.AddTriple(1)", 70, 151); + yield return new TestCaseData("AsyncValue", "return 40;", "return 50.AddDouble(1);", 40, 101); + yield return new TestCaseData("IteratorValues", "yield return 50;", "yield return 50.AddDouble(1);", 50, 101); + } + + /// + /// What: a plain type's own statements calling the internal extension method are patched, and + /// the method returns the edited value, so the public method of the same name does not get in + /// the way of the in-place call. + /// + [Test] + public async Task Run_PlainOwnStatementsCallingInternalExtensionBesideSameNamePublicOne_PatchesBehavior() + { + HotReloadOrchestratorResult result = await RunEditAsync(FixtureKind.Plain, OwnStatementsValue, "return 10;", "return 50.AddDouble(1);"); + + Assert.That(FindRow(result, FixtureKind.Plain, OwnStatementsValue).Kind, Is.EqualTo(HotReloadMethodOutcomeKind.Patched), FormatOutcomes(result)); + Assert.That(await CallAsync(FixtureKind.Plain, OwnStatementsValue), Is.EqualTo(101), FormatOutcomes(result)); + } + + /// + /// What: a partial type's own statements calling the internal extension method are either + /// patched and return the edited value, or skipped and keep the compiled value. They are never + /// reported as patched and then throw when called. + /// + [Test] + public async Task Run_PartialOwnStatementsCallingInternalExtensionBesideSameNamePublicOne_IsAppliedAsEditedOrSkipped() + { + HotReloadOrchestratorResult result = await RunEditAsync(FixtureKind.Partial, OwnStatementsValue, "return 10;", "return 50.AddDouble(1);"); + + HotReloadMethodOutcomeKind kind = FindRow(result, FixtureKind.Partial, OwnStatementsValue).Kind; + Assert.That( + kind, + Is.EqualTo(HotReloadMethodOutcomeKind.Patched).Or.EqualTo(HotReloadMethodOutcomeKind.Skipped), + FormatOutcomes(result)); + int expected = kind == HotReloadMethodOutcomeKind.Patched ? 101 : 10; + Assert.That(await CallAsync(FixtureKind.Partial, OwnStatementsValue), Is.EqualTo(expected), FormatOutcomes(result)); + } + + /// + /// What: on a plain type, a call to the internal extension method that the shim assembly + /// compiles as code of its own is either patched and returns the edited value, or skipped and + /// keeps the compiled value. It is never reported as patched and then throws when called. + /// + [TestCaseSource(nameof(CallsInShimCompiledBodies))] + public async Task Run_PlainCallInShimCompiledBodyBesideSameNamePublicExtension_IsAppliedAsEditedOrSkipped( + string methodName, + string fragment, + string replacement, + int compiledValue, + int editedValue) + { + HotReloadOrchestratorResult result = await RunEditAsync(FixtureKind.Plain, methodName, fragment, replacement); + + HotReloadMethodOutcomeKind kind = FindRow(result, FixtureKind.Plain, methodName).Kind; + Assert.That( + kind, + Is.EqualTo(HotReloadMethodOutcomeKind.Patched).Or.EqualTo(HotReloadMethodOutcomeKind.Skipped), + FormatOutcomes(result)); + int expected = kind == HotReloadMethodOutcomeKind.Patched ? editedValue : compiledValue; + Assert.That(await CallAsync(FixtureKind.Plain, methodName), Is.EqualTo(expected), FormatOutcomes(result)); + } + + /// + /// What: on a partial type, the same calls are skipped and the method keeps the compiled + /// value, instead of being reported as patched and then throwing when called. + /// + [TestCaseSource(nameof(CallsInShimCompiledBodies))] + public async Task Run_PartialCallInShimCompiledBodyBesideSameNamePublicExtension_IsSkipped( + string methodName, + string fragment, + string replacement, + int compiledValue, + int editedValue) + { + HotReloadOrchestratorResult result = await RunEditAsync(FixtureKind.Partial, methodName, fragment, replacement); + + Assert.That(FindRow(result, FixtureKind.Partial, methodName).Kind, Is.EqualTo(HotReloadMethodOutcomeKind.Skipped), FormatOutcomes(result)); + Assert.That(await CallAsync(FixtureKind.Partial, methodName), Is.EqualTo(compiledValue), FormatOutcomes(result)); + } + + private static async Task RunEditAsync( + FixtureKind fixture, + string methodName, + string fragment, + string replacement) + { + string path = FixturePath(TypeName(fixture) + ".cs"); + string edited = HotReloadTestSourceWriter.WriteEditedSource( + "SameNameExtension" + fixture + methodName + ".cs", + ReplaceOnce(File.ReadAllText(path), fragment, replacement)); + return await HotReloadCompositionRoot.Services.Orchestrator.RunAsync( + new[] { path }, + contentPathOverride: null, + CancellationToken.None, + new Dictionary { [path] = edited }); + } + + // Why async: the async fixture method is awaited rather than waited on, because an EditMode + // test must not block the main thread on a task. + private static async Task CallAsync(FixtureKind fixture, string methodName) + { + if (fixture == FixtureKind.Plain) + { + HotReloadSameNameExtensionCaller plain = new HotReloadSameNameExtensionCaller(); + switch (methodName) + { + case OwnStatementsValue: + return plain.OwnStatementsValue(); + case "LambdaValue": + return plain.LambdaValue(); + case "ConditionalAccessLambdaValue": + return plain.ConditionalAccessLambdaValue(); + case "MemberAccessReceiverLambdaValue": + return plain.MemberAccessReceiverLambdaValue(); + case "IntOverloadLambdaValue": + return plain.IntOverloadLambdaValue(); + case "AsyncValue": + return await plain.AsyncValue(); + case "IteratorValues": + return First(plain.IteratorValues()); + } + } + else + { + HotReloadSameNameExtensionPartialCaller partial = new HotReloadSameNameExtensionPartialCaller(); + switch (methodName) + { + case OwnStatementsValue: + return partial.OwnStatementsValue(); + case "LambdaValue": + return partial.LambdaValue(); + case "ConditionalAccessLambdaValue": + return partial.ConditionalAccessLambdaValue(); + case "MemberAccessReceiverLambdaValue": + return partial.MemberAccessReceiverLambdaValue(); + case "IntOverloadLambdaValue": + return partial.IntOverloadLambdaValue(); + case "AsyncValue": + return await partial.AsyncValue(); + case "IteratorValues": + return First(partial.IteratorValues()); + } + } + + throw new ArgumentException("Unknown caller method: " + methodName); + } + + private static int First(IEnumerable values) + { + foreach (int value in values) + { + return value; + } + + throw new InvalidOperationException("The iterator yielded nothing."); + } + + private static string TypeName(FixtureKind fixture) + { + return fixture == FixtureKind.Plain ? nameof(HotReloadSameNameExtensionCaller) : nameof(HotReloadSameNameExtensionPartialCaller); + } + + // Why the type and the parenthesis: a bare method name would also match a longer name that + // contains it, or the same method on the other fixture type. + private static HotReloadMethodOutcome FindRow(HotReloadOrchestratorResult result, FixtureKind fixture, string methodName) + { + string labelPart = "." + TypeName(fixture) + "." + methodName + "("; + foreach (HotReloadMethodOutcome outcome in result.Methods) + { + if (outcome.Method != null && outcome.Method.Contains(labelPart)) + { + return outcome; + } + } + + Assert.Fail("No row for " + TypeName(fixture) + "." + methodName + ".\n" + FormatOutcomes(result)); + return null; + } + + // Why the uniqueness check: a fragment that also matched another member would edit a method + // the test does not call, and the assert would pass or fail for the wrong reason. + private static string ReplaceOnce(string source, string fragment, string replacement) + { + int first = source.IndexOf(fragment, StringComparison.Ordinal); + Assert.That(first, Is.GreaterThanOrEqualTo(0), "Fragment missing from the fixture: " + fragment); + Assert.That( + source.IndexOf(fragment, first + fragment.Length, StringComparison.Ordinal), + Is.EqualTo(-1), + "Fragment occurs more than once in the fixture: " + fragment); + return source.Replace(fragment, replacement, StringComparison.Ordinal); + } + + private static string FixturePath(string fileName) + { + string path = Path.GetFullPath(Path.Combine(Application.dataPath, "Tests", "Editor", "HotReload", fileName)); + Assert.That(File.Exists(path), Is.True, "Fixture missing: " + path); + return path; + } + + private static string FormatOutcomes(HotReloadOrchestratorResult result) + { + List lines = new List(); + foreach (HotReloadMethodOutcome outcome in result.Methods) + { + lines.Add(outcome.Kind + " " + outcome.Method + " :: " + outcome.Reason); + } + + return string.Join("\n", lines) + "\nWarnings:\n" + string.Join("\n", result.Warnings); + } + } +} diff --git a/Assets/Tests/Editor/HotReload/HotReloadSameNameExtensionCallE2ETests.cs.meta b/Assets/Tests/Editor/HotReload/HotReloadSameNameExtensionCallE2ETests.cs.meta new file mode 100644 index 000000000..23dd342bd --- /dev/null +++ b/Assets/Tests/Editor/HotReload/HotReloadSameNameExtensionCallE2ETests.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 42a2ace7b64134354b8c698e39a20541 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Tests/Editor/HotReload/HotReloadSameNameExtensionCaller.cs b/Assets/Tests/Editor/HotReload/HotReloadSameNameExtensionCaller.cs new file mode 100644 index 000000000..7dc01680c --- /dev/null +++ b/Assets/Tests/Editor/HotReload/HotReloadSameNameExtensionCaller.cs @@ -0,0 +1,63 @@ +using System; +using System.Collections.Generic; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; + +namespace io.github.hatayama.UnityCliLoop.Tests.Editor.HotReload +{ + /// + /// Methods the same-name extension tests edit to call an internal extension method whose name a + /// public extension method of another class shares. + /// + public class HotReloadSameNameExtensionCaller + { + private int _seed = 50; + + [MethodImpl(MethodImplOptions.NoInlining)] + public int OwnStatementsValue() + { + return 10; + } + + [MethodImpl(MethodImplOptions.NoInlining)] + public int LambdaValue() + { + Func read = () => 20; + return read(); + } + + [MethodImpl(MethodImplOptions.NoInlining)] + public int ConditionalAccessLambdaValue() + { + Func read = () => 30; + return read(); + } + + [MethodImpl(MethodImplOptions.NoInlining)] + public int MemberAccessReceiverLambdaValue() + { + Func read = () => this._seed + 10; + return read(); + } + + [MethodImpl(MethodImplOptions.NoInlining)] + public int IntOverloadLambdaValue() + { + Func read = () => 70; + return read(); + } + + [MethodImpl(MethodImplOptions.NoInlining)] + public async Task AsyncValue() + { + await Task.CompletedTask; + return 40; + } + + [MethodImpl(MethodImplOptions.NoInlining)] + public IEnumerable IteratorValues() + { + yield return 50; + } + } +} diff --git a/Assets/Tests/Editor/HotReload/HotReloadSameNameExtensionCaller.cs.meta b/Assets/Tests/Editor/HotReload/HotReloadSameNameExtensionCaller.cs.meta new file mode 100644 index 000000000..162b6b86e --- /dev/null +++ b/Assets/Tests/Editor/HotReload/HotReloadSameNameExtensionCaller.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 33871b904a7854771add1542378cce99 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Tests/Editor/HotReload/HotReloadSameNameExtensionPartialCaller.cs b/Assets/Tests/Editor/HotReload/HotReloadSameNameExtensionPartialCaller.cs new file mode 100644 index 000000000..c3614be38 --- /dev/null +++ b/Assets/Tests/Editor/HotReload/HotReloadSameNameExtensionPartialCaller.cs @@ -0,0 +1,62 @@ +using System; +using System.Collections.Generic; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; + +namespace io.github.hatayama.UnityCliLoop.Tests.Editor.HotReload +{ + /// + /// The partial-type counterpart of . + /// + public partial class HotReloadSameNameExtensionPartialCaller + { + private int _seed = 50; + + [MethodImpl(MethodImplOptions.NoInlining)] + public int OwnStatementsValue() + { + return 10; + } + + [MethodImpl(MethodImplOptions.NoInlining)] + public int LambdaValue() + { + Func read = () => 20; + return read(); + } + + [MethodImpl(MethodImplOptions.NoInlining)] + public int ConditionalAccessLambdaValue() + { + Func read = () => 30; + return read(); + } + + [MethodImpl(MethodImplOptions.NoInlining)] + public int MemberAccessReceiverLambdaValue() + { + Func read = () => this._seed + 10; + return read(); + } + + [MethodImpl(MethodImplOptions.NoInlining)] + public int IntOverloadLambdaValue() + { + Func read = () => 70; + return read(); + } + + [MethodImpl(MethodImplOptions.NoInlining)] + public async Task AsyncValue() + { + await Task.CompletedTask; + return 40; + } + + [MethodImpl(MethodImplOptions.NoInlining)] + public IEnumerable IteratorValues() + { + yield return 50; + } + } +} diff --git a/Assets/Tests/Editor/HotReload/HotReloadSameNameExtensionPartialCaller.cs.meta b/Assets/Tests/Editor/HotReload/HotReloadSameNameExtensionPartialCaller.cs.meta new file mode 100644 index 000000000..d1cb5e3bb --- /dev/null +++ b/Assets/Tests/Editor/HotReload/HotReloadSameNameExtensionPartialCaller.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 9d7f28f787588401cb582a17711b1c54 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Tests/Editor/HotReload/HotReloadSameNameInternalExtensionMath.cs b/Assets/Tests/Editor/HotReload/HotReloadSameNameInternalExtensionMath.cs new file mode 100644 index 000000000..fc91a676c --- /dev/null +++ b/Assets/Tests/Editor/HotReload/HotReloadSameNameInternalExtensionMath.cs @@ -0,0 +1,22 @@ +namespace io.github.hatayama.UnityCliLoop.Tests.Editor.HotReload +{ + /// + /// Internal extension method whose name a public extension method of another class shares. + /// + /// + /// Why a name of its own: a public extension method named like an existing fixture method would + /// change the outcome of every other test that calls that method. + /// + internal static class HotReloadSameNameInternalExtensionMath + { + internal static int AddDouble(this int value, int add) + { + return value * 2 + add; + } + + internal static int AddTriple(this int value, int add) + { + return value * 3 + add; + } + } +} diff --git a/Assets/Tests/Editor/HotReload/HotReloadSameNameInternalExtensionMath.cs.meta b/Assets/Tests/Editor/HotReload/HotReloadSameNameInternalExtensionMath.cs.meta new file mode 100644 index 000000000..cdc152629 --- /dev/null +++ b/Assets/Tests/Editor/HotReload/HotReloadSameNameInternalExtensionMath.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: fe5a2644066094500bd25c000ed3f6d5 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Tests/Editor/HotReload/HotReloadSameNamePublicExtensionMath.cs b/Assets/Tests/Editor/HotReload/HotReloadSameNamePublicExtensionMath.cs new file mode 100644 index 000000000..2715312ea --- /dev/null +++ b/Assets/Tests/Editor/HotReload/HotReloadSameNamePublicExtensionMath.cs @@ -0,0 +1,20 @@ +namespace io.github.hatayama.UnityCliLoop.Tests.Editor.HotReload +{ + /// + /// Public extension methods that share their names with internal ones of another class and never + /// apply to the calls the tests make: one takes another receiver type, one takes an int + /// receiver with another argument type. + /// + public static class HotReloadSameNamePublicExtensionMath + { + public static int AddDouble(this string value, object other) + { + return value.Length; + } + + public static int AddTriple(this int value, string other) + { + return value + other.Length; + } + } +} diff --git a/Assets/Tests/Editor/HotReload/HotReloadSameNamePublicExtensionMath.cs.meta b/Assets/Tests/Editor/HotReload/HotReloadSameNamePublicExtensionMath.cs.meta new file mode 100644 index 000000000..d4ba92d05 --- /dev/null +++ b/Assets/Tests/Editor/HotReload/HotReloadSameNamePublicExtensionMath.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 52d1783e494844a3faf3d72d68a69c29 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Tests/Editor/HotReload/TransformWorkerInapplicableExtensionCallTests.cs b/Assets/Tests/Editor/HotReload/TransformWorkerInapplicableExtensionCallTests.cs new file mode 100644 index 000000000..d23242638 --- /dev/null +++ b/Assets/Tests/Editor/HotReload/TransformWorkerInapplicableExtensionCallTests.cs @@ -0,0 +1,102 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Threading; +using System.Threading.Tasks; + +using NUnit.Framework; + +using UnityEngine; + +using io.github.hatayama.UnityCliLoop.FirstPartyTools; + +namespace io.github.hatayama.UnityCliLoop.Tests.Editor.HotReload +{ + /// + /// Transform worker coverage for a call whose name only binds to a same-named public extension + /// method that does not take it (CS1929), when no internal extension method of a file the run + /// does not pass takes the call either. + /// + public class TransformWorkerInapplicableExtensionCallTests + { + private const string FixtureDirectory = "Assets/Tests/Editor/HotReload/"; + + /// + /// What: a lambda calling a same-named public extension method that does not take its + /// receiver, with no internal extension method behind the call, is not skipped by the worker + /// and stays an entry, so the shim compile settles it as before. + /// + [Test] + public async Task LambdaCallingOnlyAnInapplicablePublicExtension_IsNotSkipped() + { + TransformWorkerClientResult result = await RunEditedFixtureAsync( + "HotReloadSameNameExtensionCaller", + "() => 20", + "() => 50L.AddDouble(1)"); + + Assert.That(FindSkipReason(result, "LambdaValue("), Is.Null, FormatSkipped(result.Output.skipped)); + Assert.That(HasEntry(result, "LambdaValue"), Is.True, "LambdaValue must be an entry."); + } + + private static async Task RunEditedFixtureAsync(string typeName, string fragment, string replacement) + { + string fileName = typeName + ".cs"; + string fixturePath = Path.GetFullPath(Path.Combine(Application.dataPath, "Tests", "Editor", "HotReload", fileName)); + string onDisk = File.ReadAllText(fixturePath); + int first = onDisk.IndexOf(fragment, StringComparison.Ordinal); + Assert.That(first, Is.GreaterThanOrEqualTo(0), "Precondition: the fragment must be in the fixture."); + Assert.That( + onDisk.IndexOf(fragment, first + fragment.Length, StringComparison.Ordinal), + Is.EqualTo(-1), + "Precondition: the fragment must occur once in the fixture."); + string editedPath = HotReloadTestSourceWriter.WriteEditedSource( + "InapplicableExtension" + typeName + ".cs", + onDisk.Replace(fragment, replacement, StringComparison.Ordinal)); + TransformWorkerInputDto input = TransformWorkerClientTests.BuildInputForSource( + editedPath, + FixtureDirectory + fileName, + snapshotSource: onDisk); + TransformWorkerClientResult result = + await HotReloadCompositionRoot.Services.TransformWorkerClient.RunAsync(input, CancellationToken.None); + Assert.That(result.Success, Is.True, result.ErrorMessage); + return result; + } + + private static bool HasEntry(TransformWorkerClientResult result, string methodName) + { + foreach (TransformWorkerEntryDto entry in result.Output.entries) + { + if (entry.methodName == methodName) + { + return true; + } + } + + return false; + } + + private static string FindSkipReason(TransformWorkerClientResult result, string methodNameFragment) + { + foreach (TransformWorkerSkippedDto skipped in result.Output.skipped) + { + if (skipped.method != null && skipped.method.Contains(methodNameFragment)) + { + return HotReloadWorkerReasonText.Render(skipped.reason); + } + } + + return null; + } + + private static string FormatSkipped(TransformWorkerSkippedDto[] skipped) + { + List lines = new List(); + foreach (TransformWorkerSkippedDto row in skipped) + { + lines.Add(row.method + " => " + HotReloadWorkerReasonText.Render(row.reason)); + } + + return "Skipped=[" + string.Join(" | ", lines) + "]"; + } + } +} diff --git a/Assets/Tests/Editor/HotReload/TransformWorkerInapplicableExtensionCallTests.cs.meta b/Assets/Tests/Editor/HotReload/TransformWorkerInapplicableExtensionCallTests.cs.meta new file mode 100644 index 000000000..8f5fbc5fa --- /dev/null +++ b/Assets/Tests/Editor/HotReload/TransformWorkerInapplicableExtensionCallTests.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 5cb8fc97b214f4b638d4a006062a25ba +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Packages/src/Editor/FirstPartyTools/HotReload/TransformWorker~/InapplicableCallName.cs b/Packages/src/Editor/FirstPartyTools/HotReload/TransformWorker~/InapplicableCallName.cs new file mode 100644 index 000000000..3676d5bc0 --- /dev/null +++ b/Packages/src/Editor/FirstPartyTools/HotReload/TransformWorker~/InapplicableCallName.cs @@ -0,0 +1,109 @@ +using System; +using System.Collections.Generic; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp.Syntax; + +/// +/// What: the called name of a call 'receiver.Name(...)' or 'receiver?.Name(...)' that the worker's +/// binding rejected because every method of that name it can see fails to take the call, while an +/// internal extension method declared in a file the run was not given may be the one the call means. +/// +/// +/// Why these errors: the worker's binding imports the target assembly through its public surface +/// only, so a same-named public extension method is all it can see. When that method takes another +/// receiver type the compiler reports CS1929 instead of CS1061, and when it takes the receiver with +/// other parameter types it reports CS1503. Neither error is located on the name: CS1929 marks the +/// receiver and CS1503 the argument, so the name is found from the node the error marks. +/// +internal static class InapplicableCallName +{ + private static readonly HashSet InapplicableCallDiagnosticIds = + new HashSet(StringComparer.Ordinal) { "CS1929", "CS1503" }; + + /// + /// What: whether reports a call whose name only binds to methods that + /// do not take it. + /// + internal static bool IsInapplicableCallDiagnostic(Diagnostic error) + { + return InapplicableCallDiagnosticIds.Contains(error.Id); + } + + /// + /// What: the called name of the call , an inapplicable-call error inside + /// , reports: the name after the receiver CS1929 marks, or of the call + /// whose argument CS1503 marks. Null when the marked node is not the receiver or an argument of + /// such a call, such as a call by bare name. + /// + internal static SimpleNameSyntax FindOrNull(Diagnostic error, SyntaxNode bodyNode) + { + Location location = error.Location; + if (!location.IsInSource + || location.SourceTree != bodyNode.SyntaxTree + || !bodyNode.Span.Contains(location.SourceSpan)) + { + return null; + } + + // Why every node with the marked span and not the innermost one: a receiver such as + // 'this._seed' shares its span with no inner node, while a literal argument shares it with + // the ArgumentSyntax around it, and only the right one of those has the call as its parent. + for (SyntaxNode node = bodyNode.FindNode(location.SourceSpan, getInnermostNodeForTie: true); + node != null && node.Span == location.SourceSpan; + node = node.Parent) + { + SimpleNameSyntax name = error.Id == "CS1929" ? NameAfterReceiverOrNull(node) : NameOfCallWithArgumentOrNull(node); + if (name != null) + { + return name; + } + } + + return null; + } + + // 'receiver.Name(...)' or 'receiver?.Name(...)', where 'node' is the receiver. + // Why through parentheses: the compiler marks a parenthesized receiver without them, so + // '((int?)50)?.Name(...)' marks '(int?)50'. + private static SimpleNameSyntax NameAfterReceiverOrNull(SyntaxNode marked) + { + SyntaxNode node = marked; + while (node.Parent is ParenthesizedExpressionSyntax parenthesized) + { + node = parenthesized; + } + + if (node.Parent is MemberAccessExpressionSyntax access + && access.Expression == node + && access.Parent is InvocationExpressionSyntax invocation + && invocation.Expression == access) + { + return access.Name; + } + + return node.Parent is ConditionalAccessExpressionSyntax conditional + && conditional.Expression == node + && conditional.WhenNotNull is InvocationExpressionSyntax { Expression: MemberBindingExpressionSyntax binding } + ? binding.Name + : null; + } + + // 'receiver.Name(..., node, ...)' or 'receiver?.Name(..., node, ...)', where 'node' is an argument. + private static SimpleNameSyntax NameOfCallWithArgumentOrNull(SyntaxNode node) + { + if (node is not ArgumentSyntax { Parent: ArgumentListSyntax { Parent: InvocationExpressionSyntax invocation } }) + { + return null; + } + + switch (invocation.Expression) + { + case MemberAccessExpressionSyntax access: + return access.Name; + case MemberBindingExpressionSyntax binding: + return binding.Name; + default: + return null; + } + } +} diff --git a/Packages/src/Editor/FirstPartyTools/HotReload/TransformWorker~/UnpassedInternalMemberUse.cs b/Packages/src/Editor/FirstPartyTools/HotReload/TransformWorker~/UnpassedInternalMemberUse.cs index 62b3cc907..625ca2693 100644 --- a/Packages/src/Editor/FirstPartyTools/HotReload/TransformWorker~/UnpassedInternalMemberUse.cs +++ b/Packages/src/Editor/FirstPartyTools/HotReload/TransformWorker~/UnpassedInternalMemberUse.cs @@ -100,27 +100,27 @@ internal static UnpassedInternalMemberUse FindOrNull( Debug.Assert(decision != null, "decision must not be null."); Debug.Assert(enclosingType != null, "enclosingType must not be null."); - if (targetAssembly == null || !MemberNotFoundDiagnosticIds.Contains(error.Id)) + bool isInapplicableCall = InapplicableCallName.IsInapplicableCallDiagnostic(error); + if (targetAssembly == null || (!isInapplicableCall && !MemberNotFoundDiagnosticIds.Contains(error.Id))) { return null; } - SimpleNameSyntax name = FindReportedNameOrNull(error, bodyNode); + SimpleNameSyntax name = isInapplicableCall + ? InapplicableCallName.FindOrNull(error, bodyNode) + : FindReportedNameOrNull(error, bodyNode); if (name == null) { return null; } + // Why an inapplicable call skips the receiver's own members: such a call is looked up only + // as an internal extension, which is used only to refuse a use outside the patched method, + // so the error never lets a body through that was not let through before. bool hasReceiver = HasReceiver(name); - INamedTypeSymbol start = hasReceiver ? FindReceiverTypeOrNull(name, semanticModel) : enclosingType; - ISymbol member = start == null + ISymbol member = isInapplicableCall ? null - : FindInternalMemberOfUnpassedTypeOrNull( - start, - name.Identifier.ValueText, - outParameterCount: null, - semanticModel, - targetAssembly); + : FindInternalMemberOrNull(name, hasReceiver, enclosingType, semanticModel, targetAssembly); // Why the extensions after the receiver's own members: 'value.Name(...)' calls an extension // only when the receiver's type has no member of that name, and an internal extension @@ -252,6 +252,26 @@ private static UnpassedInternalMemberUseForm ChooseForm(UseRunPlace runPlace, bo : UnpassedInternalMemberUseForm.OutOfReach; } + // The internal member of a compiled type the run does not declare that 'name' names: looked up + // on the receiver's type, or on the enclosing type for a bare name. + private static ISymbol FindInternalMemberOrNull( + SimpleNameSyntax name, + bool hasReceiver, + INamedTypeSymbol enclosingType, + SemanticModel semanticModel, + IAssemblySymbol targetAssembly) + { + INamedTypeSymbol start = hasReceiver ? FindReceiverTypeOrNull(name, semanticModel) : enclosingType; + return start == null + ? null + : FindInternalMemberOfUnpassedTypeOrNull( + start, + name.Identifier.ValueText, + outParameterCount: null, + semanticModel, + targetAssembly); + } + private static SimpleNameSyntax FindReportedNameOrNull(Diagnostic error, SyntaxNode bodyNode) { Location location = error.Location; diff --git a/Packages/src/Editor/FirstPartyTools/HotReload/TransformWorker~/UnresolvedBodyNameGuard.cs b/Packages/src/Editor/FirstPartyTools/HotReload/TransformWorker~/UnresolvedBodyNameGuard.cs index 6596548d8..b853d53b6 100644 --- a/Packages/src/Editor/FirstPartyTools/HotReload/TransformWorker~/UnresolvedBodyNameGuard.cs +++ b/Packages/src/Editor/FirstPartyTools/HotReload/TransformWorker~/UnresolvedBodyNameGuard.cs @@ -59,16 +59,19 @@ internal static WorkerReason DescribeSkipOrNull( // Why before the name check: a call the compiler generates has no name in the source, // and the error its missing method raises varies with what else is in scope. - UnpassedInternalMemberUse implicitCall = UnpassedImplicitCallLookup.FindUseOrNull( - diagnostic, - semanticModel, - bodyNode, - methodDeclarationOrNull, - decision, - targetAssembly); - if (implicitCall != null && !IsWithinReach(implicitCall, isPartial)) + WorkerReason implicitCallSkip = DescribeOutOfReachOrNull( + UnpassedImplicitCallLookup.FindUseOrNull( + diagnostic, + semanticModel, + bodyNode, + methodDeclarationOrNull, + decision, + targetAssembly), + isPartial, + diagnosticText); + if (implicitCallSkip != null) { - return Describe(implicitCall, isPartial, diagnosticText); + return implicitCallSkip; } // Why apart from the missing-name IDs: a missing accessor is either an internal accessor @@ -76,16 +79,44 @@ internal static WorkerReason DescribeSkipOrNull( // part the worker cannot see. if (UnpassedInternalAccessorLookup.IsMissingAccessorDiagnostic(diagnostic)) { - UnpassedInternalMemberUse accessorCall = UnpassedInternalAccessorLookup.FindOrNull( - diagnostic, - semanticModel, - bodyNode, - methodDeclarationOrNull, - decision, - targetAssembly); - if (accessorCall != null && !IsWithinReach(accessorCall, isPartial)) + WorkerReason accessorCallSkip = DescribeOutOfReachOrNull( + UnpassedInternalAccessorLookup.FindOrNull( + diagnostic, + semanticModel, + bodyNode, + methodDeclarationOrNull, + decision, + targetAssembly), + isPartial, + diagnosticText); + if (accessorCallSkip != null) { - return Describe(accessorCall, isPartial, diagnosticText); + return accessorCallSkip; + } + + continue; + } + + // Why apart from the missing-name IDs: a same-named public extension method turns the + // missing internal extension into an inapplicable call, which on a partial type is still + // not a part the worker cannot see, so one with no internal extension behind it goes on + // to the shim compile as before. + if (InapplicableCallName.IsInapplicableCallDiagnostic(diagnostic)) + { + WorkerReason inapplicableCallSkip = DescribeOutOfReachOrNull( + UnpassedInternalMemberUse.FindOrNull( + diagnostic, + semanticModel, + bodyNode, + methodDeclarationOrNull, + decision, + typeSymbol, + targetAssembly), + isPartial, + diagnosticText); + if (inapplicableCallSkip != null) + { + return inapplicableCallSkip; } continue; @@ -144,6 +175,15 @@ internal static WorkerReason DescribeSkipOrNull( return null; } + // The skip reason for 'useOrNull' when there is such a use and the patched method cannot reach + // it; null otherwise. + private static WorkerReason DescribeOutOfReachOrNull(UnpassedInternalMemberUse useOrNull, bool isPartial, string diagnosticText) + { + return useOrNull != null && !IsWithinReach(useOrNull, isPartial) + ? Describe(useOrNull, isPartial, diagnosticText) + : null; + } + private static WorkerReason Describe(UnpassedInternalMemberUse use, bool isPartial, string diagnosticText) { return WorkerReason.Of( From 26356dfc5e70e432348e79f7a12b75ff36615ebb Mon Sep 17 00:00:00 2001 From: hatayama Date: Sat, 28 Nov 2026 18:25:14 +0900 Subject: [PATCH 2/3] fix: find the called name of an inapplicable call after a chained ?. call or with a named argument Review follow-up for the CS1929 / CS1503 handling: - A chained call after `?.` (`((int?)50)?.AddDouble(1).CompareTo(0)`) has an outer invocation whose callee is a member access, so the direct member-binding match missed it. Walk the WhenNotNull spine to its leftmost member binding and still require that binding to be called. - For a named argument (`50.AddTriple(add: 1)`) CS1503 marks only the argument's expression, whose span differs from the ArgumentSyntax, so the span walk never reached the argument. Accept the expression of an argument as well. Both forms reported Patched and then threw MethodAccessException; they now skip. The E2E test's CallAsync is split per fixture kind to stay under the complexity limit. --- .../HotReloadSameNameExtensionCallE2ETests.cs | 102 ++++++++++-------- .../HotReloadSameNameExtensionCaller.cs | 14 +++ ...HotReloadSameNameExtensionPartialCaller.cs | 14 +++ .../HotReloadSameNamePublicExtensionMath.cs | 6 +- .../TransformWorker~/InapplicableCallName.cs | 41 +++++-- 5 files changed, 125 insertions(+), 52 deletions(-) diff --git a/Assets/Tests/Editor/HotReload/HotReloadSameNameExtensionCallE2ETests.cs b/Assets/Tests/Editor/HotReload/HotReloadSameNameExtensionCallE2ETests.cs index f1a7a5098..25ecd2f51 100644 --- a/Assets/Tests/Editor/HotReload/HotReloadSameNameExtensionCallE2ETests.cs +++ b/Assets/Tests/Editor/HotReload/HotReloadSameNameExtensionCallE2ETests.cs @@ -47,14 +47,17 @@ public void TearDown() } // Calls the shim assembly compiles as code of its own: in a lambda, through conditional - // access, on a receiver that is itself a member access, beside a same-named public extension - // that takes an int with another argument type, in an async body and in an iterator body. + // access (also followed by another call), on a receiver that is itself a member access, + // beside a same-named public extension that takes an int with another argument type (also + // with a named argument), in an async body and in an iterator body. private static IEnumerable CallsInShimCompiledBodies() { yield return new TestCaseData("LambdaValue", "() => 20", "() => 50.AddDouble(1)", 20, 101); yield return new TestCaseData("ConditionalAccessLambdaValue", "() => 30", "() => ((int?)50)?.AddDouble(1) ?? 0", 30, 101); yield return new TestCaseData("MemberAccessReceiverLambdaValue", "() => this._seed + 10", "() => this._seed.AddDouble(1)", 60, 101); yield return new TestCaseData("IntOverloadLambdaValue", "() => 70", "() => 50.AddTriple(1)", 70, 151); + yield return new TestCaseData("ChainedConditionalAccessLambdaValue", "() => 80", "() => ((int?)50)?.AddDouble(1).CompareTo(0) ?? 0", 80, 1); + yield return new TestCaseData("NamedArgumentLambdaValue", "() => 90", "() => 50.AddTriple(add: 1)", 90, 151); yield return new TestCaseData("AsyncValue", "return 40;", "return 50.AddDouble(1);", 40, 101); yield return new TestCaseData("IteratorValues", "yield return 50;", "yield return 50.AddDouble(1);", 50, 101); } @@ -153,52 +156,65 @@ private static async Task RunEditAsync( // Why async: the async fixture method is awaited rather than waited on, because an EditMode // test must not block the main thread on a task. - private static async Task CallAsync(FixtureKind fixture, string methodName) + private static Task CallAsync(FixtureKind fixture, string methodName) { - if (fixture == FixtureKind.Plain) + return fixture == FixtureKind.Plain ? CallPlainAsync(methodName) : CallPartialAsync(methodName); + } + + private static async Task CallPlainAsync(string methodName) + { + HotReloadSameNameExtensionCaller caller = new HotReloadSameNameExtensionCaller(); + switch (methodName) { - HotReloadSameNameExtensionCaller plain = new HotReloadSameNameExtensionCaller(); - switch (methodName) - { - case OwnStatementsValue: - return plain.OwnStatementsValue(); - case "LambdaValue": - return plain.LambdaValue(); - case "ConditionalAccessLambdaValue": - return plain.ConditionalAccessLambdaValue(); - case "MemberAccessReceiverLambdaValue": - return plain.MemberAccessReceiverLambdaValue(); - case "IntOverloadLambdaValue": - return plain.IntOverloadLambdaValue(); - case "AsyncValue": - return await plain.AsyncValue(); - case "IteratorValues": - return First(plain.IteratorValues()); - } + case OwnStatementsValue: + return caller.OwnStatementsValue(); + case "LambdaValue": + return caller.LambdaValue(); + case "ConditionalAccessLambdaValue": + return caller.ConditionalAccessLambdaValue(); + case "ChainedConditionalAccessLambdaValue": + return caller.ChainedConditionalAccessLambdaValue(); + case "MemberAccessReceiverLambdaValue": + return caller.MemberAccessReceiverLambdaValue(); + case "IntOverloadLambdaValue": + return caller.IntOverloadLambdaValue(); + case "NamedArgumentLambdaValue": + return caller.NamedArgumentLambdaValue(); + case "AsyncValue": + return await caller.AsyncValue(); + case "IteratorValues": + return First(caller.IteratorValues()); + default: + throw new ArgumentException("Unknown caller method: " + methodName); } - else + } + + private static async Task CallPartialAsync(string methodName) + { + HotReloadSameNameExtensionPartialCaller caller = new HotReloadSameNameExtensionPartialCaller(); + switch (methodName) { - HotReloadSameNameExtensionPartialCaller partial = new HotReloadSameNameExtensionPartialCaller(); - switch (methodName) - { - case OwnStatementsValue: - return partial.OwnStatementsValue(); - case "LambdaValue": - return partial.LambdaValue(); - case "ConditionalAccessLambdaValue": - return partial.ConditionalAccessLambdaValue(); - case "MemberAccessReceiverLambdaValue": - return partial.MemberAccessReceiverLambdaValue(); - case "IntOverloadLambdaValue": - return partial.IntOverloadLambdaValue(); - case "AsyncValue": - return await partial.AsyncValue(); - case "IteratorValues": - return First(partial.IteratorValues()); - } + case OwnStatementsValue: + return caller.OwnStatementsValue(); + case "LambdaValue": + return caller.LambdaValue(); + case "ConditionalAccessLambdaValue": + return caller.ConditionalAccessLambdaValue(); + case "ChainedConditionalAccessLambdaValue": + return caller.ChainedConditionalAccessLambdaValue(); + case "MemberAccessReceiverLambdaValue": + return caller.MemberAccessReceiverLambdaValue(); + case "IntOverloadLambdaValue": + return caller.IntOverloadLambdaValue(); + case "NamedArgumentLambdaValue": + return caller.NamedArgumentLambdaValue(); + case "AsyncValue": + return await caller.AsyncValue(); + case "IteratorValues": + return First(caller.IteratorValues()); + default: + throw new ArgumentException("Unknown caller method: " + methodName); } - - throw new ArgumentException("Unknown caller method: " + methodName); } private static int First(IEnumerable values) diff --git a/Assets/Tests/Editor/HotReload/HotReloadSameNameExtensionCaller.cs b/Assets/Tests/Editor/HotReload/HotReloadSameNameExtensionCaller.cs index 7dc01680c..3046ae955 100644 --- a/Assets/Tests/Editor/HotReload/HotReloadSameNameExtensionCaller.cs +++ b/Assets/Tests/Editor/HotReload/HotReloadSameNameExtensionCaller.cs @@ -47,6 +47,20 @@ public int IntOverloadLambdaValue() return read(); } + [MethodImpl(MethodImplOptions.NoInlining)] + public int ChainedConditionalAccessLambdaValue() + { + Func read = () => 80; + return read(); + } + + [MethodImpl(MethodImplOptions.NoInlining)] + public int NamedArgumentLambdaValue() + { + Func read = () => 90; + return read(); + } + [MethodImpl(MethodImplOptions.NoInlining)] public async Task AsyncValue() { diff --git a/Assets/Tests/Editor/HotReload/HotReloadSameNameExtensionPartialCaller.cs b/Assets/Tests/Editor/HotReload/HotReloadSameNameExtensionPartialCaller.cs index c3614be38..86f0566f6 100644 --- a/Assets/Tests/Editor/HotReload/HotReloadSameNameExtensionPartialCaller.cs +++ b/Assets/Tests/Editor/HotReload/HotReloadSameNameExtensionPartialCaller.cs @@ -46,6 +46,20 @@ public int IntOverloadLambdaValue() return read(); } + [MethodImpl(MethodImplOptions.NoInlining)] + public int ChainedConditionalAccessLambdaValue() + { + Func read = () => 80; + return read(); + } + + [MethodImpl(MethodImplOptions.NoInlining)] + public int NamedArgumentLambdaValue() + { + Func read = () => 90; + return read(); + } + [MethodImpl(MethodImplOptions.NoInlining)] public async Task AsyncValue() { diff --git a/Assets/Tests/Editor/HotReload/HotReloadSameNamePublicExtensionMath.cs b/Assets/Tests/Editor/HotReload/HotReloadSameNamePublicExtensionMath.cs index 2715312ea..c17cb6fea 100644 --- a/Assets/Tests/Editor/HotReload/HotReloadSameNamePublicExtensionMath.cs +++ b/Assets/Tests/Editor/HotReload/HotReloadSameNamePublicExtensionMath.cs @@ -12,9 +12,11 @@ public static int AddDouble(this string value, object other) return value.Length; } - public static int AddTriple(this int value, string other) + // Why the parameter is named like the internal one's: a named argument then fails only on + // its type, as a positional one does. + public static int AddTriple(this int value, string add) { - return value + other.Length; + return value + add.Length; } } } diff --git a/Packages/src/Editor/FirstPartyTools/HotReload/TransformWorker~/InapplicableCallName.cs b/Packages/src/Editor/FirstPartyTools/HotReload/TransformWorker~/InapplicableCallName.cs index 3676d5bc0..06667b8b8 100644 --- a/Packages/src/Editor/FirstPartyTools/HotReload/TransformWorker~/InapplicableCallName.cs +++ b/Packages/src/Editor/FirstPartyTools/HotReload/TransformWorker~/InapplicableCallName.cs @@ -81,17 +81,44 @@ private static SimpleNameSyntax NameAfterReceiverOrNull(SyntaxNode marked) return access.Name; } - return node.Parent is ConditionalAccessExpressionSyntax conditional - && conditional.Expression == node - && conditional.WhenNotNull is InvocationExpressionSyntax { Expression: MemberBindingExpressionSyntax binding } - ? binding.Name - : null; + return node.Parent is ConditionalAccessExpressionSyntax conditional && conditional.Expression == node + ? CalledBindingNameOrNull(conditional.WhenNotNull) + : null; } - // 'receiver.Name(..., node, ...)' or 'receiver?.Name(..., node, ...)', where 'node' is an argument. + // The name of the call that '?.' starts, the leftmost member binding of 'whenNotNull', which may + // be followed by more calls or member accesses ('?.Name(...).Other()'); null when that binding is + // not called. + private static SimpleNameSyntax CalledBindingNameOrNull(ExpressionSyntax whenNotNull) + { + ExpressionSyntax current = whenNotNull; + while (true) + { + switch (current) + { + case MemberBindingExpressionSyntax binding: + return binding.Parent is InvocationExpressionSyntax call && call.Expression == binding + ? binding.Name + : null; + case InvocationExpressionSyntax invocation: + current = invocation.Expression; + break; + case MemberAccessExpressionSyntax access: + current = access.Expression; + break; + default: + return null; + } + } + } + + // 'receiver.Name(..., node, ...)' or 'receiver?.Name(..., node, ...)', where 'node' is an argument + // or the expression of one. Why the expression too: for a named argument 'add: 1' the compiler + // marks only '1', whose span is not the argument's. private static SimpleNameSyntax NameOfCallWithArgumentOrNull(SyntaxNode node) { - if (node is not ArgumentSyntax { Parent: ArgumentListSyntax { Parent: InvocationExpressionSyntax invocation } }) + SyntaxNode argument = node.Parent is ArgumentSyntax parent && parent.Expression == node ? parent : node; + if (argument is not ArgumentSyntax { Parent: ArgumentListSyntax { Parent: InvocationExpressionSyntax invocation } }) { return null; } From d6db0c6f58f58310d650becc93b4510dd65e3bbe Mon Sep 17 00:00:00 2001 From: hatayama Date: Sat, 28 Nov 2026 18:48:16 +0900 Subject: [PATCH 3/3] fix: refuse internal extension calls that a same-named public extension turns into CS1501 or CS7036 Review follow-up for #3628: - CS1501 (the public extension takes fewer arguments) and CS7036 (it takes more) join CS1929 / CS1503 under the same refuse-only rule. Both mark the called name, or its '.Name' binding after '?.'. - The conditional-access spine walk also passes element accesses, so '?.Name(...).ToString()[0]' finds the call. - The refuse path explains why a same-named instance method of the receiver does not stop the refusal: with no applicable instance method the compiler goes on to the extension methods, so the internal extension is the call. A CS1503 from a source/compiled type split next to such an extension is skipped too and keeps its compiled behavior. Tests: E2E rows for CS1501, CS7036, CS1501 after '?.', a property and an element access after a '?.' call; a test that the instance-method case is skipped with a reason naming the internal class; a worker test that a partial type's CS1929 with no internal extension behind it stays an entry. --- .../HotReloadSameNameExtensionCallE2ETests.cs | 33 ++++++++++- .../HotReloadSameNameInternalExtensionMath.cs | 23 +++++++- .../HotReloadSameNamePublicExtensionMath.cs | 26 ++++++++- .../TransformWorkerPartialTypeTests.cs | 22 +++++++ .../TransformWorker~/InapplicableCallName.cs | 58 ++++++++++++++++--- .../UnpassedInternalMemberUse.cs | 7 ++- 6 files changed, 152 insertions(+), 17 deletions(-) diff --git a/Assets/Tests/Editor/HotReload/HotReloadSameNameExtensionCallE2ETests.cs b/Assets/Tests/Editor/HotReload/HotReloadSameNameExtensionCallE2ETests.cs index 25ecd2f51..3341ea06b 100644 --- a/Assets/Tests/Editor/HotReload/HotReloadSameNameExtensionCallE2ETests.cs +++ b/Assets/Tests/Editor/HotReload/HotReloadSameNameExtensionCallE2ETests.cs @@ -47,9 +47,10 @@ public void TearDown() } // Calls the shim assembly compiles as code of its own: in a lambda, through conditional - // access (also followed by another call), on a receiver that is itself a member access, - // beside a same-named public extension that takes an int with another argument type (also - // with a named argument), in an async body and in an iterator body. + // access (also followed by a call, a property or an element access), on a receiver that is + // itself a member access, beside a same-named public extension that takes an int with another + // argument type (also with a named argument), fewer parameters (CS1501, also after '?.') or + // more parameters (CS7036), in an async body and in an iterator body. private static IEnumerable CallsInShimCompiledBodies() { yield return new TestCaseData("LambdaValue", "() => 20", "() => 50.AddDouble(1)", 20, 101); @@ -58,6 +59,11 @@ private static IEnumerable CallsInShimCompiledBodies() yield return new TestCaseData("IntOverloadLambdaValue", "() => 70", "() => 50.AddTriple(1)", 70, 151); yield return new TestCaseData("ChainedConditionalAccessLambdaValue", "() => 80", "() => ((int?)50)?.AddDouble(1).CompareTo(0) ?? 0", 80, 1); yield return new TestCaseData("NamedArgumentLambdaValue", "() => 90", "() => 50.AddTriple(add: 1)", 90, 151); + yield return new TestCaseData("ConditionalAccessLambdaValue", "() => 30", "() => ((int?)50)?.AddDouble(1).ToString().Length ?? 0", 30, 3); + yield return new TestCaseData("ConditionalAccessLambdaValue", "() => 30", "() => ((int?)50)?.AddDouble(1).ToString()[0] ?? 0", 30, (int)'1'); + yield return new TestCaseData("LambdaValue", "() => 20", "() => 50.AddQuadruple(1)", 20, 201); + yield return new TestCaseData("ConditionalAccessLambdaValue", "() => 30", "() => ((int?)50)?.AddQuadruple(1) ?? 0", 30, 201); + yield return new TestCaseData("LambdaValue", "() => 20", "() => 50.AddQuintuple(1)", 20, 251); yield return new TestCaseData("AsyncValue", "return 40;", "return 50.AddDouble(1);", 40, 101); yield return new TestCaseData("IteratorValues", "yield return 50;", "yield return 50.AddDouble(1);", 50, 101); } @@ -137,6 +143,27 @@ public async Task Run_PartialCallInShimCompiledBodyBesideSameNamePublicExtension Assert.That(await CallAsync(FixtureKind.Partial, methodName), Is.EqualTo(compiledValue), FormatOutcomes(result)); } + /// + /// What: a lambda calling the internal extension method is skipped with a reason that names + /// the internal class, and the method keeps the compiled value. This holds beside a same-named + /// public extension method, and beside a public instance method of the receiver that does not + /// take the call, because the compiler then goes on to the extension methods. + /// + [TestCase(FixtureKind.Plain, "() => 50.AddDouble(1)")] + [TestCase(FixtureKind.Plain, "() => new HotReloadSameNameInstanceTarget().Measure(1)")] + [TestCase(FixtureKind.Partial, "() => new HotReloadSameNameInstanceTarget().Measure(1)")] + public async Task Run_LambdaCallingInternalExtensionBesideSameNamedPublicMethod_IsSkippedNamingTheInternalClass( + FixtureKind fixture, + string replacement) + { + HotReloadOrchestratorResult result = await RunEditAsync(fixture, "LambdaValue", "() => 20", replacement); + + HotReloadMethodOutcome row = FindRow(result, fixture, "LambdaValue"); + Assert.That(row.Kind, Is.EqualTo(HotReloadMethodOutcomeKind.Skipped), FormatOutcomes(result)); + Assert.That(row.Reason, Does.Contain("is internal to 'HotReloadSameNameInternalExtensionMath'"), FormatOutcomes(result)); + Assert.That(await CallAsync(fixture, "LambdaValue"), Is.EqualTo(20), FormatOutcomes(result)); + } + private static async Task RunEditAsync( FixtureKind fixture, string methodName, diff --git a/Assets/Tests/Editor/HotReload/HotReloadSameNameInternalExtensionMath.cs b/Assets/Tests/Editor/HotReload/HotReloadSameNameInternalExtensionMath.cs index fc91a676c..b84c2b0da 100644 --- a/Assets/Tests/Editor/HotReload/HotReloadSameNameInternalExtensionMath.cs +++ b/Assets/Tests/Editor/HotReload/HotReloadSameNameInternalExtensionMath.cs @@ -1,11 +1,13 @@ namespace io.github.hatayama.UnityCliLoop.Tests.Editor.HotReload { /// - /// Internal extension method whose name a public extension method of another class shares. + /// Internal extension methods whose names a public extension method of another class, or a public + /// instance method of the receiver's type, shares. /// /// - /// Why a name of its own: a public extension method named like an existing fixture method would - /// change the outcome of every other test that calls that method. + /// Why names of their own: a public extension method named like an existing fixture method would + /// change the outcome of every other test that calls that method, and one name per public + /// counterpart keeps each compiler error the tests rely on apart. /// internal static class HotReloadSameNameInternalExtensionMath { @@ -18,5 +20,20 @@ internal static int AddTriple(this int value, int add) { return value * 3 + add; } + + internal static int AddQuadruple(this int value, int add) + { + return value * 4 + add; + } + + internal static int AddQuintuple(this int value, int add) + { + return value * 5 + add; + } + + internal static int Measure(this object value, int add) + { + return add + 1000; + } } } diff --git a/Assets/Tests/Editor/HotReload/HotReloadSameNamePublicExtensionMath.cs b/Assets/Tests/Editor/HotReload/HotReloadSameNamePublicExtensionMath.cs index c17cb6fea..f2138d065 100644 --- a/Assets/Tests/Editor/HotReload/HotReloadSameNamePublicExtensionMath.cs +++ b/Assets/Tests/Editor/HotReload/HotReloadSameNamePublicExtensionMath.cs @@ -2,8 +2,8 @@ namespace io.github.hatayama.UnityCliLoop.Tests.Editor.HotReload { /// /// Public extension methods that share their names with internal ones of another class and never - /// apply to the calls the tests make: one takes another receiver type, one takes an int - /// receiver with another argument type. + /// apply to the calls the tests make: one takes another receiver type, the others take an + /// int receiver with another argument type, fewer parameters or more parameters. /// public static class HotReloadSameNamePublicExtensionMath { @@ -18,5 +18,27 @@ public static int AddTriple(this int value, string add) { return value + add.Length; } + + public static int AddQuadruple(this int value) + { + return value; + } + + public static int AddQuintuple(this int value, int add, int extra) + { + return value + add + extra; + } + } + + /// + /// Public type whose public instance method shares its name with an internal extension method + /// of another class and does not take an int argument. + /// + public class HotReloadSameNameInstanceTarget + { + public int Measure(string text) + { + return text.Length; + } } } diff --git a/Assets/Tests/Editor/HotReload/TransformWorkerPartialTypeTests.cs b/Assets/Tests/Editor/HotReload/TransformWorkerPartialTypeTests.cs index daa3ef2f4..bbc95123c 100644 --- a/Assets/Tests/Editor/HotReload/TransformWorkerPartialTypeTests.cs +++ b/Assets/Tests/Editor/HotReload/TransformWorkerPartialTypeTests.cs @@ -1447,6 +1447,28 @@ public async Task Skip_PartialTypeBodyUsingPrivateMemberOfUnpassedType_KeepsTheM Assert.That(AssertSkipped(result, "OwnOnly"), Does.Contain("generated at compile time"), FormatSkipped(result)); } + /// + /// What: a lambda in a partial type calling a same-named public extension method that does not + /// take its receiver (CS1929), with no internal extension method behind the call, is not + /// skipped and stays an entry, as before: the error is not a part the worker cannot see. + /// + [Test] + public async Task Run_PartialTypeLambdaCallingOnlyAnInapplicablePublicExtension_IsNotSkipped() + { + TransformWorkerClientResult result = await RunWorkerOnSourcesAsync(new[] + { + BuildEditedFixtureSource( + "HotReloadSameNameExtensionPartialCaller.cs", + "InapplicablePublicExtensionOnly.cs", + "() => 20", + "() => 50L.AddDouble(1)") + }); + + Assert.That(result.Success, Is.True, result.ErrorMessage); + Assert.That(FindSkipReason(result, "LambdaValue("), Is.Null, FormatSkipped(result)); + Assert.That(FindEntry(result, "LambdaValue"), Is.Not.Null, "LambdaValue must be an entry."); + } + /// /// What: a body of a partial type that uses an internal member of a type in another assembly /// keeps the missing-name reason. diff --git a/Packages/src/Editor/FirstPartyTools/HotReload/TransformWorker~/InapplicableCallName.cs b/Packages/src/Editor/FirstPartyTools/HotReload/TransformWorker~/InapplicableCallName.cs index 06667b8b8..151790d8b 100644 --- a/Packages/src/Editor/FirstPartyTools/HotReload/TransformWorker~/InapplicableCallName.cs +++ b/Packages/src/Editor/FirstPartyTools/HotReload/TransformWorker~/InapplicableCallName.cs @@ -11,14 +11,15 @@ /// /// Why these errors: the worker's binding imports the target assembly through its public surface /// only, so a same-named public extension method is all it can see. When that method takes another -/// receiver type the compiler reports CS1929 instead of CS1061, and when it takes the receiver with -/// other parameter types it reports CS1503. Neither error is located on the name: CS1929 marks the -/// receiver and CS1503 the argument, so the name is found from the node the error marks. +/// receiver type the compiler reports CS1929 instead of CS1061; when it takes the receiver with other +/// parameter types, CS1503; with fewer parameters, CS1501; with more, CS7036. Only the last two are +/// located on the name: CS1929 marks the receiver and CS1503 the argument, so the name is found from +/// the node the error marks. /// internal static class InapplicableCallName { private static readonly HashSet InapplicableCallDiagnosticIds = - new HashSet(StringComparer.Ordinal) { "CS1929", "CS1503" }; + new HashSet(StringComparer.Ordinal) { "CS1929", "CS1503", "CS1501", "CS7036" }; /// /// What: whether reports a call whose name only binds to methods that @@ -31,9 +32,9 @@ internal static bool IsInapplicableCallDiagnostic(Diagnostic error) /// /// What: the called name of the call , an inapplicable-call error inside - /// , reports: the name after the receiver CS1929 marks, or of the call - /// whose argument CS1503 marks. Null when the marked node is not the receiver or an argument of - /// such a call, such as a call by bare name. + /// , reports: the name after the receiver CS1929 marks, of the call + /// whose argument CS1503 marks, or the called name CS1501 and CS7036 mark. Null when the marked + /// node is not the receiver, an argument or the name of such a call, such as a call by bare name. /// internal static SimpleNameSyntax FindOrNull(Diagnostic error, SyntaxNode bodyNode) { @@ -52,7 +53,7 @@ internal static SimpleNameSyntax FindOrNull(Diagnostic error, SyntaxNode bodyNod node != null && node.Span == location.SourceSpan; node = node.Parent) { - SimpleNameSyntax name = error.Id == "CS1929" ? NameAfterReceiverOrNull(node) : NameOfCallWithArgumentOrNull(node); + SimpleNameSyntax name = NameForMarkedNodeOrNull(error.Id, node); if (name != null) { return name; @@ -62,6 +63,44 @@ internal static SimpleNameSyntax FindOrNull(Diagnostic error, SyntaxNode bodyNod return null; } + private static SimpleNameSyntax NameForMarkedNodeOrNull(string diagnosticId, SyntaxNode node) + { + switch (diagnosticId) + { + case "CS1929": + return NameAfterReceiverOrNull(node); + case "CS1503": + return NameOfCallWithArgumentOrNull(node); + default: + return CalledNameOrNull(node); + } + } + + // 'receiver.Name(...)' or 'receiver?.Name(...)', where 'node' is 'Name', or the '.Name' binding, + // which the compiler marks for a call after '?.'. + private static SimpleNameSyntax CalledNameOrNull(SyntaxNode node) + { + if (node is MemberBindingExpressionSyntax marked) + { + return marked.Parent is InvocationExpressionSyntax call && call.Expression == marked ? marked.Name : null; + } + + if (node is not SimpleNameSyntax name) + { + return null; + } + + switch (name.Parent) + { + case MemberAccessExpressionSyntax access when access.Name == name: + return access.Parent is InvocationExpressionSyntax invocation && invocation.Expression == access ? name : null; + case MemberBindingExpressionSyntax binding when binding.Name == name: + return CalledNameOrNull(binding); + default: + return null; + } + } + // 'receiver.Name(...)' or 'receiver?.Name(...)', where 'node' is the receiver. // Why through parentheses: the compiler marks a parenthesized receiver without them, so // '((int?)50)?.Name(...)' marks '(int?)50'. @@ -106,6 +145,9 @@ private static SimpleNameSyntax CalledBindingNameOrNull(ExpressionSyntax whenNot case MemberAccessExpressionSyntax access: current = access.Expression; break; + case ElementAccessExpressionSyntax elementAccess: + current = elementAccess.Expression; + break; default: return null; } diff --git a/Packages/src/Editor/FirstPartyTools/HotReload/TransformWorker~/UnpassedInternalMemberUse.cs b/Packages/src/Editor/FirstPartyTools/HotReload/TransformWorker~/UnpassedInternalMemberUse.cs index 625ca2693..a518b3f7b 100644 --- a/Packages/src/Editor/FirstPartyTools/HotReload/TransformWorker~/UnpassedInternalMemberUse.cs +++ b/Packages/src/Editor/FirstPartyTools/HotReload/TransformWorker~/UnpassedInternalMemberUse.cs @@ -116,7 +116,12 @@ internal static UnpassedInternalMemberUse FindOrNull( // Why an inapplicable call skips the receiver's own members: such a call is looked up only // as an internal extension, which is used only to refuse a use outside the patched method, - // so the error never lets a body through that was not let through before. + // so the error never lets a body through that was not let through before. Why a same-named + // instance method of the receiver does not stop the refusal: the compiler goes on to the + // extension methods when no instance method takes the call, so 'value.Name(1)' beside an + // instance 'Name(string)' calls the internal extension. The cost is a CS1503 that comes from + // a source and compiled copy of one type next to such an extension: it is skipped too, with + // this reason, and keeps its compiled behavior. bool hasReceiver = HasReceiver(name); ISymbol member = isInapplicableCall ? null