fix(csharp): show Roslyn's inlay hints and bold the right parameter (#7701)

Roslyn's inlay hints are off unless the client turns them on, and csharp.toml passed no csharp|inlay_hints settings, so C# showed no parameter name or type hints. csharp.toml and razor.toml now enable parameter hints for literals, new-expressions and indexers (with Roslyn's suppressions) and var/lambda parameter types. Parameter info matches string parameter labels as whole words from the parameter list on (all servers) and keeps a variadic last parameter (params, ..., *args) bold. The real-server test is ignored by default (needs the .NET SDK).

Closes #7678

Co-authored-by: wildcatDownstairs <[email protected]>
Цей коміт міститься в:
LU XIANGRUIтаwildcatDownstairs authored and GitHub committed 2026-12-03 15:31:16 +08:00
1 джерело 7fdd39a628
коміт 9e4fbe863d
9 files changed
+719 -13

No files matched your search

+343
Переглянути файл
@@ -0,0 +1,343 @@
//! C# inlay hints and parameter info (#7678) with the bundled settings, against the real `dotnet`,
//! csharp-ls and the Roslyn language server, installed as Settings does (network). Ignored by
//! default: `cargo test -p ide-host --test roslyn_hints -- --ignored`; skipped without a .NET SDK.
mod common;
use ide_core::{DocId, Pos, Range};
use ide_host::{Host, HostConfig, ops};
use ide_lsp::types::{InlayHint, InlayKind, SignatureHelp};
use ide_workspace::settings::SettingsScope;
use std::path::Path;
use std::process::Command;
use std::sync::Arc;
use std::time::{Duration, Instant};
const WINDOW: &str = "main";
/// Complete code: what the hints are asked for.
const HINTS: &str = r#"using System;
using System.Collections.Generic;
using System.Linq;
public record Point(int X, int Y);
public static class Ext { public static string Repeat(this string s, int count) => s; }
public class Grid { public int this[int row, int column] => row; }
public class Demo
{
static int Add(int first, int second) => first + second;
static void Log(string format, params object[] args) { }
static void Opt(int width, int height = 2, bool visible = true) { }
static T Echo<T>(T value) => value;
static void Take(Point point) { }
static void Enable(bool value) { }
static void SetColor(string color) { }
static void Pair(int item1, int item2) { }
static void Name(string name) { }
public void Run(string name, int total)
{
var sum = Add(1, 2);
var point = new Point(3, 4);
Take(new Point(5, 6));
Take(new(5, 6));
Opt(width: 1, visible: false);
Opt(
1,
height: 3);
Log("a {0}", 1, 2);
var r = "x".Repeat(3);
var g = Echo<int>(7);
var cell = new Grid()[1, 2];
var xs = new List<int> { 1 }.Select(n => n + 1);
Add(Add(1, total), 3);
var text = $"v={Add(total, 2)}";
var 名前 = "日本語😀"; Add(名前.Length, 2);
Point q = new(1, 2);
Enable(true);
SetColor("red");
Pair(1, 2);
Name("x");
Name(name);
Func<int, int, int> f = (a, b) => a + b;
List<int> empty = [];
foreach (var item in xs) { }
}
}
"#;
/// `HINTS` from `Run` on, with Roslyn's hints written in: `‹name:›` before an argument, `«type»`
/// before a name.
const ROSLYN: &str = r#" public void Run(string name, int total)
{
var «int»sum = Add(‹first:›1, ‹second:›2);
var «Point?»point = new Point(‹X:›3, ‹Y:›4);
Take(‹point:›new Point(‹X:›5, ‹Y:›6));
Take(new(‹X:›5, ‹Y:›6));
Opt(width: 1, visible: false);
Opt(
‹width:›1,
height: 3);
Log(‹format:›"a {0}", ‹args:›1, 2);
var «string?»r = "x".Repeat(‹count:›3);
var «int»g = Echo<int>(‹value:›7);
var «int»cell = new Grid()[‹row:›1, ‹column:›2];
var «IEnumerable<int>?»xs = new List<int> { 1 }.Select(«int»n => n + 1);
Add(Add(‹first:›1, total), ‹second:›3);
var «string?»text = $"v={Add(total, ‹second:›2)}";
var «string?»名前 = "日本語😀"; Add(名前.Length, ‹second:›2);
Point q = new(‹X:›1, ‹Y:›2);
Enable(‹value:›true);
SetColor("red");
Pair(1, 2);
Name(‹name:›"x");
Name(name);
Func<int, int, int> f = («int»a, «int»b) => a + b;
List<int> empty = [];
foreach (var «int»item in xs) { }
}
}
"#;
/// Code being typed: where parameter info is asked for.
const CALLS: &str = r#"public record Point(int X, int Y);
public static class Ext { public static string Repeat(this string s, int count) => s; }
public class Grid { public int this[int row, int column] => row; }
public class Calls
{
static int Add(int first, int second) => first + second;
static int Add(int first, int second, int third) => first;
static void Take(int a, int n) { }
static void Log(string format, params object[] args) { }
static void Opt(int width, int height = 2, bool visible = true) { }
static T Echo<T>(T value) => value;
static void Origin(Point point) { }
static void Map(System.Func<int, int> map, int e) { }
public void Run(int total)
{
Add(1, );
Add(1, 2, );
Take(1, );
Add(Add(1, total), 3);
Add($"{Add(1, 2)},)".Length, 4);
Add(
total,
);
var 名前 = "日本語😀"; Add(名前.Length, 5);
Log("f", 6, 7);
Opt(visible: true, width: 8);
"x".Repeat(9);
Echo<int>(10);
new Point(11, 12);
Origin(new(13, 14));
new Grid()[15, 16].ToString();
Map(x => x, 17);
}
}
"#;
fn has_dotnet() -> bool {
Command::new("dotnet").arg("--version").output().is_ok_and(|o| o.status.success())
}
/// Installs a server as Settings does and puts it on `PATH` as the app does at startup. This
/// binary has one test, so nothing else reads the environment meanwhile.
fn install(data: &Path, server: &str) {
let languages = ide_language::LanguageRegistry::load(None).unwrap().all();
ide_tools::Tools::new(data).install(server, &languages, &Default::default(), &|_| {}).unwrap();
ide_tools::extend_process_path(data);
}
/// A host with the project in `root` open.
async fn open(root: &Path, base: &Path) -> Arc<Host> {
let host = Arc::new(Host::new(HostConfig { ..common::host_config(base) }));
host.set_project_trust(root, true, false).await.unwrap();
host.open_project(WINDOW, root).unwrap();
host
}
async fn document(host: &Arc<Host>, root: &Path, file: &str) -> DocId {
ops::doc::doc_open(host, WINDOW, root.join(file)).await.unwrap().id
}
/// Asks for the hints of the whole file until `done`, while the server loads the project.
async fn hints(host: &Host, doc: DocId, done: impl Fn(&[InlayHint]) -> bool) -> Vec<InlayHint> {
let range = Range::new(Pos::new(0, 0), Pos::new(HINTS.lines().count() as u32, 0));
let start = Instant::now();
loop {
let found = ops::lsp::lsp_inlay_hints(host, WINDOW, doc, range).await;
if let Ok(found) = &found
&& done(found)
{
return found.clone();
}
assert!(
start.elapsed() < Duration::from_secs(180),
"{found:#?}\n{}",
render(found.as_deref().unwrap_or_default())
);
tokio::time::sleep(Duration::from_millis(500)).await;
}
}
/// The byte offset of UTF-16 column `col`.
fn byte(line: &str, col: u32) -> usize {
let mut units = 0;
line.char_indices()
.find(|(_, c)| {
let here = units;
units += c.len_utf16() as u32;
here >= col
})
.map_or(line.len(), |(i, _)| i)
}
/// `HINTS` from `Run` on, with `hints` written in.
fn render(hints: &[InlayHint]) -> String {
let first = HINTS.lines().position(|l| l.contains("void Run")).unwrap();
let mut out = String::new();
for (number, line) in HINTS.lines().enumerate().skip(first) {
let mut line_hints: Vec<_> = hints.iter().filter(|h| h.position.line == number as u32).collect();
line_hints.sort_by_key(|h| h.position.col);
let mut end = 0;
for hint in line_hints {
let at = byte(line, hint.position.col);
out.push_str(&line[end..at]);
end = at;
let (open, close) = if matches!(hint.kind, InlayKind::Type) { ('«', '»') } else { ('‹', '›') };
out.push(open);
out.push_str(hint.label.trim());
out.push(close);
}
out.push_str(&line[end..]);
out.push('\n');
}
out
}
/// Parameter info with the caret at the `|` of `marked`, a piece of one line of `CALLS`:
/// the number of overloads, the marked one's label and the parameter it bolds.
async fn parameter_info(host: &Host, doc: DocId, marked: &str) -> Option<(usize, String, u32, String)> {
let (before, after) = marked.split_once('|').unwrap();
let needle = format!("{before}{after}");
let (number, line) = CALLS.lines().enumerate().find(|(_, l)| l.contains(&needle)).expect(marked);
let col = line[..line.find(&needle).unwrap() + before.len()].encode_utf16().count();
let help: Option<SignatureHelp> =
ops::lsp::lsp_signature_help(host, WINDOW, doc, Pos::new(number as u32, col as u32)).await.unwrap();
help.map(|help| {
let signature = &help.signatures[help.active_signature as usize];
let units: Vec<u16> = signature.label.encode_utf16().collect();
let bold = signature
.parameters
.get(help.active_parameter as usize)
.map_or_else(String::new, |&(a, b)| String::from_utf16(&units[a as usize..b as usize]).unwrap());
(help.signatures.len(), signature.label.clone(), help.active_parameter, bold)
})
}
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
#[ignore = "installs csharp-ls and roslyn-language-server and needs the .NET SDK"]
async fn csharp_inlay_hints_and_parameter_info() {
if !has_dotnet() {
return;
}
let tmp = tempfile::tempdir().unwrap();
let base = dunce::canonicalize(tmp.path()).unwrap();
let root = base.join("app");
std::fs::create_dir_all(&root).unwrap();
std::fs::write(
root.join("App.csproj"),
"<Project Sdk=\"Microsoft.NET.Sdk\"><PropertyGroup><TargetFramework>net10.0</TargetFramework>\
<Nullable>enable</Nullable></PropertyGroup></Project>\n",
)
.unwrap();
std::fs::write(root.join("Hints.cs"), HINTS).unwrap();
let restore = Command::new("dotnet").arg("restore").current_dir(&root).output().unwrap();
assert!(restore.status.success(), "{}", String::from_utf8_lossy(&restore.stdout));
let tools = base.join("tools");
let has = |hints: &[InlayHint], line: &str, label: &str| {
let number = HINTS.lines().position(|l| l.trim() == line).expect(line) as u32;
hints.iter().any(|h| h.position.line == number && h.label.trim() == label)
};
// csharp-ls, the fallback without Roslyn: its own hints, which the C# settings don't touch.
install(&tools, "csharp-ls");
let host = open(&root, &base.join("fallback")).await;
let doc = document(&host, &root, "Hints.cs").await;
hints(&host, doc, |h| has(h, "var sum = Add(1, 2);", "first:") && has(h, "var sum = Add(1, 2);", ": int")).await;
host.shutdown().await;
install(&tools, "roslyn-language-server");
let host = open(&root, &base.join("roslyn")).await;
let doc = document(&host, &root, "Hints.cs").await;
let found = hints(&host, doc, |h| render(h) == ROSLYN).await;
assert!(found.iter().all(|h| !matches!(h.kind, InlayKind::Other)), "Editor › Inlay Hints switches them by kind");
// The server's own settings (Settings › Language Servers) win, without a restart.
let set = |value: &str| {
ops::project::settings_set(
&host,
WINDOW,
SettingsScope::Global,
"languageServers.roslyn-language-server.settings".into(),
value.into(),
)
.unwrap();
};
set(r#"{"csharp|inlay_hints":{"dotnet_enable_inlay_hints_for_parameters":false}}"#);
hints(&host, doc, |h| !h.is_empty() && h.iter().all(|h| matches!(h.kind, InlayKind::Type))).await;
set(r#"{"csharp|inlay_hints":{"csharp_enable_inlay_hints_for_types":false}}"#);
hints(&host, doc, |h| !h.is_empty() && h.iter().all(|h| matches!(h.kind, InlayKind::Parameter))).await;
// Parameter info, with the bundled settings untouched.
std::fs::write(root.join("Calls.cs"), CALLS).unwrap();
std::fs::remove_file(root.join("Hints.cs")).unwrap();
host.shutdown().await;
let host = open(&root, &base.join("calls")).await;
let doc = document(&host, &root, "Calls.cs").await;
let start = Instant::now();
while parameter_info(&host, doc, "Take(1, |)").await.is_none() {
assert!(start.elapsed() < Duration::from_secs(180), "no parameter info");
tokio::time::sleep(Duration::from_millis(500)).await;
}
let two = "int Calls.Add(int first, int second)";
let three = "int Calls.Add(int first, int second, int third)";
let log = "void Calls.Log(string format, params object[] args)";
let opt = "void Calls.Opt(int width, int height = 2, bool visible = true)";
// (caret, overloads, marked signature, active parameter, bolded text)
let cases = [
("Add(|1, );", 2, two, 0, "first"),
("Add(1, |);", 2, two, 1, "second"),
// A third argument marks the overload that takes it.
("Add(1, 2, |);", 2, three, 2, "third"),
// `n` is also a letter in front of the parameter list.
("Take(1, |);", 1, "void Calls.Take(int a, int n)", 1, "n"),
("Add(Add(1, |total), 3);", 2, two, 1, "second"),
("Add(Add(1, total), |3);", 2, two, 1, "second"),
(r#"Length, |4);"#, 2, two, 1, "second"),
(" |);", 2, two, 1, "second"),
("Add(名前.Length, |5);", 2, two, 1, "second"),
(r#"Log("f", |6, 7);"#, 1, log, 1, "args"),
// Past the `params` array the count goes on; the popup keeps `args` bold (signature.ts).
(r#"Log("f", 6, |7);"#, 1, log, 2, ""),
("visible: |true", 1, opt, 2, "visible"),
("width: |8", 1, opt, 0, "width"),
(r#""x".Repeat(|9)"#, 1, "(extension) string string.Repeat(int count)", 0, "count"),
("Echo<int>(|10)", 1, "int Calls.Echo<int>(int value)", 0, "value"),
("new Point(11, |12)", 1, "Point(int X, int Y)", 1, "Y"),
("new(13, |14)", 1, "Point(int X, int Y)", 1, "Y"),
("[15, |16]", 1, "int Grid[int row, int column]", 1, "column"),
("Map(x => x, |17)", 1, "void Calls.Map(System.Func<int, int> map, int e)", 1, "e"),
];
for (caret, overloads, label, active, bold) in cases {
let found = parameter_info(&host, doc, caret).await;
assert_eq!(found, Some((overloads, label.to_owned(), active, bold.to_owned())), "{caret}");
}
// Closed after the `)` of the outermost call.
assert_eq!(parameter_info(&host, doc, "Add(Add(1, total), 3);|").await, None);
host.shutdown().await;
}
+63 -7
Переглянути файл
@@ -904,6 +904,31 @@ pub fn workspace_symbols(conv: &Conv, r: lsp::WorkspaceSymbolResponse) -> Vec<Wo
}
}
fn is_word(c: char) -> bool {
c.is_alphanumeric() || c == '_'
}
/// The first `(` or `[` right after a name (`Take(`, `Echo<T>(`, `Grid[`), else the label's start.
fn parameter_list_start(label: &str) -> usize {
label
.match_indices(['(', '['])
.find(|(i, _)| label[..*i].chars().next_back().is_some_and(|c| is_word(c) || c == '>'))
.map_or(0, |(i, _)| i)
}
/// Where the string parameter label `name` is in `label`, at or after `from`: as a whole word
/// (`a` is not the one in `max`), else anywhere.
fn find_parameter(label: &str, name: &str, from: usize) -> Option<usize> {
let whole = |start: usize| {
let glued = |a: Option<char>, b: Option<char>| a.is_some_and(is_word) && b.is_some_and(is_word);
!glued(label[..start].chars().next_back(), name.chars().next())
&& !glued(name.chars().next_back(), label[start + name.len()..].chars().next())
};
let rest = &label[from..];
let mut found = rest.match_indices(name).map(|(i, _)| from + i);
found.find(|&start| whole(start)).or_else(|| rest.find(name).map(|i| from + i))
}
pub fn signature_help(conv_enc: Encoding, h: lsp::SignatureHelp) -> Option<SignatureHelp> {
if h.signatures.is_empty() {
return None;
@@ -915,7 +940,9 @@ pub fn signature_help(conv_enc: Encoding, h: lsp::SignatureHelp) -> Option<Signa
.signatures
.into_iter()
.map(|s| {
let mut search_from = 0usize; // byte offset in label
// Byte offset in the label: string labels are looked up from the parameter list on,
// so a name in front of it isn't taken for the parameter.
let mut search_from = parameter_list_start(&s.label);
let parameters = s
.parameters
.unwrap_or_default()
@@ -924,12 +951,10 @@ pub fn signature_help(conv_enc: Encoding, h: lsp::SignatureHelp) -> Option<Signa
lsp::ParameterLabel::LabelOffsets([a, b]) => {
convert_offsets(&s.label, a as usize, b as usize, conv_enc)
}
lsp::ParameterLabel::Simple(name) => match s.label[search_from..].find(&name) {
Some(i) => {
let start = search_from + i;
let end = start + name.len();
search_from = end;
convert_offsets(&s.label, start, end, Encoding::Utf8)
lsp::ParameterLabel::Simple(name) => match find_parameter(&s.label, &name, search_from) {
Some(start) => {
search_from = start + name.len();
convert_offsets(&s.label, start, search_from, Encoding::Utf8)
}
None => (0, 0),
},
@@ -1431,6 +1456,37 @@ mod tests {
assert_eq!(s.active_parameter, 1);
}
#[test]
fn string_parameter_labels_are_whole_words_in_the_parameter_list() {
let bolded = |label: &str, parameters: &[&str]| {
let h: lsp::SignatureHelp = serde_json::from_value(json!({ "signatures": [{
"label": label,
"parameters": parameters.iter().map(|p| json!({ "label": p })).collect::<Vec<_>>(),
}] }))
.unwrap();
let units: Vec<u16> = label.encode_utf16().collect();
signature_help(Encoding::Utf16, h).unwrap().signatures[0]
.parameters
.iter()
.map(|&(a, b)| (a, String::from_utf16(&units[a as usize..b as usize]).unwrap()))
.collect::<Vec<_>>()
};
let at = |expected: &[(u32, &str)]| expected.iter().map(|&(a, p)| (a, p.to_owned())).collect::<Vec<_>>();
// Roslyn labels parameters by name: not the `a` of `Take`, the `t` of `string` or the method `count`.
assert_eq!(bolded("void Demo.Take(int a, int n)", &["a", "n"]), at(&[(19, "a"), (26, "n")]));
assert_eq!(bolded("void Demo.Log(string t)", &["t"]), at(&[(21, "t")]));
assert_eq!(bolded("int Demo.count(int count)", &["count"]), at(&[(19, "count")]));
// Generic methods, indexers, a tuple return type, type arguments without a parameter list.
assert_eq!(bolded("int Echo<value>(value value)", &["value"]), at(&[(16, "value")]));
assert_eq!(bolded("int Grid[int row, int r]", &["row", "r"]), at(&[(13, "row"), (22, "r")]));
assert_eq!(bolded("(int a, int b) Demo.Pair(int a)", &["a"]), at(&[(29, "a")]));
assert_eq!(bolded("Demo.Echo<T>", &["T"]), at(&[(10, "T")]));
// UTF-16 offsets after multi-byte names.
assert_eq!(bolded("void 日本😀.f(int 名前)", &["名前"]), at(&[(16, "名前")]));
// Not a whole word anywhere: the first occurrence, as before.
assert_eq!(bolded("f(xs)", &["x", "gone"]), at(&[(2, "x"), (0, "")]));
}
#[test]
fn location_links_use_target_selection_range() {
let conv = Conv::utf16();
+3
Переглянути файл
@@ -14,6 +14,8 @@ OpenIDEA supports C# (`.cs`, `.csx`) through Microsoft's [Roslyn language server
For C#, the IDE uses the Roslyn language server when it is installed and csharp-ls otherwise. Roslyn is the server of the VS Code C# extension. It needs the .NET 10 SDK or newer; csharp-ls also runs on older SDKs. With Roslyn, completion also lists types from namespaces the file doesn't import yet (shown with their namespace), and accepting one adds the `using` directive. Roslyn starts with `--autoLoadProjects`, so it finds and opens the solution or projects itself. On macOS and Linux it loads SDK-style projects only: .NET Framework projects need Mono MSBuild, which it doesn't use. Unity's Visual Studio Editor package generates SDK-style `.csproj` files.
With Roslyn, the editor shows inlay hints: parameter names before literals, `new` objects and indexer arguments (not before variables or other expressions, and not where the method or argument name already says it), and the types of `var` and lambda parameters. Turn them off in **Settings › Editor › Inlay Hints** (types, parameter names, or C# altogether). The server's own options win over these defaults: set them in **Settings › Languages & Frameworks › Language Servers** › Roslyn (C#) › settings, for example `{"csharp|inlay_hints": {"dotnet_enable_inlay_hints_for_other_parameters": true}}`. csharp-ls sends its own inlay hints. Parameter info opens after `(` and `,` and with ⌘P / Ctrl+P, with the current parameter in bold.
The server loads the solution or project it finds from these markers. FsAutoComplete starts with `AutomaticWorkspaceInit` on, so it loads the projects without waiting for the editor to ask.
When you go to the definition of a library type, the server returns decompiled source. It opens as a read-only document, and so does source-generated code.
@@ -111,6 +113,7 @@ See [Debugging](/en/guide/debugging).
- Builds always use the `Debug` configuration; there is no setting to build `Release` from the Project view.
- Test configurations run without a debugger; there is no Debug action for .NET tests.
- There is no Visual Basic language server.
- csharp-ls doesn't report the current parameter while you type the last argument, so parameter info bolds the first one. Roslyn does.
- netcoredbg has no prebuilt download for Intel Macs or Windows on ARM64, so **Install** isn't offered there. [Build it from source](https://github.com/Samsung/netcoredbg#building-from-source-code), then put `netcoredbg` on `PATH` or set its executable path in **Settings › Languages & Frameworks › Language Servers**.
- There is no designer for WinForms, WPF or XAML.
- Razor needs roslyn-language-server (and so the .NET 10 SDK); with csharp-ls, `.cshtml` and `.razor` files have highlighting and the IDE's own features only.
+3
Переглянути файл
@@ -14,6 +14,8 @@ OpenIDEA 通过微软的 [Roslyn 语言服务器](https://github.com/dotnet/rosl
C# 在装了 Roslyn 语言服务器时用它,否则用 csharp-ls。Roslyn 是 VS Code C# 扩展使用的服务器,需要 .NET 10 或更新的 SDK;csharp-ls 在较旧的 SDK 上也能运行。用 Roslyn 时,补全还会列出当前文件尚未导入的命名空间里的类型(附带命名空间),选中后自动加上 `using` 指令。Roslyn 以 `--autoLoadProjects` 启动,会自己找到并打开解决方案或项目。在 macOS 和 Linux 上它只加载 SDK 风格的项目:.NET Framework 项目需要 Mono MSBuild,它不使用。Unity 的 Visual Studio Editor 包生成的就是 SDK 风格的 `.csproj`。
使用 Roslyn 时,编辑器显示内联提示:字面量、`new` 对象和索引器实参前的参数名(变量和其他表达式前不显示,方法名或实参名已经说明含义时也不显示),以及 `var` 和 lambda 参数的类型。可在 **Settings › Editor › Inlay Hints** 中关闭(类型、参数名,或整个 C#)。服务器自身的选项优先于这些默认值:在 **Settings › Languages & Frameworks › Language Servers** › Roslyn (C#) › settings 中设置,例如 `{"csharp|inlay_hints": {"dotnet_enable_inlay_hints_for_other_parameters": true}}`。csharp-ls 发送它自己的内联提示。输入 `(` 和 `,` 之后或按 ⌘P / Ctrl+P 会弹出参数信息,当前参数以粗体显示。
语言服务器会加载根据这些标记找到的解决方案或项目。FsAutoComplete 启动时开启了 `AutomaticWorkspaceInit`,无需等待编辑器请求就会自动加载项目。
跳转到类库类型的定义时,语言服务器返回反编译后的源码,以只读文档打开;源生成器生成的代码同样以只读方式打开。
@@ -90,5 +92,6 @@ C# 在装了 Roslyn 语言服务器时用它,否则用 csharp-ls。Roslyn 是
- 构建始终使用 `Debug` 配置,项目视图中无法选择构建 `Release`。
- 测试配置不带调试器运行,.NET 测试没有调试入口。
- 没有 Visual Basic 语言服务器。
- 使用 csharp-ls 时,输入最后一个实参的过程中它不返回当前参数,参数信息会加粗第一个参数。Roslyn 没有这个问题。
- netcoredbg 没有 Intel Mac 和 Windows ARM64 的预编译包,这两个平台不提供**安装**。请[从源码编译](https://github.com/Samsung/netcoredbg#building-from-source-code),然后把 `netcoredbg` 放到 `PATH` 上,或在 **Settings › Languages & Frameworks › Language Servers** 里设置它的可执行文件路径。
- 没有 WinForms、WPF 或 XAML 设计器。
+195
Переглянути файл
@@ -0,0 +1,195 @@
/**
* C# inlay hints and parameter info (#7678). The host is stubbed at the IPC layer with the answers
* Roslyn gives; `crates/ide-host/tests/roslyn_hints.rs` gets them from the real server.
*/
import type { Page } from "@playwright/test";
import type { InlayHint, SignatureHelp } from "../src/bindings";
import { expect, openFromTree, stubDesktop, stubSettingsWrites, test } from "./fixtures";
const SHOTS = process.env.E2E_SHOTS;
/** Roslyn's hints written in: `‹name:›` before an argument, `«type»` before a name. */
const ANNOTATED = `public class Demo
{
static int Add(int first, int second) => first + second;
static void Log(string format, params object[] args) { }
public void Run(int total)
{
var «int»sum = Add(‹first:›1, ‹second:›2);
var «Point?»point = new Point(‹X:›3, ‹Y:›4);
Add(total, ‹second:›3);
var «IEnumerable<int>?»xs = list.Select(«int»n => n + 1);
Log
}
}
`;
function fixture() {
const hints: InlayHint[] = [];
const text = ANNOTATED.split("\n")
.map((line, number) => {
let out = "";
for (const part of line.split(/(‹[^›]*›|«[^»]*»)/)) {
if (!/^[‹«]/.test(part)) {
out += part;
continue;
}
const parameter = part.startsWith("‹");
hints.push({
position: { line: number, col: out.length },
label: part.slice(1, -1),
kind: parameter ? "parameter" : "type",
paddingLeft: false,
paddingRight: true,
tooltip: null,
parts: [],
textEdits: [],
});
}
return out;
})
.join("\n");
return { text, hints };
}
/** A C# file in the sample project, open, with the host stubbed. */
async function openProgram(page: Page) {
const { text, hints } = fixture();
await page.evaluate(async () => {
const projectModule = "/src/platform/project.ts";
const filesModule = "/src/features/project-tree/fs.ts";
const { useProject } = await import(/* @vite-ignore */ projectModule);
const { projectFs } = await import(/* @vite-ignore */ filesModule);
const root = useProject.getState().project.root;
await projectFs(root).createFile(`${root}/Program.cs`);
});
const editor = await openFromTree(page, "Program.cs");
// The in-memory document starts as its path in a comment: replace it with the fixture.
const content = editor.locator(".cm-content");
await expect(content).toContainText("Program.cs");
await content.click();
await page.keyboard.press("Meta+a");
await page.keyboard.insertText(text);
await expect(content).toContainText("public class Demo");
await stubDesktop(page);
await stubSettingsWrites(page);
return { editor, hints };
}
/** Answers `lsp_inlay_hints` with `hints` and has the editor ask again. */
async function answerHints(page: Page, hints: InlayHint[]) {
await page.evaluate(async (hints) => {
const projectModule = "/src/platform/project.ts";
const availabilityModule = "/src/editor/lsp/availability.ts";
const { useProject } = await import(/* @vite-ignore */ projectModule);
const { clearBackoffs } = await import(/* @vite-ignore */ availabilityModule);
window.__ipc.handlers.lsp_inlay_hints = () => hints;
// The editor opened before the stub: its request failed, and it waits before asking again.
clearBackoffs();
// A new `editor.inlay` object has the editor ask again.
const { settings } = useProject.getState();
const editor = { ...settings?.editor, inlay: { ...settings?.editor?.inlay } };
useProject.setState({ settings: { ...settings, editor } });
}, hints);
}
test("C# parameter name and type hints show, and turn off by kind", async ({ workbench: page }) => {
const { editor, hints } = await openProgram(page);
const shown = editor.locator(".cm-lsp-inlay");
// What Roslyn answered without the `csharp|inlay_hints` settings: nothing.
await answerHints(page, []);
await expect(shown).toHaveCount(0);
if (SHOTS) await page.screenshot({ path: `${SHOTS}/csharp-hints-before.png` });
await answerHints(page, hints);
await expect(shown).toHaveCount(hints.length);
await expect(editor.locator(".cm-line", { hasText: "sum" })).toHaveText(
" var intsum = Add(first:1, second:2);",
);
if (SHOTS) await page.screenshot({ path: `${SHOTS}/csharp-hints-after.png` });
await editor.locator(".cm-lsp-inlay-parameter").first().click({ button: "right" });
await page.getByRole("menuitem", { name: "Disable Parameter name hints" }).click();
await expect(editor.locator(".cm-lsp-inlay-parameter")).toHaveCount(0);
await expect(editor.locator(".cm-lsp-inlay-type")).toHaveCount(hints.filter((h) => h.kind === "type").length);
await editor.locator(".cm-lsp-inlay-type").first().click({ button: "right" });
await page.getByRole("menuitem", { name: "Disable Type hints" }).click();
await expect(shown).toHaveCount(0);
});
test("C# parameter info bolds the argument being typed, `params` included", async ({ workbench: page }) => {
const { editor } = await openProgram(page);
// Roslyn's answer: the parameters by name, `activeParameter` counting past the `params` array.
const log: SignatureHelp["signatures"][number] = {
label: "void Demo.Log(string format, params object[] args)",
parameters: [
[21, 27],
[45, 49],
],
documentation: null,
};
await page.evaluate((log) => {
window.__ipc.handlers.lsp_signature_help = (args) => {
const { line, col } = (args as { pos: { line: number; col: number } }).pos;
// The caret's line up to the caret: no answer outside the parentheses.
const view = document.querySelectorAll(".cm-line")[line]!.textContent!.slice(0, col);
if (!view.includes("(") || view.includes(")")) return null;
return { signatures: [log], activeSignature: 0, activeParameter: view.split(",").length - 1 };
};
}, log);
await editor.locator(".cm-line", { hasText: /^ {8}Log$/ }).click();
await page.keyboard.press("End");
const popup = page.locator(".cm-lsp-signature");
await page.keyboard.type("(");
await expect(popup.locator("b")).toHaveText("format");
await page.keyboard.type('"{0}", ');
await expect(popup.locator("b")).toHaveText("args");
await page.keyboard.type("1, ");
// The third argument: past the last parameter. Reopened, so the old popup can't answer for it.
await page.keyboard.press("Escape");
await expect(popup).toBeHidden();
await page.keyboard.press("Meta+p");
await expect(popup.locator("b")).toHaveText("args");
if (SHOTS) await page.screenshot({ path: `${SHOTS}/csharp-parameter-info.png` });
await page.keyboard.type("2)");
await expect(popup).toBeHidden();
});
test("C# parameter info lists the overloads and marks the server's", async ({ workbench: page }) => {
const { editor } = await openProgram(page);
await page.evaluate(() => {
window.__ipc.handlers.lsp_signature_help = () => ({
signatures: [
{
label: "int Demo.Add(int first, int second)",
parameters: [
[17, 22],
[28, 34],
],
documentation: null,
},
{
label: "int Demo.Add(int first, int second, int third)",
parameters: [
[17, 22],
[28, 34],
[40, 45],
],
documentation: null,
},
],
activeSignature: 1,
activeParameter: 2,
});
});
await editor.locator(".cm-line", { hasText: "Add(total" }).click();
await page.keyboard.press("Meta+p");
const popup = page.locator(".cm-lsp-signature");
await expect(popup.locator(".cm-lsp-signature-row")).toHaveCount(2);
await expect(popup.locator(".cm-lsp-signature-active b")).toHaveText("third");
await expect(popup.locator(".cm-lsp-signature-disabled")).toHaveText("int Demo.Add(int first, int second)");
if (SHOTS) await page.screenshot({ path: `${SHOTS}/csharp-overloads.png` });
});
+19
Переглянути файл
@@ -18,6 +18,25 @@ install-hint = "Install Roslyn (C#) in Settings › Languages & Frameworks › L
[language-servers.settings."csharp|completion"]
dotnet_show_completion_items_from_unimported_namespaces = true
# Roslyn's inlay hints are off unless asked for (#7678). Parameter names where the argument
# doesn't say what it is (literals, `new X()`, indexers), not at variables and other expressions;
# the types of `var` and lambda parameters. Editor › Inlay Hints turns each kind off.
[language-servers.settings."csharp|inlay_hints"]
dotnet_enable_inlay_hints_for_parameters = true
dotnet_enable_inlay_hints_for_literal_parameters = true
dotnet_enable_inlay_hints_for_object_creation_parameters = true
dotnet_enable_inlay_hints_for_indexer_parameters = true
dotnet_suppress_inlay_hints_for_parameters_that_differ_only_by_suffix = true
dotnet_suppress_inlay_hints_for_parameters_that_match_method_intent = true
dotnet_suppress_inlay_hints_for_parameters_that_match_argument_name = true
csharp_enable_inlay_hints_for_types = true
csharp_enable_inlay_hints_for_implicit_variable_types = true
csharp_enable_inlay_hints_for_lambda_parameter_types = true
dotnet_enable_inlay_hints_for_other_parameters = false
# On by default in Roslyn; the type is mostly written beside them already (#7326).
csharp_enable_inlay_hints_for_implicit_object_creation = false
csharp_enable_inlay_hints_for_collection_expressions = false
[[language-servers]]
name = "csharp-ls"
# Alternative: used only when the server above is not installed.
+19
Переглянути файл
@@ -27,6 +27,25 @@ install-hint = "Install Roslyn (C#) in Settings › Languages & Frameworks › L
[language-servers.settings."csharp|completion"]
dotnet_show_completion_items_from_unimported_namespaces = true
# Roslyn's inlay hints are off unless asked for (#7678). Parameter names where the argument
# doesn't say what it is (literals, `new X()`, indexers), not at variables and other expressions;
# the types of `var` and lambda parameters. Editor › Inlay Hints turns each kind off.
[language-servers.settings."csharp|inlay_hints"]
dotnet_enable_inlay_hints_for_parameters = true
dotnet_enable_inlay_hints_for_literal_parameters = true
dotnet_enable_inlay_hints_for_object_creation_parameters = true
dotnet_enable_inlay_hints_for_indexer_parameters = true
dotnet_suppress_inlay_hints_for_parameters_that_differ_only_by_suffix = true
dotnet_suppress_inlay_hints_for_parameters_that_match_method_intent = true
dotnet_suppress_inlay_hints_for_parameters_that_match_argument_name = true
csharp_enable_inlay_hints_for_types = true
csharp_enable_inlay_hints_for_implicit_variable_types = true
csharp_enable_inlay_hints_for_lambda_parameter_types = true
dotnet_enable_inlay_hints_for_other_parameters = false
# On by default in Roslyn; the type is mostly written beside them already (#7326).
csharp_enable_inlay_hints_for_implicit_object_creation = false
csharp_enable_inlay_hints_for_collection_expressions = false
# Tailwind CSS: class completion, hover and diagnostics, only in a project that uses Tailwind
# (`tailwind.config.*` or `tailwindcss` in package.json). After the language's own servers,
# which answer hover first.
+58
Переглянути файл
@@ -18,6 +18,7 @@ vi.mock("@/platform/ipc", async (orig) => {
const {
signatureExtension,
acceptsParameter,
parameterAt,
argumentSpans,
argumentStop,
parameterInfoOrLeave,
@@ -223,6 +224,63 @@ describe("parameter info replies", () => {
});
});
describe("C# parameter info", () => {
// What Roslyn answers: parameters by name, `activeParameter` counting past a `params` array.
const log = {
label: "void Demo.Log(string format, params object[] args)",
documentation: null,
parameters: [[21, 27] as [number, number], [45, 49] as [number, number]],
};
const reply = (activeParameter: number) => ({
status: "ok" as const,
data: { signatures: [log], activeSignature: 0, activeParameter },
});
it("re-asks on `,`, keeps the params array bold for the arguments after it, and closes on `)`", async () => {
const view = new EditorView({
state: EditorState.create({
doc: "Log(",
selection: { anchor: 4 },
extensions: [
closeBrackets(),
lspDoc.of({ doc: 1, path: "/a.cs", language: "csharp", uiMode: null, readOnly: false }),
signatureExtension(),
],
}),
parent: document.body,
});
views.push(view);
const bold = () => view.dom.querySelector(".cm-lsp-signature b")?.textContent ?? null;
lspSignatureHelp.mockResolvedValueOnce(reply(0) as never);
triggerSignatureHelp(view, true);
await vi.waitFor(() => expect(bold()).toBe("format"));
const comma = async (active: number) => {
lspSignatureHelp.mockResolvedValueOnce(reply(active) as never);
typeChar(view, ",");
await vi.waitFor(() => expect(lspSignatureHelp).toHaveBeenCalledTimes(active + 1));
await vi.waitFor(() => expect(bold()).toBe("args"));
};
await comma(1);
await comma(2);
lspSignatureHelp.mockResolvedValueOnce({ status: "ok", data: null } as never);
typeChar(view, ")");
expect(view.state.doc.toString()).toBe("Log(,,)");
await vi.waitFor(() => expect(view.dom.querySelector(".cm-lsp-signature")).toBeNull());
});
it("takes any number of arguments in a `params` array, but not in an ordinary last parameter", () => {
expect(parameterAt(log, 5)).toBe(1);
expect(acceptsParameter(log, 5)).toBe(true);
// A parameter named `params` isn't the keyword.
const named = {
label: "f(a, params: object)",
parameters: [[2, 3] as [number, number], [5, 19] as [number, number]],
};
expect(parameterAt(named, 2)).toBe(2);
expect(acceptsParameter(named, 2)).toBe(false);
});
});
describe("acceptsParameter", () => {
it("rejects overloads with too few parameters unless the last is variadic", () => {
expect(acceptsParameter({ label: "println() : void", parameters: [] }, 0)).toBe(false);
+16 -6
Переглянути файл
@@ -50,13 +50,23 @@ export function splitSignature(label: string, params: ReadonlyArray<[number, num
return { before: label.slice(0, s), param: label.slice(s, e), after: label.slice(e) };
}
/** Whether an overload can take an argument at `index` (varargs take any number). */
export function acceptsParameter(sig: { label: string; parameters: ReadonlyArray<[number, number]> }, index: number) {
if (index < sig.parameters.length) return true;
const last = sig.parameters[sig.parameters.length - 1];
return !!last && /\.\.\.|^\s*\*/.test(sig.label.slice(last[0], last[1]));
type Sig = { label: string; parameters: ReadonlyArray<[number, number]> };
/**
* The parameter that takes argument `index`: a variadic last one (`...`, `*args`, C# `params`)
* takes all the rest. Roslyn counts arguments past it.
*/
export function parameterAt(sig: Sig, index: number) {
const last = sig.parameters.length - 1;
const range = sig.parameters[last];
if (index <= last || !range) return index;
const variadic = /\.\.\.|^\s*\*/.test(sig.label.slice(...range)) || /[([,]\s*params\s/.test(sig.label);
return variadic ? last : index;
}
/** Whether an overload can take an argument at `index`. */
export const acceptsParameter = (sig: Sig, index: number) => parameterAt(sig, index) < sig.parameters.length;
function signatureTooltip(s: SigState): Tooltip {
return {
pos: s.pos,
@@ -77,7 +87,7 @@ function signatureTooltip(s: SigState): Tooltip {
row.setAttribute("aria-current", "true");
active = row;
} else if (!acceptsParameter(sig, activeParameter)) row.classList.add("cm-lsp-signature-disabled");
const parts = splitSignature(sig.label, sig.parameters, activeParameter);
const parts = splitSignature(sig.label, sig.parameters, parameterAt(sig, activeParameter));
row.append(parts.before);
if (parts.param) {
const b = document.createElement("b");