diff --git a/Assets/Tests/Editor/HotReload/HotReloadSameNameExtensionCallE2ETests.cs b/Assets/Tests/Editor/HotReload/HotReloadSameNameExtensionCallE2ETests.cs new file mode 100644 index 000000000..3341ea06b --- /dev/null +++ b/Assets/Tests/Editor/HotReload/HotReloadSameNameExtensionCallE2ETests.cs @@ -0,0 +1,310 @@ +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 (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); + 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("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); + } + + /// + /// 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)); + } + + /// + /// 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, + 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 Task CallAsync(FixtureKind fixture, string methodName) + { + return fixture == FixtureKind.Plain ? CallPlainAsync(methodName) : CallPartialAsync(methodName); + } + + private static async Task CallPlainAsync(string methodName) + { + HotReloadSameNameExtensionCaller caller = new HotReloadSameNameExtensionCaller(); + switch (methodName) + { + 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); + } + } + + private static async Task CallPartialAsync(string methodName) + { + HotReloadSameNameExtensionPartialCaller caller = new HotReloadSameNameExtensionPartialCaller(); + switch (methodName) + { + 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); + } + } + + 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..3046ae955 --- /dev/null +++ b/Assets/Tests/Editor/HotReload/HotReloadSameNameExtensionCaller.cs @@ -0,0 +1,77 @@ +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 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() + { + 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..86f0566f6 --- /dev/null +++ b/Assets/Tests/Editor/HotReload/HotReloadSameNameExtensionPartialCaller.cs @@ -0,0 +1,76 @@ +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 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() + { + 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..b84c2b0da --- /dev/null +++ b/Assets/Tests/Editor/HotReload/HotReloadSameNameInternalExtensionMath.cs @@ -0,0 +1,39 @@ +namespace io.github.hatayama.UnityCliLoop.Tests.Editor.HotReload +{ + /// + /// Internal extension methods whose names a public extension method of another class, or a public + /// instance method of the receiver's type, shares. + /// + /// + /// 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 + { + 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; + } + + 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/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..f2138d065 --- /dev/null +++ b/Assets/Tests/Editor/HotReload/HotReloadSameNamePublicExtensionMath.cs @@ -0,0 +1,44 @@ +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, the others take an + /// int receiver with another argument type, fewer parameters or more parameters. + /// + public static class HotReloadSameNamePublicExtensionMath + { + public static int AddDouble(this string value, object other) + { + return value.Length; + } + + // 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 + 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/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/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 new file mode 100644 index 000000000..151790d8b --- /dev/null +++ b/Packages/src/Editor/FirstPartyTools/HotReload/TransformWorker~/InapplicableCallName.cs @@ -0,0 +1,178 @@ +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; 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", "CS1501", "CS7036" }; + + /// + /// 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, 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) + { + 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 = NameForMarkedNodeOrNull(error.Id, node); + if (name != null) + { + return name; + } + } + + 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'. + 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 + ? CalledBindingNameOrNull(conditional.WhenNotNull) + : null; + } + + // 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; + case ElementAccessExpressionSyntax elementAccess: + current = elementAccess.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) + { + SyntaxNode argument = node.Parent is ArgumentSyntax parent && parent.Expression == node ? parent : node; + if (argument 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..a518b3f7b 100644 --- a/Packages/src/Editor/FirstPartyTools/HotReload/TransformWorker~/UnpassedInternalMemberUse.cs +++ b/Packages/src/Editor/FirstPartyTools/HotReload/TransformWorker~/UnpassedInternalMemberUse.cs @@ -100,27 +100,32 @@ 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. 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); - 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 +257,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(