3543: Parameter inlay hint separate from variable type inlay? #2876 r=matklad a=slyngbaek

Add setting to allow enabling either type inlay hints or parameter
inlay hints or both. Group the the max inlay hint length option
into the object.

- Add a new type for the inlayHint options.
- Add tests to ensure the inlays don't happen on the server side

Co-authored-by: Steffen Lyngbaek <steffenlyngbaek@gmail.com>
This commit is contained in:
bors[bot] 2020-03-12 16:02:55 +00:00 committed by GitHub
commit d98a5fab46
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
12 changed files with 150 additions and 43 deletions

View file

@ -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<usize>,
}
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<usize>,
inlay_hint_opts: &InlayConfig,
) -> Vec<InlayHint> {
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<InlayHint>,
sema: &Semantics<RootDatabase>,
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<InlayHint>,
sema: &Semantics<RootDatabase>,
max_inlay_hint_length: Option<usize>,
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<RootDatabase>, 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###"
[]
"###
);

View file

@ -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<usize>,
inlay_hint_opts: &InlayConfig,
) -> Cancelable<Vec<InlayHint>> {
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.

View file

@ -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<usize>,
pub max_inlay_hint_length: Option<usize>,
#[serde(with = "InlayConfigDef")]
pub inlay_hints: InlayConfig,
pub cargo_watch_enable: bool,
pub cargo_watch_args: Vec<String>,
@ -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(),

View file

@ -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,

View file

@ -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())
}

View file

@ -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<usize>,
}
#[derive(Debug, Deserialize, Serialize)]
pub struct InlayHint {
pub range: Range,
#[serde(with = "InlayKindDef")]
pub kind: InlayKind,
pub label: String,
}

View file

@ -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<usize>,
pub inlay_hints: InlayConfig,
pub rustfmt_args: Vec<String>,
pub cargo_watch: CheckOptions,
}

View file

@ -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:

View file

@ -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"

View file

@ -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,

View file

@ -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<string, boolean>; }

View file

@ -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);