Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
158 changes: 158 additions & 0 deletions Catglobe.CgScript.EditorSupport.Lsp.Tests/VariadicParameterTests.cs
Original file line number Diff line number Diff line change
@@ -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<string, MethodOverload[]>
{
["mixedFn"] = [Mixed],
["variadicOnly"] = [new(Param: [new("", Type: "Params object")])],
["fixedFn"] = [new(Param: [new("label", Type: "string")])],
},
new Dictionary<string, ObjectDefinition>
{
["Sample"] = new("", Constructors: [Mixed],
Methods: new() { ["Mix"] = [Mixed] },
StaticMethods: new() { ["Create"] = [Mixed] }),
}, new Dictionary<string, GlobalVariableDefinition>(), [], [])
{ }
}

[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),
});
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,8 @@
<PackageReference Include="Microsoft.VisualStudio.LanguageServer.Protocol" Version="17.2.8" />
<PackageReference Include="Nerdbank.MessagePack" Version="1.2.30" />
<PackageReference Include="StreamJsonRpc" Version="2.25.29" />
<!-- Override StreamJsonRpc's vulnerable transitive version (GHSA-qhrr-8q5h-9q3h). -->
<PackageReference Include="MessagePack" Version="2.5.303" />
<!-- Pin all System.* transitive deps to 10.x so the server runs on .NET 10 (rollForward:Major) -->
<PackageReference Include="System.Diagnostics.DiagnosticSource" Version="10.0.9" />
<PackageReference Include="System.IO.Pipelines" Version="10.0.9" />
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -369,9 +369,9 @@ private string BuildEnumConstantDoc(string name)
}

/// <summary>
/// Builds signature info for a method call on an instance or type: <c>receiver.Method(</c>.
/// Resolves overloads for a method call on an instance or type: <c>receiver.Method(</c>.
/// </summary>
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.
Expand Down Expand Up @@ -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<string, MarkupContent>(
new MarkupContent { Kind = MarkupKind.Markdown, Value = m.Doc ?? string.Empty }),
Parameters = (m.Param ?? []).Select(p =>
new ParameterInformation
{
Label = new SumType<string, Tuple<int, int>>($"{p.Type} {p.Name}"),
Documentation = new SumType<string, MarkupContent>(p.Doc ?? string.Empty),
}).ToArray(),
}).ToArray();
return methods;
}

/// <summary>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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))
Expand All @@ -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;
Expand All @@ -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)
Expand All @@ -112,6 +119,12 @@ public partial class CgScriptLanguageTarget
return null;
}

/// <summary>All arguments in a variadic tail highlight its single parameter.</summary>
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;

/// <summary>
/// Builds signature info for an indexer expression <c>receiver[</c>.
/// Resolves the receiver variable (or chained property) to its declared type, then
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down Expand Up @@ -62203,4 +62240,4 @@
"obsoleteMessage": null
}
}
}
}
Loading