Parameter inlay hint separate from variable type inlay? #2876

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
This commit is contained in:
Steffen Lyngbaek 2020-03-10 00:55:46 -07:00
parent 0714a065d5
commit e98aff109a
13 changed files with 155 additions and 34 deletions

1
Cargo.lock generated
View file

@ -1028,6 +1028,7 @@ dependencies = [
"ra_hir",
"ra_ide_db",
"ra_prof",
"ra_project_model",
"ra_syntax",
"ra_text_edit",
"rand",

View file

@ -21,6 +21,7 @@ rustc-hash = "1.1.0"
rand = { version = "0.7.3", features = ["small_rng"] }
ra_syntax = { path = "../ra_syntax" }
ra_project_model = { path = "../ra_project_model" }
ra_text_edit = { path = "../ra_text_edit" }
ra_db = { path = "../ra_db" }
ra_ide_db = { path = "../ra_ide_db" }

View file

@ -3,6 +3,7 @@
use hir::{Adt, HirDisplay, Semantics, Type};
use ra_ide_db::RootDatabase;
use ra_prof::profile;
use ra_project_model::{InlayHintDisplayType, InlayHintOptions};
use ra_syntax::{
ast::{self, ArgListOwner, AstNode, TypeAscriptionOwner},
match_ast, SmolStr, TextRange,
@ -26,7 +27,7 @@ pub struct InlayHint {
pub(crate) fn inlay_hints(
db: &RootDatabase,
file_id: FileId,
max_inlay_hint_length: Option<usize>,
inlay_hint_opts: &InlayHintOptions,
) -> Vec<InlayHint> {
let _p = profile("inlay_hints");
let sema = Semantics::new(db);
@ -36,9 +37,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 +50,14 @@ pub(crate) fn inlay_hints(
fn get_param_name_hints(
acc: &mut Vec<InlayHint>,
sema: &Semantics<RootDatabase>,
inlay_hint_opts: &InlayHintOptions,
expr: ast::Expr,
) -> Option<()> {
match inlay_hint_opts.display_type {
InlayHintDisplayType::Off | InlayHintDisplayType::TypeHints => return None,
_ => {}
}
let args = match &expr {
ast::Expr::CallExpr(expr) => expr.arg_list()?.args(),
ast::Expr::MethodCallExpr(expr) => expr.arg_list()?.args(),
@ -84,9 +91,14 @@ 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: &InlayHintOptions,
pat: ast::BindPat,
) -> Option<()> {
match inlay_hint_opts.display_type {
InlayHintDisplayType::Off | InlayHintDisplayType::ParameterHints => return None,
_ => {}
}
let ty = sema.type_of_pat(&pat.clone().into())?;
if should_not_display_type_hint(sema.db, &pat, &ty) {
@ -96,7 +108,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(())
}
@ -205,7 +217,62 @@ mod tests {
use insta::assert_debug_snapshot;
use crate::mock_analysis::single_file;
use ra_project_model::{InlayHintDisplayType, InlayHintOptions};
#[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, &InlayHintOptions{ display_type: InlayHintDisplayType::ParameterHints, 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, &InlayHintOptions{ display_type: InlayHintDisplayType::Off, 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, &InlayHintOptions{ display_type: InlayHintDisplayType::TypeHints, 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 +288,7 @@ fn main() {
}"#,
);
assert_debug_snapshot!(analysis.inlay_hints(file_id, None).unwrap(), @r###"
assert_debug_snapshot!(analysis.inlay_hints(file_id, &InlayHintOptions::new(None)).unwrap(), @r###"
[
InlayHint {
range: [69; 71),
@ -278,7 +345,7 @@ fn main() {
}"#,
);
assert_debug_snapshot!(analysis.inlay_hints(file_id, None).unwrap(), @r###"
assert_debug_snapshot!(analysis.inlay_hints(file_id, &InlayHintOptions::new(None)).unwrap(), @r###"
[
InlayHint {
range: [193; 197),
@ -358,7 +425,7 @@ fn main() {
}"#,
);
assert_debug_snapshot!(analysis.inlay_hints(file_id, None).unwrap(), @r###"
assert_debug_snapshot!(analysis.inlay_hints(file_id, &InlayHintOptions::new(None)).unwrap(), @r###"
[
InlayHint {
range: [21; 30),
@ -422,7 +489,7 @@ fn main() {
}"#,
);
assert_debug_snapshot!(analysis.inlay_hints(file_id, None).unwrap(), @r###"
assert_debug_snapshot!(analysis.inlay_hints(file_id, &InlayHintOptions::new(None)).unwrap(), @r###"
[
InlayHint {
range: [21; 30),
@ -472,7 +539,7 @@ fn main() {
}"#,
);
assert_debug_snapshot!(analysis.inlay_hints(file_id, None).unwrap(), @r###"
assert_debug_snapshot!(analysis.inlay_hints(file_id, &InlayHintOptions::new(None)).unwrap(), @r###"
[
InlayHint {
range: [188; 192),
@ -567,7 +634,7 @@ fn main() {
}"#,
);
assert_debug_snapshot!(analysis.inlay_hints(file_id, None).unwrap(), @r###"
assert_debug_snapshot!(analysis.inlay_hints(file_id, &InlayHintOptions::new(None)).unwrap(), @r###"
[
InlayHint {
range: [188; 192),
@ -662,7 +729,7 @@ fn main() {
}"#,
);
assert_debug_snapshot!(analysis.inlay_hints(file_id, None).unwrap(), @r###"
assert_debug_snapshot!(analysis.inlay_hints(file_id, &InlayHintOptions::new(None)).unwrap(), @r###"
[
InlayHint {
range: [252; 256),
@ -734,7 +801,7 @@ fn main() {
}"#,
);
assert_debug_snapshot!(analysis.inlay_hints(file_id, Some(8)).unwrap(), @r###"
assert_debug_snapshot!(analysis.inlay_hints(file_id, &InlayHintOptions::new(Some(8))).unwrap(), @r###"
[
InlayHint {
range: [74; 75),
@ -822,7 +889,7 @@ fn main() {
}"#,
);
assert_debug_snapshot!(analysis.inlay_hints(file_id, None).unwrap(), @r###"
assert_debug_snapshot!(analysis.inlay_hints(file_id, &InlayHintOptions::new(None)).unwrap(), @r###"
[
InlayHint {
range: [798; 809),
@ -944,7 +1011,7 @@ fn main() {
}"#,
);
assert_debug_snapshot!(analysis.inlay_hints(file_id, Some(8)).unwrap(), @r###"
assert_debug_snapshot!(analysis.inlay_hints(file_id, &InlayHintOptions::new(Some(8))).unwrap(), @r###"
[]
"###
);
@ -970,7 +1037,7 @@ fn main() {
}"#,
);
assert_debug_snapshot!(analysis.inlay_hints(file_id, Some(8)).unwrap(), @r###"
assert_debug_snapshot!(analysis.inlay_hints(file_id, &InlayHintOptions::new(Some(8))).unwrap(), @r###"
[]
"###
);

View file

@ -44,6 +44,7 @@ mod marks;
#[cfg(test)]
mod test_utils;
use ra_project_model::InlayHintOptions;
use std::sync::Arc;
use ra_cfg::CfgOptions;
@ -318,9 +319,9 @@ impl Analysis {
pub fn inlay_hints(
&self,
file_id: FileId,
max_inlay_hint_length: Option<usize>,
inlay_hint_opts: &InlayHintOptions,
) -> 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

@ -16,6 +16,7 @@ use anyhow::{bail, Context, Result};
use ra_cfg::CfgOptions;
use ra_db::{CrateGraph, CrateName, Edition, Env, FileId};
use rustc_hash::FxHashMap;
use serde::Deserialize;
use serde_json::from_reader;
pub use crate::{
@ -24,6 +25,34 @@ pub use crate::{
sysroot::Sysroot,
};
#[derive(Deserialize, Clone, Debug, PartialEq, Eq)]
#[serde(rename_all = "lowercase")]
pub enum InlayHintDisplayType {
Off,
TypeHints,
ParameterHints,
Full,
}
#[derive(Deserialize, Clone, Debug, PartialEq, Eq)]
#[serde(rename_all = "camelCase", default)]
pub struct InlayHintOptions {
pub display_type: InlayHintDisplayType,
pub max_length: Option<usize>,
}
impl InlayHintOptions {
pub fn new(max_length: Option<usize>) -> Self {
Self { display_type: InlayHintDisplayType::Full, max_length }
}
}
impl Default for InlayHintOptions {
fn default() -> Self {
Self { display_type: InlayHintDisplayType::Full, max_length: None }
}
}
#[derive(Clone, PartialEq, Eq, Hash, Debug)]
pub struct CargoTomlNotFoundError {
pub searched_at: PathBuf,

View file

@ -7,6 +7,7 @@
//! configure the server itself, feature flags are passed into analysis, and
//! tweak things like automatic insertion of `()` in completions.
use ra_project_model::InlayHintOptions;
use rustc_hash::FxHashMap;
use ra_project_model::CargoFeatures;
@ -30,7 +31,7 @@ pub struct ServerConfig {
pub lru_capacity: Option<usize>,
pub max_inlay_hint_length: Option<usize>,
pub inlay_hint_opts: InlayHintOptions,
pub cargo_watch_enable: bool,
pub cargo_watch_args: Vec<String>,
@ -57,7 +58,7 @@ impl Default for ServerConfig {
exclude_globs: Vec::new(),
use_client_watching: false,
lru_capacity: None,
max_inlay_hint_length: None,
inlay_hint_opts: 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_hint_opts: config.inlay_hint_opts.clone(),
cargo_watch: CheckOptions {
enable: config.cargo_watch_enable,
args: config.cargo_watch_args,

View file

@ -15,7 +15,7 @@ use ra_cargo_watch::{url_from_path_with_drive_lowercasing, CheckOptions, CheckWa
use ra_ide::{
Analysis, AnalysisChange, AnalysisHost, CrateGraph, FileId, LibraryData, SourceRootId,
};
use ra_project_model::{get_rustc_cfg_options, ProjectWorkspace};
use ra_project_model::{get_rustc_cfg_options, InlayHintOptions, ProjectWorkspace};
use ra_vfs::{LineEndings, RootEntry, Vfs, VfsChange, VfsFile, VfsRoot, VfsTask, Watch};
use relative_path::RelativePathBuf;
@ -32,7 +32,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_hint_opts: InlayHintOptions,
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

@ -307,12 +307,24 @@
"exclusiveMinimum": true,
"description": "Number of syntax trees rust-analyzer keeps in memory"
},
"rust-analyzer.displayInlayHints": {
"type": "boolean",
"default": true,
"rust-analyzer.inlayHintOpts.displayType": {
"type": "string",
"enum": [
"off",
"typeHints",
"parameterHints",
"full"
],
"enumDescriptions": [
"No type inlay hints",
"Type inlays hints only",
"Parameter inlays hints only",
"All inlay hints types"
],
"default": "full",
"description": "Display additional type and parameter information in the editor"
},
"rust-analyzer.maxInlayHintLength": {
"rust-analyzer.inlayHintOpts.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,
inlayHintOpts: config.inlayHintOpts,
cargoWatchEnable: cargoWatchOpts.enable,
cargoWatchArgs: cargoWatchOpts.arguments,
cargoWatchCommand: cargoWatchOpts.command,

View file

@ -5,6 +5,11 @@ import { log } from "./util";
const RA_LSP_DEBUG = process.env.__RA_LSP_SERVER_DEBUG;
export interface InlayHintOptions {
displayType: string;
maxLength: number;
}
export interface CargoWatchOptions {
enable: boolean;
arguments: string[];
@ -149,8 +154,12 @@ 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 inlayHintOpts(): InlayHintOptions {
return {
displayType: this.cfg.get("inlayHintOpts.displayType") as string,
maxLength: this.cfg.get("inlayHintOpts.maxLength") as 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.inlayHintOpts.displayType === 'off') {
return this.dispose();
}
if (!this.updater) this.updater = new HintsUpdater(ctx);