diff --git a/Catglobe.CgScript.EditorSupport.Lsp.Tests/VariadicParameterTests.cs b/Catglobe.CgScript.EditorSupport.Lsp.Tests/VariadicParameterTests.cs new file mode 100644 index 00000000..508816c2 --- /dev/null +++ b/Catglobe.CgScript.EditorSupport.Lsp.Tests/VariadicParameterTests.cs @@ -0,0 +1,158 @@ +using Catglobe.CgScript.EditorSupport.Lsp.Handlers; +using Catglobe.CgScript.EditorSupport.Parsing; +using Microsoft.VisualStudio.LanguageServer.Protocol; + +namespace Catglobe.CgScript.EditorSupport.Lsp.Tests; + +public class VariadicParameterTests +{ + private sealed class TestDefinitions : CgScriptDefinitions + { + private static readonly MethodOverload Mixed = new( + "Accepts a typed prefix and arbitrary trailing values", + [new("count", "A count", "number"), new("label", "A label", "string"), new("", Type: "Params object")], + "Sample"); + + public TestDefinitions() : base( + new Dictionary + { + ["mixedFn"] = [Mixed], + ["variadicOnly"] = [new(Param: [new("", Type: "Params object")])], + ["fixedFn"] = [new(Param: [new("label", Type: "string")])], + }, + new Dictionary + { + ["Sample"] = new("", Constructors: [Mixed], + Methods: new() { ["Mix"] = [Mixed] }, + StaticMethods: new() { ["Create"] = [Mixed] }), + }, new Dictionary(), [], []) + { } + } + + [Theory] + [InlineData("1, \"label\"", true)] + [InlineData("1, \"label\", true", true)] + [InlineData("1, \"label\", true, 2, \"text\", {}", true)] + [InlineData("", false)] + [InlineData("1", false)] + [InlineData("\"wrong\", \"label\"", false)] + [InlineData("1, false", false)] + [InlineData("1, false, \"label\", 2", false)] + public void TypedPrefix_ValidatesFunctionsMethodsAndConstructors(string arguments, bool valid) + { + var source = $"mixedFn({arguments}); Sample s; s.Mix({arguments}); new Sample({arguments});"; + var parsed = CgScriptParseService.Parse(source); + Assert.Empty(parsed.Diagnostics); + + var diagnostics = SemanticAnalyzer.Analyze(parsed.Tree, new TestDefinitions()); + if (valid) + Assert.Empty(diagnostics); + else + { + Assert.Equal(3, diagnostics.Count); + Assert.Single(diagnostics, d => d.Code == "CGS022"); + Assert.Single(diagnostics, d => d.Code == "CGS023"); + Assert.Single(diagnostics, d => d.Code == "CGS024"); + } + } + + [Theory] + [InlineData("")] + [InlineData("1")] + [InlineData("1, true, \"text\", {}")] + public void VariadicOnly_AcceptsAnyArgumentCount(string arguments) + { + var parsed = CgScriptParseService.Parse($"variadicOnly({arguments});"); + Assert.Empty(parsed.Diagnostics); + Assert.Empty(SemanticAnalyzer.Analyze(parsed.Tree, new TestDefinitions())); + } + + [Theory] + [InlineData("mixedFn(", "Sample mixedFn")] + [InlineData("Sample s; s.Mix(", "Sample Mix")] + [InlineData("Sample.Create(", "Sample Create")] + [InlineData("new Sample(", "new Sample")] + public void SignatureHelp_HighlightsTypedPrefixThenVariadicTail(string call, string label) + { + string[] arguments = ["", "1, ", "1, \"label\", ", "1, \"label\", true, ", "1, \"label\", true, 2, "]; + for (var argumentIndex = 0; argumentIndex < arguments.Length; argumentIndex++) + { + var help = GetSignatureHelp(call + arguments[argumentIndex], new TestDefinitions()); + Assert.NotNull(help); + var signature = Assert.Single(help.Signatures); + Assert.Equal(label + "(number count, string label, Params object )", signature.Label); + Assert.NotNull(signature.Parameters); + Assert.Equal(3, signature.Parameters.Length); + Assert.Equal(Math.Min(argumentIndex, 2), help.ActiveParameter); + } + } + + [Theory] + [InlineData("variadicOnly(")] + [InlineData("variadicOnly(1, ")] + [InlineData("variadicOnly(1, true, ")] + public void SignatureHelp_VariadicOnly_KeepsTailActive(string source) + { + var help = GetSignatureHelp(source, new TestDefinitions()); + Assert.NotNull(help); + Assert.Equal(0, help.ActiveParameter); + Assert.Single(help.Signatures); + } + + [Theory] + [InlineData("fixedFn(", 0)] + [InlineData("fixedFn(\"label\", ", 1)] + public void SignatureHelp_NonVariadic_PreservesArgumentIndex(string source, int expected) + { + var help = GetSignatureHelp(source, new TestDefinitions()); + Assert.NotNull(help); + Assert.Equal(expected, help.ActiveParameter); + } + + [Theory] + [InlineData("formatToUser(\"text\");", true)] + [InlineData("formatToUser(\"{0} {1}\", 1, true);", true)] + [InlineData("User u; formatToUser(u, \"text\");", true)] + [InlineData("User u; formatToUser(u, \"{0} {1}\", 1, true);", true)] + [InlineData("formatToUser(empty, \"{0}\", 1);", true)] + [InlineData("formatToUser();", false)] + [InlineData("formatToUser(42, \"{0}\", 1);", false)] + [InlineData("User u; formatToUser(u);", false)] + [InlineData("User u; formatToUser(u, 42, \"text\");", false)] + public void FormatToUser_BundledDefinitions_ValidateBothOverloads(string source, bool valid) + { + var parsed = CgScriptParseService.Parse(source); + Assert.Empty(parsed.Diagnostics); + var diagnostics = SemanticAnalyzer.Analyze(parsed.Tree, new CgScriptDefinitions()); + if (valid) + Assert.Empty(diagnostics); + else + Assert.Equal("CGS022", Assert.Single(diagnostics).Code); + } + + [Fact] + public void FormatToUser_SignatureHelp_PreservesEachOverloadsPrefixAndTail() + { + var help = GetSignatureHelp("formatToUser(\"{0} {1}\", 1, true, ", new CgScriptDefinitions()); + Assert.NotNull(help); + Assert.Equal(2, help.Signatures.Length); + Assert.Contains(help.Signatures, s => s.Label == "string formatToUser(User user, string format, Params object )"); + Assert.Contains(help.Signatures, s => s.Label == "string formatToUser(string format, Params object )"); + var active = help.Signatures[help.ActiveSignature ?? 0]; + Assert.NotNull(active.Parameters); + Assert.Equal(active.Parameters.Length - 1, help.ActiveParameter); + } + + private static SignatureHelp? GetSignatureHelp(string source, CgScriptDefinitions definitions) + { + const string uri = "file:///variadic.cgs"; + var store = new DocumentStore(definitions); + store.Update(uri, source); + var target = new CgScriptLanguageTarget(store, definitions); + return target.OnSignatureHelp(new SignatureHelpParams + { + TextDocument = new TextDocumentIdentifier { Uri = new Uri(uri) }, + Position = new Position(0, source.Length), + }); + } +} diff --git a/Catglobe.CgScript.EditorSupport.Lsp/Catglobe.CgScript.EditorSupport.Lsp.csproj b/Catglobe.CgScript.EditorSupport.Lsp/Catglobe.CgScript.EditorSupport.Lsp.csproj index 2f8a8053..8d97c48b 100644 --- a/Catglobe.CgScript.EditorSupport.Lsp/Catglobe.CgScript.EditorSupport.Lsp.csproj +++ b/Catglobe.CgScript.EditorSupport.Lsp/Catglobe.CgScript.EditorSupport.Lsp.csproj @@ -42,6 +42,8 @@ + + diff --git a/Catglobe.CgScript.EditorSupport.Lsp/Handlers/CgScriptLanguageTarget.Hover.cs b/Catglobe.CgScript.EditorSupport.Lsp/Handlers/CgScriptLanguageTarget.Hover.cs index 781402de..e68fd625 100644 --- a/Catglobe.CgScript.EditorSupport.Lsp/Handlers/CgScriptLanguageTarget.Hover.cs +++ b/Catglobe.CgScript.EditorSupport.Lsp/Handlers/CgScriptLanguageTarget.Hover.cs @@ -369,9 +369,9 @@ private string BuildEnumConstantDoc(string name) } /// - /// Builds signature info for a method call on an instance or type: receiver.Method(. + /// Resolves overloads for a method call on an instance or type: receiver.Method(. /// - private SignatureInformation[]? TryBuildMethodSignatures( + private MethodOverload[]? TryGetMethodOverloads( string methodName, string text, int parenPos, Antlr4.Runtime.Tree.IParseTree? tree) { // Step back over whitespace to the char before the method name identifier. @@ -399,18 +399,7 @@ private string BuildEnumConstantDoc(string name) var methodSource = isStatic ? objDef.StaticMethods : objDef.Methods; if (methodSource == null || !methodSource.TryGetValue(methodName, out var methods) || methods.Length == 0) return null; - return methods.Select(m => new SignatureInformation - { - Label = $"{m.ReturnType} {methodName}({BuildMethodParamList(m.Param)})", - Documentation = new SumType( - new MarkupContent { Kind = MarkupKind.Markdown, Value = m.Doc ?? string.Empty }), - Parameters = (m.Param ?? []).Select(p => - new ParameterInformation - { - Label = new SumType>($"{p.Type} {p.Name}"), - Documentation = new SumType(p.Doc ?? string.Empty), - }).ToArray(), - }).ToArray(); + return methods; } /// diff --git a/Catglobe.CgScript.EditorSupport.Lsp/Handlers/CgScriptLanguageTarget.SignatureHelp.cs b/Catglobe.CgScript.EditorSupport.Lsp/Handlers/CgScriptLanguageTarget.SignatureHelp.cs index bb916267..dea8d40f 100644 --- a/Catglobe.CgScript.EditorSupport.Lsp/Handlers/CgScriptLanguageTarget.SignatureHelp.cs +++ b/Catglobe.CgScript.EditorSupport.Lsp/Handlers/CgScriptLanguageTarget.SignatureHelp.cs @@ -56,9 +56,11 @@ public partial class CgScriptLanguageTarget if (funcName is null) return null; SignatureInformation[]? signatures = null; + MethodOverload[]? overloads = null; if (_definitions.Functions.TryGetValue(funcName, out var fn)) { + overloads = fn; signatures = BuildSignatureInfoList(funcName, fn); } else if (_definitions.WhereExpressions.TryGetValue(funcName, out var whereDef)) @@ -69,14 +71,17 @@ public partial class CgScriptLanguageTarget && obj.Constructors?.Length > 0 && IsConstructorCall(text, i, funcName)) { + overloads = obj.Constructors; signatures = BuildConstructorSignatureInfoList(funcName, obj.Constructors); } else { // Method call on a variable: receiver.Method( — find the dot and // resolve the receiver's declared type, then look up the method. - signatures = TryBuildMethodSignatures(funcName, text, i, + overloads = TryGetMethodOverloads(funcName, text, i, _store.GetParseResult(p.TextDocument.Uri.ToString())?.Tree); + if (overloads != null) + signatures = BuildSignatureInfoList(funcName, overloads); } if (signatures is null) return null; @@ -85,7 +90,9 @@ public partial class CgScriptLanguageTarget { Signatures = signatures, ActiveSignature = 0, - ActiveParameter = commaCount, + ActiveParameter = overloads is { Length: > 0 } + ? GetActiveParameter(overloads[0].Param, commaCount) + : commaCount, }; } else if (c == '[' && parenDepth == 0 && bracketDepth == 0) @@ -112,6 +119,12 @@ public partial class CgScriptLanguageTarget return null; } + /// All arguments in a variadic tail highlight its single parameter. + private static int GetActiveParameter(MethodParam[] parameters, int argumentIndex) + => parameters.Length > 0 && parameters[parameters.Length - 1].Type == "Params object" + ? Math.Min(argumentIndex, parameters.Length - 1) + : argumentIndex; + /// /// Builds signature info for an indexer expression receiver[. /// Resolves the receiver variable (or chained property) to its declared type, then diff --git a/Catglobe.CgScript.EditorSupport.Parsing/Resources/CgScriptDefinitions.json b/Catglobe.CgScript.EditorSupport.Parsing/Resources/CgScriptDefinitions.json index c1ccde0b..8d493c44 100644 --- a/Catglobe.CgScript.EditorSupport.Parsing/Resources/CgScriptDefinitions.json +++ b/Catglobe.CgScript.EditorSupport.Parsing/Resources/CgScriptDefinitions.json @@ -10685,6 +10685,43 @@ ] } ], + "formatToUser": [ + { + "doc": "Formats a string like format, but with the culture of the given user, e.g. formatToUser(User_getCurrentUser(), \"{0:N0}\", 12345)", + "returnType": "string", + "param": [ + { + "name": "user", + "doc": "The user whose culture to format with; empty uses the user that most likely started the script", + "type": "User" + }, + { + "name": "format", + "doc": "The composite format string", + "type": "string" + }, + { + "name": "", + "type": "Params object" + } + ] + }, + { + "doc": "Formats a string like format, but with the culture of the user that most likely started the script", + "returnType": "string", + "param": [ + { + "name": "format", + "doc": "The composite format string", + "type": "string" + }, + { + "name": "", + "type": "Params object" + } + ] + } + ], "getAddress": [ { "doc": "Returns the street address of the current QAS user, or empty if not set", @@ -62203,4 +62240,4 @@ "obsoleteMessage": null } } -} \ No newline at end of file +}