diff --git a/crates/ra_ide/src/inlay_hints.rs b/crates/ra_ide/src/inlay_hints.rs index cf0cbdbd02..59922e14c4 100644 --- a/crates/ra_ide/src/inlay_hints.rs +++ b/crates/ra_ide/src/inlay_hints.rs @@ -10,7 +10,20 @@ use ra_syntax::{ use crate::{FileId, FunctionSignature}; -#[derive(Debug, PartialEq, Eq)] +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct InlayConfig { + pub type_hints: bool, + pub parameter_hints: bool, + pub max_length: Option, +} + +impl Default for InlayConfig { + fn default() -> Self { + Self { type_hints: true, parameter_hints: true, max_length: None } + } +} + +#[derive(Clone, Debug, PartialEq, Eq)] pub enum InlayKind { TypeHint, ParameterHint, @@ -26,7 +39,7 @@ pub struct InlayHint { pub(crate) fn inlay_hints( db: &RootDatabase, file_id: FileId, - max_inlay_hint_length: Option, + inlay_hint_opts: &InlayConfig, ) -> Vec { let _p = profile("inlay_hints"); let sema = Semantics::new(db); @@ -36,9 +49,9 @@ pub(crate) fn inlay_hints( for node in file.syntax().descendants() { match_ast! { match node { - ast::CallExpr(it) => { get_param_name_hints(&mut res, &sema, ast::Expr::from(it)); }, - ast::MethodCallExpr(it) => { get_param_name_hints(&mut res, &sema, ast::Expr::from(it)); }, - ast::BindPat(it) => { get_bind_pat_hints(&mut res, &sema, max_inlay_hint_length, it); }, + ast::CallExpr(it) => { get_param_name_hints(&mut res, &sema, inlay_hint_opts, ast::Expr::from(it)); }, + ast::MethodCallExpr(it) => { get_param_name_hints(&mut res, &sema, inlay_hint_opts, ast::Expr::from(it)); }, + ast::BindPat(it) => { get_bind_pat_hints(&mut res, &sema, inlay_hint_opts, it); }, _ => (), } } @@ -49,8 +62,13 @@ pub(crate) fn inlay_hints( fn get_param_name_hints( acc: &mut Vec, sema: &Semantics, + inlay_hint_opts: &InlayConfig, expr: ast::Expr, ) -> Option<()> { + if !inlay_hint_opts.parameter_hints { + return None; + } + let args = match &expr { ast::Expr::CallExpr(expr) => expr.arg_list()?.args(), ast::Expr::MethodCallExpr(expr) => expr.arg_list()?.args(), @@ -84,9 +102,13 @@ fn get_param_name_hints( fn get_bind_pat_hints( acc: &mut Vec, sema: &Semantics, - max_inlay_hint_length: Option, + inlay_hint_opts: &InlayConfig, pat: ast::BindPat, ) -> Option<()> { + if !inlay_hint_opts.type_hints { + return None; + } + let ty = sema.type_of_pat(&pat.clone().into())?; if should_not_display_type_hint(sema.db, &pat, &ty) { @@ -96,7 +118,7 @@ fn get_bind_pat_hints( acc.push(InlayHint { range: pat.syntax().text_range(), kind: InlayKind::TypeHint, - label: ty.display_truncated(sema.db, max_inlay_hint_length).to_string().into(), + label: ty.display_truncated(sema.db, inlay_hint_opts.max_length).to_string().into(), }); Some(()) } @@ -202,10 +224,65 @@ fn get_fn_signature(sema: &Semantics, expr: &ast::Expr) -> Option< #[cfg(test)] mod tests { + use crate::inlay_hints::InlayConfig; use insta::assert_debug_snapshot; use crate::mock_analysis::single_file; + #[test] + fn param_hints_only() { + let (analysis, file_id) = single_file( + r#" + fn foo(a: i32, b: i32) -> i32 { a + b } + fn main() { + let _x = foo(4, 4); + }"#, + ); + assert_debug_snapshot!(analysis.inlay_hints(file_id, &InlayConfig{ parameter_hints: true, type_hints: false, max_length: None}).unwrap(), @r###" + [ + InlayHint { + range: [106; 107), + kind: ParameterHint, + label: "a", + }, + InlayHint { + range: [109; 110), + kind: ParameterHint, + label: "b", + }, + ]"###); + } + + #[test] + fn hints_disabled() { + let (analysis, file_id) = single_file( + r#" + fn foo(a: i32, b: i32) -> i32 { a + b } + fn main() { + let _x = foo(4, 4); + }"#, + ); + assert_debug_snapshot!(analysis.inlay_hints(file_id, &InlayConfig{ type_hints: false, parameter_hints: false, max_length: None}).unwrap(), @r###"[]"###); + } + + #[test] + fn type_hints_only() { + let (analysis, file_id) = single_file( + r#" + fn foo(a: i32, b: i32) -> i32 { a + b } + fn main() { + let _x = foo(4, 4); + }"#, + ); + assert_debug_snapshot!(analysis.inlay_hints(file_id, &InlayConfig{ type_hints: true, parameter_hints: false, max_length: None}).unwrap(), @r###" + [ + InlayHint { + range: [97; 99), + kind: TypeHint, + label: "i32", + }, + ]"###); + } #[test] fn default_generic_types_should_not_be_displayed() { let (analysis, file_id) = single_file( @@ -221,7 +298,7 @@ fn main() { }"#, ); - assert_debug_snapshot!(analysis.inlay_hints(file_id, None).unwrap(), @r###" + assert_debug_snapshot!(analysis.inlay_hints(file_id, &InlayConfig::default()).unwrap(), @r###" [ InlayHint { range: [69; 71), @@ -278,7 +355,7 @@ fn main() { }"#, ); - assert_debug_snapshot!(analysis.inlay_hints(file_id, None).unwrap(), @r###" + assert_debug_snapshot!(analysis.inlay_hints(file_id, &InlayConfig::default()).unwrap(), @r###" [ InlayHint { range: [193; 197), @@ -358,7 +435,7 @@ fn main() { }"#, ); - assert_debug_snapshot!(analysis.inlay_hints(file_id, None).unwrap(), @r###" + assert_debug_snapshot!(analysis.inlay_hints(file_id, &InlayConfig::default()).unwrap(), @r###" [ InlayHint { range: [21; 30), @@ -422,7 +499,7 @@ fn main() { }"#, ); - assert_debug_snapshot!(analysis.inlay_hints(file_id, None).unwrap(), @r###" + assert_debug_snapshot!(analysis.inlay_hints(file_id, &InlayConfig::default()).unwrap(), @r###" [ InlayHint { range: [21; 30), @@ -472,7 +549,7 @@ fn main() { }"#, ); - assert_debug_snapshot!(analysis.inlay_hints(file_id, None).unwrap(), @r###" + assert_debug_snapshot!(analysis.inlay_hints(file_id, &InlayConfig::default()).unwrap(), @r###" [ InlayHint { range: [188; 192), @@ -567,7 +644,7 @@ fn main() { }"#, ); - assert_debug_snapshot!(analysis.inlay_hints(file_id, None).unwrap(), @r###" + assert_debug_snapshot!(analysis.inlay_hints(file_id, &InlayConfig::default()).unwrap(), @r###" [ InlayHint { range: [188; 192), @@ -662,7 +739,7 @@ fn main() { }"#, ); - assert_debug_snapshot!(analysis.inlay_hints(file_id, None).unwrap(), @r###" + assert_debug_snapshot!(analysis.inlay_hints(file_id, &InlayConfig::default()).unwrap(), @r###" [ InlayHint { range: [252; 256), @@ -734,7 +811,7 @@ fn main() { }"#, ); - assert_debug_snapshot!(analysis.inlay_hints(file_id, Some(8)).unwrap(), @r###" + assert_debug_snapshot!(analysis.inlay_hints(file_id, &InlayConfig { max_length: Some(8), ..Default::default() }).unwrap(), @r###" [ InlayHint { range: [74; 75), @@ -822,7 +899,7 @@ fn main() { }"#, ); - assert_debug_snapshot!(analysis.inlay_hints(file_id, None).unwrap(), @r###" + assert_debug_snapshot!(analysis.inlay_hints(file_id, &InlayConfig::default()).unwrap(), @r###" [ InlayHint { range: [798; 809), @@ -944,7 +1021,7 @@ fn main() { }"#, ); - assert_debug_snapshot!(analysis.inlay_hints(file_id, Some(8)).unwrap(), @r###" + assert_debug_snapshot!(analysis.inlay_hints(file_id, &InlayConfig { max_length: Some(8), ..Default::default() }).unwrap(), @r###" [] "### ); @@ -970,7 +1047,7 @@ fn main() { }"#, ); - assert_debug_snapshot!(analysis.inlay_hints(file_id, Some(8)).unwrap(), @r###" + assert_debug_snapshot!(analysis.inlay_hints(file_id, &InlayConfig { max_length: Some(8), ..Default::default() }).unwrap(), @r###" [] "### ); diff --git a/crates/ra_ide/src/lib.rs b/crates/ra_ide/src/lib.rs index 015fae1956..922e4caa8a 100644 --- a/crates/ra_ide/src/lib.rs +++ b/crates/ra_ide/src/lib.rs @@ -68,7 +68,7 @@ pub use crate::{ expand_macro::ExpandedMacro, folding_ranges::{Fold, FoldKind}, hover::HoverResult, - inlay_hints::{InlayHint, InlayKind}, + inlay_hints::{InlayConfig, InlayHint, InlayKind}, references::{Declaration, Reference, ReferenceAccess, ReferenceKind, ReferenceSearchResult}, runnables::{Runnable, RunnableKind, TestId}, source_change::{FileSystemEdit, SourceChange, SourceFileEdit}, @@ -319,9 +319,9 @@ impl Analysis { pub fn inlay_hints( &self, file_id: FileId, - max_inlay_hint_length: Option, + inlay_hint_opts: &InlayConfig, ) -> Cancelable> { - self.with_db(|db| inlay_hints::inlay_hints(db, file_id, max_inlay_hint_length)) + self.with_db(|db| inlay_hints::inlay_hints(db, file_id, inlay_hint_opts)) } /// Returns the set of folding ranges. diff --git a/crates/rust-analyzer/src/config.rs b/crates/rust-analyzer/src/config.rs index a8bf29ddf0..bd5904db00 100644 --- a/crates/rust-analyzer/src/config.rs +++ b/crates/rust-analyzer/src/config.rs @@ -7,6 +7,8 @@ //! configure the server itself, feature flags are passed into analysis, and //! tweak things like automatic insertion of `()` in completions. +use crate::req::InlayConfigDef; +use ra_ide::InlayConfig; use rustc_hash::FxHashMap; use ra_project_model::CargoFeatures; @@ -30,7 +32,8 @@ pub struct ServerConfig { pub lru_capacity: Option, - pub max_inlay_hint_length: Option, + #[serde(with = "InlayConfigDef")] + pub inlay_hints: InlayConfig, pub cargo_watch_enable: bool, pub cargo_watch_args: Vec, @@ -60,7 +63,7 @@ impl Default for ServerConfig { exclude_globs: Vec::new(), use_client_watching: false, lru_capacity: None, - max_inlay_hint_length: None, + inlay_hints: Default::default(), cargo_watch_enable: true, cargo_watch_args: Vec::new(), cargo_watch_command: "check".to_string(), diff --git a/crates/rust-analyzer/src/main_loop.rs b/crates/rust-analyzer/src/main_loop.rs index 4f7aac7540..495056da3e 100644 --- a/crates/rust-analyzer/src/main_loop.rs +++ b/crates/rust-analyzer/src/main_loop.rs @@ -177,7 +177,7 @@ pub fn main_loop( .and_then(|it| it.folding_range.as_ref()) .and_then(|it| it.line_folding_only) .unwrap_or(false), - max_inlay_hint_length: config.max_inlay_hint_length, + inlay_hints: config.inlay_hints, cargo_watch: CheckOptions { enable: config.cargo_watch_enable, args: config.cargo_watch_args, diff --git a/crates/rust-analyzer/src/main_loop/handlers.rs b/crates/rust-analyzer/src/main_loop/handlers.rs index fcb40432d4..921990da03 100644 --- a/crates/rust-analyzer/src/main_loop/handlers.rs +++ b/crates/rust-analyzer/src/main_loop/handlers.rs @@ -37,7 +37,7 @@ use crate::{ }, diagnostics::DiagnosticTask, from_json, - req::{self, Decoration, InlayHint, InlayHintsParams, InlayKind}, + req::{self, Decoration, InlayHint, InlayHintsParams}, semantic_tokens::SemanticTokensBuilder, world::WorldSnapshot, LspError, Result, @@ -997,15 +997,12 @@ pub fn handle_inlay_hints( let analysis = world.analysis(); let line_index = analysis.file_line_index(file_id)?; Ok(analysis - .inlay_hints(file_id, world.options.max_inlay_hint_length)? + .inlay_hints(file_id, &world.options.inlay_hints)? .into_iter() .map(|api_type| InlayHint { label: api_type.label.to_string(), range: api_type.range.conv_with(&line_index), - kind: match api_type.kind { - ra_ide::InlayKind::TypeHint => InlayKind::TypeHint, - ra_ide::InlayKind::ParameterHint => InlayKind::ParameterHint, - }, + kind: api_type.kind, }) .collect()) } diff --git a/crates/rust-analyzer/src/req.rs b/crates/rust-analyzer/src/req.rs index a3efe3b9fe..1dcab2703e 100644 --- a/crates/rust-analyzer/src/req.rs +++ b/crates/rust-analyzer/src/req.rs @@ -4,6 +4,8 @@ use lsp_types::{Location, Position, Range, TextDocumentIdentifier, Url}; use rustc_hash::FxHashMap; use serde::{Deserialize, Serialize}; +use ra_ide::{InlayConfig, InlayKind}; + pub use lsp_types::{ notification::*, request::*, ApplyWorkspaceEditParams, CodeActionParams, CodeLens, CodeLensParams, CompletionParams, CompletionResponse, DiagnosticTag, @@ -196,14 +198,24 @@ pub struct InlayHintsParams { } #[derive(Debug, PartialEq, Eq, Deserialize, Serialize)] -pub enum InlayKind { +#[serde(remote = "InlayKind")] +pub enum InlayKindDef { TypeHint, ParameterHint, } +#[derive(Deserialize)] +#[serde(remote = "InlayConfig", rename_all = "camelCase")] +pub struct InlayConfigDef { + pub type_hints: bool, + pub parameter_hints: bool, + pub max_length: Option, +} + #[derive(Debug, Deserialize, Serialize)] pub struct InlayHint { pub range: Range, + #[serde(with = "InlayKindDef")] pub kind: InlayKind, pub label: String, } diff --git a/crates/rust-analyzer/src/world.rs b/crates/rust-analyzer/src/world.rs index 9ef368529e..d358f6b479 100644 --- a/crates/rust-analyzer/src/world.rs +++ b/crates/rust-analyzer/src/world.rs @@ -13,7 +13,8 @@ use lsp_types::Url; use parking_lot::RwLock; use ra_cargo_watch::{url_from_path_with_drive_lowercasing, CheckOptions, CheckWatcher}; use ra_ide::{ - Analysis, AnalysisChange, AnalysisHost, CrateGraph, FileId, LibraryData, SourceRootId, + Analysis, AnalysisChange, AnalysisHost, CrateGraph, FileId, InlayConfig, LibraryData, + SourceRootId, }; use ra_project_model::{get_rustc_cfg_options, ProjectWorkspace}; use ra_vfs::{LineEndings, RootEntry, Vfs, VfsChange, VfsFile, VfsRoot, VfsTask, Watch}; @@ -34,7 +35,7 @@ pub struct Options { pub publish_decorations: bool, pub supports_location_link: bool, pub line_folding_only: bool, - pub max_inlay_hint_length: Option, + pub inlay_hints: InlayConfig, pub rustfmt_args: Vec, pub cargo_watch: CheckOptions, } diff --git a/docs/user/features.md b/docs/user/features.md index ba4d50fa80..06bc7ded55 100644 --- a/docs/user/features.md +++ b/docs/user/features.md @@ -191,8 +191,8 @@ Two types of inlay hints are displayed currently: In VS Code, the following settings can be used to configure the inlay hints: -* `rust-analyzer.displayInlayHints` — toggles inlay hints display on or off -* `rust-analyzer.maxInlayHintLength` — shortens the hints if their length exceeds the value specified. If no value is specified (`null`), no shortening is applied. +* `rust-analyzer.inlayHintOpts.displayType` configure which types of inlay hints are shown. +* `rust-analyzer.inlayHintOpts.maxLength` — shortens the hints if their length exceeds the value specified. If no value is specified (`null`), no shortening is applied. **Note:** VS Code does not have native support for inlay hints [yet](https://github.com/microsoft/vscode/issues/16221) and the hints are implemented using decorations. This approach has limitations, the caret movement and bracket highlighting near the edges of the hint may be weird: diff --git a/editors/code/package.json b/editors/code/package.json index 09dfc404db..3aaae357a9 100644 --- a/editors/code/package.json +++ b/editors/code/package.json @@ -312,12 +312,17 @@ "exclusiveMinimum": true, "description": "Number of syntax trees rust-analyzer keeps in memory" }, - "rust-analyzer.displayInlayHints": { + "rust-analyzer.inlayHints.typeHints": { "type": "boolean", "default": true, - "description": "Display additional type and parameter information in the editor" + "description": "Whether to show inlay type hints" }, - "rust-analyzer.maxInlayHintLength": { + "rust-analyzer.inlayHints.parameterHints": { + "type": "boolean", + "default": true, + "description": "Whether to show function parameter name inlay hints at the call site" + }, + "rust-analyzer.inlayHints.maxLength": { "type": [ "null", "integer" diff --git a/editors/code/src/client.ts b/editors/code/src/client.ts index 6ce3b9235c..e9f261c241 100644 --- a/editors/code/src/client.ts +++ b/editors/code/src/client.ts @@ -29,7 +29,7 @@ export async function createClient(config: Config, serverPath: string): Promise< initializationOptions: { publishDecorations: !config.highlightingSemanticTokens, lruCapacity: config.lruCapacity, - maxInlayHintLength: config.maxInlayHintLength, + inlayHints: config.inlayHints, cargoWatchEnable: cargoWatchOpts.enable, cargoWatchArgs: cargoWatchOpts.arguments, cargoWatchCommand: cargoWatchOpts.command, diff --git a/editors/code/src/config.ts b/editors/code/src/config.ts index 3ade7e900f..6db073bec0 100644 --- a/editors/code/src/config.ts +++ b/editors/code/src/config.ts @@ -5,6 +5,12 @@ import { log } from "./util"; const RA_LSP_DEBUG = process.env.__RA_LSP_SERVER_DEBUG; +export interface InlayHintOptions { + typeHints: boolean; + parameterHints: boolean; + maxLength: number | null; +} + export interface CargoWatchOptions { enable: boolean; arguments: string[]; @@ -22,7 +28,8 @@ export class Config { private static readonly requiresReloadOpts = [ "cargoFeatures", "cargo-watch", - "highlighting.semanticTokens" + "highlighting.semanticTokens", + "inlayHints", ] .map(opt => `${Config.rootSection}.${opt}`); @@ -149,8 +156,13 @@ export class Config { get highlightingOn() { return this.cfg.get("highlightingOn") as boolean; } get rainbowHighlightingOn() { return this.cfg.get("rainbowHighlightingOn") as boolean; } get lruCapacity() { return this.cfg.get("lruCapacity") as null | number; } - get displayInlayHints() { return this.cfg.get("displayInlayHints") as boolean; } - get maxInlayHintLength() { return this.cfg.get("maxInlayHintLength") as number; } + get inlayHints(): InlayHintOptions { + return { + typeHints: this.cfg.get("inlayHints.typeHints") as boolean, + parameterHints: this.cfg.get("inlayHints.parameterHints") as boolean, + maxLength: this.cfg.get("inlayHints.maxLength") as null | number, + }; + } get excludeGlobs() { return this.cfg.get("excludeGlobs") as string[]; } get useClientWatching() { return this.cfg.get("useClientWatching") as boolean; } get featureFlags() { return this.cfg.get("featureFlags") as Record; } diff --git a/editors/code/src/inlay_hints.ts b/editors/code/src/inlay_hints.ts index e1a82e03e8..b19b09ad56 100644 --- a/editors/code/src/inlay_hints.ts +++ b/editors/code/src/inlay_hints.ts @@ -10,7 +10,7 @@ export function activateInlayHints(ctx: Ctx) { const maybeUpdater = { updater: null as null | HintsUpdater, onConfigChange() { - if (!ctx.config.displayInlayHints) { + if (!ctx.config.inlayHints.typeHints && !ctx.config.inlayHints.parameterHints) { return this.dispose(); } if (!this.updater) this.updater = new HintsUpdater(ctx);