3790: Better names for config structs r=matklad a=matklad



bors r+
🤖

Co-authored-by: Aleksey Kladov <aleksey.kladov@gmail.com>
This commit is contained in:
bors[bot] 2020-03-31 14:06:03 +00:00 committed by GitHub
commit fa3c7742af
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
14 changed files with 142 additions and 128 deletions

View file

@ -22,7 +22,7 @@ use crate::conv::{map_rust_diagnostic_to_lsp, MappedRustDiagnostic};
pub use crate::conv::url_from_path_with_drive_lowercasing; pub use crate::conv::url_from_path_with_drive_lowercasing;
#[derive(Clone, Debug)] #[derive(Clone, Debug)]
pub struct CheckOptions { pub struct CheckConfig {
pub enable: bool, pub enable: bool,
pub args: Vec<String>, pub args: Vec<String>,
pub command: String, pub command: String,
@ -42,13 +42,11 @@ pub struct CheckWatcher {
} }
impl CheckWatcher { impl CheckWatcher {
pub fn new(options: &CheckOptions, workspace_root: PathBuf) -> CheckWatcher { pub fn new(config: CheckConfig, workspace_root: PathBuf) -> CheckWatcher {
let options = options.clone();
let (task_send, task_recv) = unbounded::<CheckTask>(); let (task_send, task_recv) = unbounded::<CheckTask>();
let (cmd_send, cmd_recv) = unbounded::<CheckCommand>(); let (cmd_send, cmd_recv) = unbounded::<CheckCommand>();
let handle = jod_thread::spawn(move || { let handle = jod_thread::spawn(move || {
let mut check = CheckWatcherThread::new(options, workspace_root); let mut check = CheckWatcherThread::new(config, workspace_root);
check.run(&task_send, &cmd_recv); check.run(&task_send, &cmd_recv);
}); });
CheckWatcher { task_recv, cmd_send, handle: Some(handle) } CheckWatcher { task_recv, cmd_send, handle: Some(handle) }
@ -78,14 +76,14 @@ pub enum CheckCommand {
} }
struct CheckWatcherThread { struct CheckWatcherThread {
options: CheckOptions, options: CheckConfig,
workspace_root: PathBuf, workspace_root: PathBuf,
watcher: WatchThread, watcher: WatchThread,
last_update_req: Option<Instant>, last_update_req: Option<Instant>,
} }
impl CheckWatcherThread { impl CheckWatcherThread {
fn new(options: CheckOptions, workspace_root: PathBuf) -> CheckWatcherThread { fn new(options: CheckConfig, workspace_root: PathBuf) -> CheckWatcherThread {
CheckWatcherThread { CheckWatcherThread {
options, options,
workspace_root, workspace_root,
@ -324,7 +322,7 @@ impl WatchThread {
WatchThread { message_recv: never(), _handle: None } WatchThread { message_recv: never(), _handle: None }
} }
fn new(options: &CheckOptions, workspace_root: &Path) -> WatchThread { fn new(options: &CheckConfig, workspace_root: &Path) -> WatchThread {
let mut args: Vec<String> = vec![ let mut args: Vec<String> = vec![
options.command.clone(), options.command.clone(),
"--workspace".to_string(), "--workspace".to_string(),

View file

@ -34,15 +34,15 @@ pub use crate::completion::completion_item::{
}; };
#[derive(Clone, Debug, PartialEq, Eq)] #[derive(Clone, Debug, PartialEq, Eq)]
pub struct CompletionOptions { pub struct CompletionConfig {
pub enable_postfix_completions: bool, pub enable_postfix_completions: bool,
pub add_call_parenthesis: bool, pub add_call_parenthesis: bool,
pub add_call_argument_snippets: bool, pub add_call_argument_snippets: bool,
} }
impl Default for CompletionOptions { impl Default for CompletionConfig {
fn default() -> Self { fn default() -> Self {
CompletionOptions { CompletionConfig {
enable_postfix_completions: true, enable_postfix_completions: true,
add_call_parenthesis: true, add_call_parenthesis: true,
add_call_argument_snippets: true, add_call_argument_snippets: true,
@ -75,9 +75,9 @@ impl Default for CompletionOptions {
pub(crate) fn completions( pub(crate) fn completions(
db: &RootDatabase, db: &RootDatabase,
position: FilePosition, position: FilePosition,
options: &CompletionOptions, config: &CompletionConfig,
) -> Option<Completions> { ) -> Option<Completions> {
let ctx = CompletionContext::new(db, position, options)?; let ctx = CompletionContext::new(db, position, config)?;
let mut acc = Completions::default(); let mut acc = Completions::default();

View file

@ -15,7 +15,7 @@ use crate::{
}; };
pub(super) fn complete_postfix(acc: &mut Completions, ctx: &CompletionContext) { pub(super) fn complete_postfix(acc: &mut Completions, ctx: &CompletionContext) {
if !ctx.options.enable_postfix_completions { if !ctx.config.enable_postfix_completions {
return; return;
} }

View file

@ -11,7 +11,7 @@ use ra_syntax::{
}; };
use ra_text_edit::AtomTextEdit; use ra_text_edit::AtomTextEdit;
use crate::{completion::CompletionOptions, FilePosition}; use crate::{completion::CompletionConfig, FilePosition};
/// `CompletionContext` is created early during completion to figure out, where /// `CompletionContext` is created early during completion to figure out, where
/// exactly is the cursor, syntax-wise. /// exactly is the cursor, syntax-wise.
@ -19,7 +19,7 @@ use crate::{completion::CompletionOptions, FilePosition};
pub(crate) struct CompletionContext<'a> { pub(crate) struct CompletionContext<'a> {
pub(super) sema: Semantics<'a, RootDatabase>, pub(super) sema: Semantics<'a, RootDatabase>,
pub(super) db: &'a RootDatabase, pub(super) db: &'a RootDatabase,
pub(super) options: &'a CompletionOptions, pub(super) config: &'a CompletionConfig,
pub(super) offset: TextUnit, pub(super) offset: TextUnit,
/// The token before the cursor, in the original file. /// The token before the cursor, in the original file.
pub(super) original_token: SyntaxToken, pub(super) original_token: SyntaxToken,
@ -61,7 +61,7 @@ impl<'a> CompletionContext<'a> {
pub(super) fn new( pub(super) fn new(
db: &'a RootDatabase, db: &'a RootDatabase,
position: FilePosition, position: FilePosition,
options: &'a CompletionOptions, config: &'a CompletionConfig,
) -> Option<CompletionContext<'a>> { ) -> Option<CompletionContext<'a>> {
let sema = Semantics::new(db); let sema = Semantics::new(db);
@ -85,7 +85,7 @@ impl<'a> CompletionContext<'a> {
let mut ctx = CompletionContext { let mut ctx = CompletionContext {
sema, sema,
db, db,
options, config,
original_token, original_token,
token, token,
offset: position.offset, offset: position.offset,

View file

@ -106,7 +106,7 @@ impl Completions {
}; };
// Add `<>` for generic types // Add `<>` for generic types
if ctx.is_path_type && !ctx.has_type_args && ctx.options.add_call_parenthesis { if ctx.is_path_type && !ctx.has_type_args && ctx.config.add_call_parenthesis {
let has_non_default_type_params = match resolution { let has_non_default_type_params = match resolution {
ScopeDef::ModuleDef(Adt(it)) => it.has_non_default_type_params(ctx.db), ScopeDef::ModuleDef(Adt(it)) => it.has_non_default_type_params(ctx.db),
ScopeDef::ModuleDef(TypeAlias(it)) => it.has_non_default_type_params(ctx.db), ScopeDef::ModuleDef(TypeAlias(it)) => it.has_non_default_type_params(ctx.db),
@ -211,14 +211,14 @@ impl Completions {
.detail(function_signature.to_string()); .detail(function_signature.to_string());
// If not an import, add parenthesis automatically. // If not an import, add parenthesis automatically.
if ctx.use_item_syntax.is_none() && !ctx.is_call && ctx.options.add_call_parenthesis { if ctx.use_item_syntax.is_none() && !ctx.is_call && ctx.config.add_call_parenthesis {
tested_by!(inserts_parens_for_function_calls); tested_by!(inserts_parens_for_function_calls);
let (snippet, label) = if params.is_empty() || has_self_param && params.len() == 1 { let (snippet, label) = if params.is_empty() || has_self_param && params.len() == 1 {
(format!("{}()$0", name), format!("{}()", name)) (format!("{}()$0", name), format!("{}()", name))
} else { } else {
builder = builder.trigger_call_info(); builder = builder.trigger_call_info();
let snippet = if ctx.options.add_call_argument_snippets { let snippet = if ctx.config.add_call_argument_snippets {
let to_skip = if has_self_param { 1 } else { 0 }; let to_skip = if has_self_param { 1 } else { 0 };
let function_params_snippet = function_signature let function_params_snippet = function_signature
.parameter_names .parameter_names
@ -311,7 +311,7 @@ mod tests {
use crate::completion::{ use crate::completion::{
test_utils::{do_completion, do_completion_with_options}, test_utils::{do_completion, do_completion_with_options},
CompletionItem, CompletionKind, CompletionOptions, CompletionConfig, CompletionItem, CompletionKind,
}; };
fn do_reference_completion(ra_fixture: &str) -> Vec<CompletionItem> { fn do_reference_completion(ra_fixture: &str) -> Vec<CompletionItem> {
@ -320,7 +320,7 @@ mod tests {
fn do_reference_completion_with_options( fn do_reference_completion_with_options(
ra_fixture: &str, ra_fixture: &str,
options: CompletionOptions, options: CompletionConfig,
) -> Vec<CompletionItem> { ) -> Vec<CompletionItem> {
do_completion_with_options(ra_fixture, CompletionKind::Reference, &options) do_completion_with_options(ra_fixture, CompletionKind::Reference, &options)
} }
@ -589,7 +589,7 @@ mod tests {
s.f<|> s.f<|>
} }
", ",
CompletionOptions { CompletionConfig {
add_call_argument_snippets: false, add_call_argument_snippets: false,
.. Default::default() .. Default::default()
} }

View file

@ -1,19 +1,19 @@
//! Runs completion for testing purposes. //! Runs completion for testing purposes.
use crate::{ use crate::{
completion::{completion_item::CompletionKind, CompletionOptions}, completion::{completion_item::CompletionKind, CompletionConfig},
mock_analysis::{analysis_and_position, single_file_with_position}, mock_analysis::{analysis_and_position, single_file_with_position},
CompletionItem, CompletionItem,
}; };
pub(crate) fn do_completion(code: &str, kind: CompletionKind) -> Vec<CompletionItem> { pub(crate) fn do_completion(code: &str, kind: CompletionKind) -> Vec<CompletionItem> {
do_completion_with_options(code, kind, &CompletionOptions::default()) do_completion_with_options(code, kind, &CompletionConfig::default())
} }
pub(crate) fn do_completion_with_options( pub(crate) fn do_completion_with_options(
code: &str, code: &str,
kind: CompletionKind, kind: CompletionKind,
options: &CompletionOptions, options: &CompletionConfig,
) -> Vec<CompletionItem> { ) -> Vec<CompletionItem> {
let (analysis, position) = if code.contains("//-") { let (analysis, position) = if code.contains("//-") {
analysis_and_position(code) analysis_and_position(code)

View file

@ -11,14 +11,14 @@ use ra_syntax::{
use crate::{FileId, FunctionSignature}; use crate::{FileId, FunctionSignature};
#[derive(Clone, Debug, PartialEq, Eq)] #[derive(Clone, Debug, PartialEq, Eq)]
pub struct InlayHintsOptions { pub struct InlayHintsConfig {
pub type_hints: bool, pub type_hints: bool,
pub parameter_hints: bool, pub parameter_hints: bool,
pub chaining_hints: bool, pub chaining_hints: bool,
pub max_length: Option<usize>, pub max_length: Option<usize>,
} }
impl Default for InlayHintsOptions { impl Default for InlayHintsConfig {
fn default() -> Self { fn default() -> Self {
Self { type_hints: true, parameter_hints: true, chaining_hints: true, max_length: None } Self { type_hints: true, parameter_hints: true, chaining_hints: true, max_length: None }
} }
@ -41,7 +41,7 @@ pub struct InlayHint {
pub(crate) fn inlay_hints( pub(crate) fn inlay_hints(
db: &RootDatabase, db: &RootDatabase,
file_id: FileId, file_id: FileId,
options: &InlayHintsOptions, config: &InlayHintsConfig,
) -> Vec<InlayHint> { ) -> Vec<InlayHint> {
let _p = profile("inlay_hints"); let _p = profile("inlay_hints");
let sema = Semantics::new(db); let sema = Semantics::new(db);
@ -50,14 +50,14 @@ pub(crate) fn inlay_hints(
let mut res = Vec::new(); let mut res = Vec::new();
for node in file.syntax().descendants() { for node in file.syntax().descendants() {
if let Some(expr) = ast::Expr::cast(node.clone()) { if let Some(expr) = ast::Expr::cast(node.clone()) {
get_chaining_hints(&mut res, &sema, options, expr); get_chaining_hints(&mut res, &sema, config, expr);
} }
match_ast! { match_ast! {
match node { match node {
ast::CallExpr(it) => { get_param_name_hints(&mut res, &sema, options, ast::Expr::from(it)); }, ast::CallExpr(it) => { get_param_name_hints(&mut res, &sema, config, ast::Expr::from(it)); },
ast::MethodCallExpr(it) => { get_param_name_hints(&mut res, &sema, options, ast::Expr::from(it)); }, ast::MethodCallExpr(it) => { get_param_name_hints(&mut res, &sema, config, ast::Expr::from(it)); },
ast::BindPat(it) => { get_bind_pat_hints(&mut res, &sema, options, it); }, ast::BindPat(it) => { get_bind_pat_hints(&mut res, &sema, config, it); },
_ => (), _ => (),
} }
} }
@ -68,10 +68,10 @@ pub(crate) fn inlay_hints(
fn get_chaining_hints( fn get_chaining_hints(
acc: &mut Vec<InlayHint>, acc: &mut Vec<InlayHint>,
sema: &Semantics<RootDatabase>, sema: &Semantics<RootDatabase>,
options: &InlayHintsOptions, config: &InlayHintsConfig,
expr: ast::Expr, expr: ast::Expr,
) -> Option<()> { ) -> Option<()> {
if !options.chaining_hints { if !config.chaining_hints {
return None; return None;
} }
@ -95,7 +95,7 @@ fn get_chaining_hints(
let next = tokens.next()?.kind(); let next = tokens.next()?.kind();
let next_next = tokens.next()?.kind(); let next_next = tokens.next()?.kind();
if next == SyntaxKind::WHITESPACE && next_next == SyntaxKind::DOT { if next == SyntaxKind::WHITESPACE && next_next == SyntaxKind::DOT {
let label = ty.display_truncated(sema.db, options.max_length).to_string(); let label = ty.display_truncated(sema.db, config.max_length).to_string();
acc.push(InlayHint { acc.push(InlayHint {
range: expr.syntax().text_range(), range: expr.syntax().text_range(),
kind: InlayKind::ChainingHint, kind: InlayKind::ChainingHint,
@ -108,10 +108,10 @@ fn get_chaining_hints(
fn get_param_name_hints( fn get_param_name_hints(
acc: &mut Vec<InlayHint>, acc: &mut Vec<InlayHint>,
sema: &Semantics<RootDatabase>, sema: &Semantics<RootDatabase>,
options: &InlayHintsOptions, config: &InlayHintsConfig,
expr: ast::Expr, expr: ast::Expr,
) -> Option<()> { ) -> Option<()> {
if !options.parameter_hints { if !config.parameter_hints {
return None; return None;
} }
@ -148,10 +148,10 @@ fn get_param_name_hints(
fn get_bind_pat_hints( fn get_bind_pat_hints(
acc: &mut Vec<InlayHint>, acc: &mut Vec<InlayHint>,
sema: &Semantics<RootDatabase>, sema: &Semantics<RootDatabase>,
options: &InlayHintsOptions, config: &InlayHintsConfig,
pat: ast::BindPat, pat: ast::BindPat,
) -> Option<()> { ) -> Option<()> {
if !options.type_hints { if !config.type_hints {
return None; return None;
} }
@ -164,7 +164,7 @@ fn get_bind_pat_hints(
acc.push(InlayHint { acc.push(InlayHint {
range: pat.syntax().text_range(), range: pat.syntax().text_range(),
kind: InlayKind::TypeHint, kind: InlayKind::TypeHint,
label: ty.display_truncated(sema.db, options.max_length).to_string().into(), label: ty.display_truncated(sema.db, config.max_length).to_string().into(),
}); });
Some(()) Some(())
} }
@ -270,7 +270,7 @@ fn get_fn_signature(sema: &Semantics<RootDatabase>, expr: &ast::Expr) -> Option<
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use crate::inlay_hints::InlayHintsOptions; use crate::inlay_hints::InlayHintsConfig;
use insta::assert_debug_snapshot; use insta::assert_debug_snapshot;
use crate::mock_analysis::single_file; use crate::mock_analysis::single_file;
@ -284,7 +284,7 @@ mod tests {
let _x = foo(4, 4); let _x = foo(4, 4);
}"#, }"#,
); );
assert_debug_snapshot!(analysis.inlay_hints(file_id, &InlayHintsOptions{ parameter_hints: true, type_hints: false, chaining_hints: false, max_length: None}).unwrap(), @r###" assert_debug_snapshot!(analysis.inlay_hints(file_id, &InlayHintsConfig{ parameter_hints: true, type_hints: false, chaining_hints: false, max_length: None}).unwrap(), @r###"
[ [
InlayHint { InlayHint {
range: [106; 107), range: [106; 107),
@ -308,7 +308,7 @@ mod tests {
let _x = foo(4, 4); let _x = foo(4, 4);
}"#, }"#,
); );
assert_debug_snapshot!(analysis.inlay_hints(file_id, &InlayHintsOptions{ type_hints: false, parameter_hints: false, chaining_hints: false, max_length: None}).unwrap(), @r###"[]"###); assert_debug_snapshot!(analysis.inlay_hints(file_id, &InlayHintsConfig{ type_hints: false, parameter_hints: false, chaining_hints: false, max_length: None}).unwrap(), @r###"[]"###);
} }
#[test] #[test]
@ -320,7 +320,7 @@ mod tests {
let _x = foo(4, 4); let _x = foo(4, 4);
}"#, }"#,
); );
assert_debug_snapshot!(analysis.inlay_hints(file_id, &InlayHintsOptions{ type_hints: true, parameter_hints: false, chaining_hints: false, max_length: None}).unwrap(), @r###" assert_debug_snapshot!(analysis.inlay_hints(file_id, &InlayHintsConfig{ type_hints: true, parameter_hints: false, chaining_hints: false, max_length: None}).unwrap(), @r###"
[ [
InlayHint { InlayHint {
range: [97; 99), range: [97; 99),
@ -344,7 +344,7 @@ fn main() {
}"#, }"#,
); );
assert_debug_snapshot!(analysis.inlay_hints(file_id, &InlayHintsOptions::default()).unwrap(), @r###" assert_debug_snapshot!(analysis.inlay_hints(file_id, &InlayHintsConfig::default()).unwrap(), @r###"
[ [
InlayHint { InlayHint {
range: [69; 71), range: [69; 71),
@ -401,7 +401,7 @@ fn main() {
}"#, }"#,
); );
assert_debug_snapshot!(analysis.inlay_hints(file_id, &InlayHintsOptions::default()).unwrap(), @r###" assert_debug_snapshot!(analysis.inlay_hints(file_id, &InlayHintsConfig::default()).unwrap(), @r###"
[ [
InlayHint { InlayHint {
range: [193; 197), range: [193; 197),
@ -481,7 +481,7 @@ fn main() {
}"#, }"#,
); );
assert_debug_snapshot!(analysis.inlay_hints(file_id, &InlayHintsOptions::default()).unwrap(), @r###" assert_debug_snapshot!(analysis.inlay_hints(file_id, &InlayHintsConfig::default()).unwrap(), @r###"
[ [
InlayHint { InlayHint {
range: [21; 30), range: [21; 30),
@ -545,7 +545,7 @@ fn main() {
}"#, }"#,
); );
assert_debug_snapshot!(analysis.inlay_hints(file_id, &InlayHintsOptions::default()).unwrap(), @r###" assert_debug_snapshot!(analysis.inlay_hints(file_id, &InlayHintsConfig::default()).unwrap(), @r###"
[ [
InlayHint { InlayHint {
range: [21; 30), range: [21; 30),
@ -595,7 +595,7 @@ fn main() {
}"#, }"#,
); );
assert_debug_snapshot!(analysis.inlay_hints(file_id, &InlayHintsOptions::default()).unwrap(), @r###" assert_debug_snapshot!(analysis.inlay_hints(file_id, &InlayHintsConfig::default()).unwrap(), @r###"
[ [
InlayHint { InlayHint {
range: [188; 192), range: [188; 192),
@ -690,7 +690,7 @@ fn main() {
}"#, }"#,
); );
assert_debug_snapshot!(analysis.inlay_hints(file_id, &InlayHintsOptions::default()).unwrap(), @r###" assert_debug_snapshot!(analysis.inlay_hints(file_id, &InlayHintsConfig::default()).unwrap(), @r###"
[ [
InlayHint { InlayHint {
range: [188; 192), range: [188; 192),
@ -785,7 +785,7 @@ fn main() {
}"#, }"#,
); );
assert_debug_snapshot!(analysis.inlay_hints(file_id, &InlayHintsOptions::default()).unwrap(), @r###" assert_debug_snapshot!(analysis.inlay_hints(file_id, &InlayHintsConfig::default()).unwrap(), @r###"
[ [
InlayHint { InlayHint {
range: [252; 256), range: [252; 256),
@ -857,7 +857,7 @@ fn main() {
}"#, }"#,
); );
assert_debug_snapshot!(analysis.inlay_hints(file_id, &InlayHintsOptions { max_length: Some(8), ..Default::default() }).unwrap(), @r###" assert_debug_snapshot!(analysis.inlay_hints(file_id, &InlayHintsConfig { max_length: Some(8), ..Default::default() }).unwrap(), @r###"
[ [
InlayHint { InlayHint {
range: [74; 75), range: [74; 75),
@ -945,7 +945,7 @@ fn main() {
}"#, }"#,
); );
assert_debug_snapshot!(analysis.inlay_hints(file_id, &InlayHintsOptions::default()).unwrap(), @r###" assert_debug_snapshot!(analysis.inlay_hints(file_id, &InlayHintsConfig::default()).unwrap(), @r###"
[ [
InlayHint { InlayHint {
range: [798; 809), range: [798; 809),
@ -1067,7 +1067,7 @@ fn main() {
}"#, }"#,
); );
assert_debug_snapshot!(analysis.inlay_hints(file_id, &InlayHintsOptions { max_length: Some(8), ..Default::default() }).unwrap(), @r###" assert_debug_snapshot!(analysis.inlay_hints(file_id, &InlayHintsConfig { max_length: Some(8), ..Default::default() }).unwrap(), @r###"
[] []
"### "###
); );
@ -1093,7 +1093,7 @@ fn main() {
}"#, }"#,
); );
assert_debug_snapshot!(analysis.inlay_hints(file_id, &InlayHintsOptions { max_length: Some(8), ..Default::default() }).unwrap(), @r###" assert_debug_snapshot!(analysis.inlay_hints(file_id, &InlayHintsConfig { max_length: Some(8), ..Default::default() }).unwrap(), @r###"
[] []
"### "###
); );
@ -1115,7 +1115,7 @@ fn main() {
.into_c(); .into_c();
}"#, }"#,
); );
assert_debug_snapshot!(analysis.inlay_hints(file_id, &InlayHintsOptions{ parameter_hints: false, type_hints: false, chaining_hints: true, max_length: None}).unwrap(), @r###" assert_debug_snapshot!(analysis.inlay_hints(file_id, &InlayHintsConfig{ parameter_hints: false, type_hints: false, chaining_hints: true, max_length: None}).unwrap(), @r###"
[ [
InlayHint { InlayHint {
range: [232; 269), range: [232; 269),
@ -1144,7 +1144,7 @@ fn main() {
let c = A(B(C)).into_b().into_c(); let c = A(B(C)).into_b().into_c();
}"#, }"#,
); );
assert_debug_snapshot!(analysis.inlay_hints(file_id, &InlayHintsOptions{ parameter_hints: false, type_hints: false, chaining_hints: true, max_length: None}).unwrap(), @r###"[]"###); assert_debug_snapshot!(analysis.inlay_hints(file_id, &InlayHintsConfig{ parameter_hints: false, type_hints: false, chaining_hints: true, max_length: None}).unwrap(), @r###"[]"###);
} }
#[test] #[test]
@ -1162,7 +1162,7 @@ fn main() {
.0; .0;
}"#, }"#,
); );
assert_debug_snapshot!(analysis.inlay_hints(file_id, &InlayHintsOptions{ parameter_hints: false, type_hints: false, chaining_hints: true, max_length: None}).unwrap(), @r###" assert_debug_snapshot!(analysis.inlay_hints(file_id, &InlayHintsConfig{ parameter_hints: false, type_hints: false, chaining_hints: true, max_length: None}).unwrap(), @r###"
[ [
InlayHint { InlayHint {
range: [150; 221), range: [150; 221),
@ -1204,7 +1204,7 @@ fn main() {
.into_c(); .into_c();
}"#, }"#,
); );
assert_debug_snapshot!(analysis.inlay_hints(file_id, &InlayHintsOptions{ parameter_hints: false, type_hints: false, chaining_hints: true, max_length: None}).unwrap(), @r###" assert_debug_snapshot!(analysis.inlay_hints(file_id, &InlayHintsConfig{ parameter_hints: false, type_hints: false, chaining_hints: true, max_length: None}).unwrap(), @r###"
[ [
InlayHint { InlayHint {
range: [403; 452), range: [403; 452),

View file

@ -62,13 +62,13 @@ use crate::display::ToNav;
pub use crate::{ pub use crate::{
assists::{Assist, AssistId}, assists::{Assist, AssistId},
call_hierarchy::CallItem, call_hierarchy::CallItem,
completion::{CompletionItem, CompletionItemKind, CompletionOptions, InsertTextFormat}, completion::{CompletionConfig, CompletionItem, CompletionItemKind, InsertTextFormat},
diagnostics::Severity, diagnostics::Severity,
display::{file_structure, FunctionSignature, NavigationTarget, StructureNode}, display::{file_structure, FunctionSignature, NavigationTarget, StructureNode},
expand_macro::ExpandedMacro, expand_macro::ExpandedMacro,
folding_ranges::{Fold, FoldKind}, folding_ranges::{Fold, FoldKind},
hover::HoverResult, hover::HoverResult,
inlay_hints::{InlayHint, InlayHintsOptions, InlayKind}, inlay_hints::{InlayHint, InlayHintsConfig, InlayKind},
references::{Declaration, Reference, ReferenceAccess, ReferenceKind, ReferenceSearchResult}, references::{Declaration, Reference, ReferenceAccess, ReferenceKind, ReferenceSearchResult},
runnables::{Runnable, RunnableKind, TestId}, runnables::{Runnable, RunnableKind, TestId},
source_change::{FileSystemEdit, SourceChange, SourceFileEdit}, source_change::{FileSystemEdit, SourceChange, SourceFileEdit},
@ -325,9 +325,9 @@ impl Analysis {
pub fn inlay_hints( pub fn inlay_hints(
&self, &self,
file_id: FileId, file_id: FileId,
inlay_hint_opts: &InlayHintsOptions, config: &InlayHintsConfig,
) -> Cancelable<Vec<InlayHint>> { ) -> Cancelable<Vec<InlayHint>> {
self.with_db(|db| inlay_hints::inlay_hints(db, file_id, inlay_hint_opts)) self.with_db(|db| inlay_hints::inlay_hints(db, file_id, config))
} }
/// Returns the set of folding ranges. /// Returns the set of folding ranges.
@ -450,9 +450,9 @@ impl Analysis {
pub fn completions( pub fn completions(
&self, &self,
position: FilePosition, position: FilePosition,
options: &CompletionOptions, config: &CompletionConfig,
) -> Cancelable<Option<Vec<CompletionItem>>> { ) -> Cancelable<Option<Vec<CompletionItem>>> {
self.with_db(|db| completion::completions(db, position, options).map(Into::into)) self.with_db(|db| completion::completions(db, position, config).map(Into::into))
} }
/// Computes assists (aka code actions aka intentions) for the given /// Computes assists (aka code actions aka intentions) for the given

View file

@ -12,7 +12,7 @@ use ra_db::{
salsa::{Database, Durability}, salsa::{Database, Durability},
FileId, SourceDatabaseExt, FileId, SourceDatabaseExt,
}; };
use ra_ide::{Analysis, AnalysisChange, AnalysisHost, CompletionOptions, FilePosition, LineCol}; use ra_ide::{Analysis, AnalysisChange, AnalysisHost, CompletionConfig, FilePosition, LineCol};
use crate::cli::{load_cargo::load_cargo, Verbosity}; use crate::cli::{load_cargo::load_cargo, Verbosity};
@ -102,7 +102,7 @@ pub fn analysis_bench(
let file_position = FilePosition { file_id, offset }; let file_position = FilePosition { file_id, offset };
if is_completion { if is_completion {
let options = CompletionOptions::default(); let options = CompletionConfig::default();
let res = do_work(&mut host, file_id, |analysis| { let res = do_work(&mut host, file_id, |analysis| {
analysis.completions(file_position, &options) analysis.completions(file_position, &options)
}); });

View file

@ -579,7 +579,7 @@ impl TryConvWith<&WorldSnapshot> for (FileId, RangeInfo<Vec<NavigationTarget>>)
.into_iter() .into_iter()
.map(|nav| (file_id, RangeInfo::new(range, nav))) .map(|nav| (file_id, RangeInfo::new(range, nav)))
.try_conv_with_to_vec(world)?; .try_conv_with_to_vec(world)?;
if world.options.supports_location_link { if world.config.supports_location_link {
Ok(links.into()) Ok(links.into())
} else { } else {
let locations: Vec<Location> = links let locations: Vec<Location> = links

View file

@ -21,8 +21,8 @@ use lsp_types::{
WorkDoneProgressBegin, WorkDoneProgressCreateParams, WorkDoneProgressEnd, WorkDoneProgressBegin, WorkDoneProgressCreateParams, WorkDoneProgressEnd,
WorkDoneProgressReport, WorkDoneProgressReport,
}; };
use ra_cargo_watch::{url_from_path_with_drive_lowercasing, CheckOptions, CheckTask}; use ra_cargo_watch::{url_from_path_with_drive_lowercasing, CheckConfig, CheckTask};
use ra_ide::{Canceled, FileId, InlayHintsOptions, LibraryData, SourceRootId}; use ra_ide::{Canceled, FileId, InlayHintsConfig, LibraryData, SourceRootId};
use ra_prof::profile; use ra_prof::profile;
use ra_vfs::{VfsFile, VfsTask, Watch}; use ra_vfs::{VfsFile, VfsTask, Watch};
use relative_path::RelativePathBuf; use relative_path::RelativePathBuf;
@ -38,7 +38,7 @@ use crate::{
subscriptions::Subscriptions, subscriptions::Subscriptions,
}, },
req, req,
world::{Options, WorldSnapshot, WorldState}, world::{Config, WorldSnapshot, WorldState},
Result, ServerConfig, Result, ServerConfig,
}; };
use req::ConfigurationParams; use req::ConfigurationParams;
@ -81,11 +81,11 @@ fn get_feature_flags(config: &ServerConfig, connection: &Connection) -> FeatureF
ff ff
} }
fn get_options( fn get_config(
config: &ServerConfig, config: &ServerConfig,
text_document_caps: Option<&TextDocumentClientCapabilities>, text_document_caps: Option<&TextDocumentClientCapabilities>,
) -> Options { ) -> Config {
Options { Config {
publish_decorations: config.publish_decorations, publish_decorations: config.publish_decorations,
supports_location_link: text_document_caps supports_location_link: text_document_caps
.and_then(|it| it.definition) .and_then(|it| it.definition)
@ -95,13 +95,13 @@ fn get_options(
.and_then(|it| it.folding_range.as_ref()) .and_then(|it| it.folding_range.as_ref())
.and_then(|it| it.line_folding_only) .and_then(|it| it.line_folding_only)
.unwrap_or(false), .unwrap_or(false),
inlay_hints: InlayHintsOptions { inlay_hints: InlayHintsConfig {
type_hints: config.inlay_hints_type, type_hints: config.inlay_hints_type,
parameter_hints: config.inlay_hints_parameter, parameter_hints: config.inlay_hints_parameter,
chaining_hints: config.inlay_hints_chaining, chaining_hints: config.inlay_hints_chaining,
max_length: config.inlay_hints_max_length, max_length: config.inlay_hints_max_length,
}, },
cargo_watch: CheckOptions { check: CheckConfig {
enable: config.cargo_watch_enable, enable: config.cargo_watch_enable,
args: config.cargo_watch_args.clone(), args: config.cargo_watch_args.clone(),
command: config.cargo_watch_command.clone(), command: config.cargo_watch_command.clone(),
@ -210,7 +210,7 @@ pub fn main_loop(
config.lru_capacity, config.lru_capacity,
&globs, &globs,
Watch(!config.use_client_watching), Watch(!config.use_client_watching),
get_options(&config, text_document_caps), get_config(&config, text_document_caps),
feature_flags, feature_flags,
) )
}; };
@ -435,7 +435,7 @@ fn loop_turn(
.to_owned(); .to_owned();
world_state.update_configuration( world_state.update_configuration(
new_config.lru_capacity, new_config.lru_capacity,
get_options(&new_config, text_document_caps), get_config(&new_config, text_document_caps),
get_feature_flags(&new_config, connection), get_feature_flags(&new_config, connection),
); );
} }
@ -498,7 +498,7 @@ fn loop_turn(
update_file_notifications_on_threadpool( update_file_notifications_on_threadpool(
pool, pool,
world_state.snapshot(), world_state.snapshot(),
world_state.options.publish_decorations, world_state.config.publish_decorations,
task_sender.clone(), task_sender.clone(),
loop_state.subscriptions.subscriptions(), loop_state.subscriptions.subscriptions(),
) )

View file

@ -19,7 +19,7 @@ use lsp_types::{
TextEdit, WorkspaceEdit, TextEdit, WorkspaceEdit,
}; };
use ra_ide::{ use ra_ide::{
Assist, AssistId, CompletionOptions, FileId, FilePosition, FileRange, Query, RangeInfo, Assist, AssistId, CompletionConfig, FileId, FilePosition, FileRange, Query, RangeInfo,
Runnable, RunnableKind, SearchScope, Runnable, RunnableKind, SearchScope,
}; };
use ra_prof::profile; use ra_prof::profile;
@ -425,7 +425,7 @@ pub fn handle_completion(
return Ok(None); return Ok(None);
} }
let options = CompletionOptions { let config = CompletionConfig {
enable_postfix_completions: world.feature_flags.get("completion.enable-postfix"), enable_postfix_completions: world.feature_flags.get("completion.enable-postfix"),
add_call_parenthesis: world.feature_flags.get("completion.insertion.add-call-parenthesis"), add_call_parenthesis: world.feature_flags.get("completion.insertion.add-call-parenthesis"),
add_call_argument_snippets: world add_call_argument_snippets: world
@ -433,7 +433,7 @@ pub fn handle_completion(
.get("completion.insertion.add-argument-snippets"), .get("completion.insertion.add-argument-snippets"),
}; };
let items = match world.analysis().completions(position, &options)? { let items = match world.analysis().completions(position, &config)? {
None => return Ok(None), None => return Ok(None),
Some(items) => items, Some(items) => items,
}; };
@ -457,7 +457,7 @@ pub fn handle_folding_range(
let ctx = FoldConvCtx { let ctx = FoldConvCtx {
text: &text, text: &text,
line_index: &line_index, line_index: &line_index,
line_folding_only: world.options.line_folding_only, line_folding_only: world.config.line_folding_only,
}; };
let res = Some(folds.into_iter().map_conv_with(&ctx).collect()); let res = Some(folds.into_iter().map_conv_with(&ctx).collect());
Ok(res) Ok(res)
@ -611,7 +611,7 @@ pub fn handle_formatting(
let end_position = TextUnit::of_str(&file).conv_with(&file_line_index); let end_position = TextUnit::of_str(&file).conv_with(&file_line_index);
let mut rustfmt = process::Command::new("rustfmt"); let mut rustfmt = process::Command::new("rustfmt");
rustfmt.args(&world.options.rustfmt_args); rustfmt.args(&world.config.rustfmt_args);
if let Some(&crate_id) = crate_ids.first() { if let Some(&crate_id) = crate_ids.first() {
// Assume all crates are in the same edition // Assume all crates are in the same edition
let edition = world.analysis().crate_edition(crate_id)?; let edition = world.analysis().crate_edition(crate_id)?;
@ -815,7 +815,7 @@ pub fn handle_code_lens(
}; };
lenses.push(lens); lenses.push(lens);
if world.options.vscode_lldb { if world.config.vscode_lldb {
if r.args[0] == "run" { if r.args[0] == "run" {
r.args[0] = "build".into(); r.args[0] = "build".into();
} else { } else {
@ -1028,7 +1028,7 @@ pub fn handle_inlay_hints(
let analysis = world.analysis(); let analysis = world.analysis();
let line_index = analysis.file_line_index(file_id)?; let line_index = analysis.file_line_index(file_id)?;
Ok(analysis Ok(analysis
.inlay_hints(file_id, &world.options.inlay_hints)? .inlay_hints(file_id, &world.config.inlay_hints)?
.into_iter() .into_iter()
.map_conv_with(&line_index) .map_conv_with(&line_index)
.collect()) .collect())

View file

@ -11,9 +11,9 @@ use std::{
use crossbeam_channel::{unbounded, Receiver}; use crossbeam_channel::{unbounded, Receiver};
use lsp_types::Url; use lsp_types::Url;
use parking_lot::RwLock; use parking_lot::RwLock;
use ra_cargo_watch::{url_from_path_with_drive_lowercasing, CheckOptions, CheckWatcher}; use ra_cargo_watch::{url_from_path_with_drive_lowercasing, CheckConfig, CheckWatcher};
use ra_ide::{ use ra_ide::{
Analysis, AnalysisChange, AnalysisHost, CrateGraph, FileId, InlayHintsOptions, LibraryData, Analysis, AnalysisChange, AnalysisHost, CrateGraph, FileId, InlayHintsConfig, LibraryData,
SourceRootId, SourceRootId,
}; };
use ra_project_model::{get_rustc_cfg_options, ProcMacroClient, ProjectWorkspace}; use ra_project_model::{get_rustc_cfg_options, ProcMacroClient, ProjectWorkspace};
@ -31,7 +31,7 @@ use crate::{
use ra_db::ExternSourceId; use ra_db::ExternSourceId;
use rustc_hash::{FxHashMap, FxHashSet}; use rustc_hash::{FxHashMap, FxHashSet};
fn create_watcher(workspaces: &[ProjectWorkspace], options: &Options) -> Option<CheckWatcher> { fn create_watcher(workspaces: &[ProjectWorkspace], config: &Config) -> Option<CheckWatcher> {
// FIXME: Figure out the multi-workspace situation // FIXME: Figure out the multi-workspace situation
workspaces workspaces
.iter() .iter()
@ -41,7 +41,7 @@ fn create_watcher(workspaces: &[ProjectWorkspace], options: &Options) -> Option<
}) })
.map(|cargo| { .map(|cargo| {
let cargo_project_root = cargo.workspace_root().to_path_buf(); let cargo_project_root = cargo.workspace_root().to_path_buf();
Some(CheckWatcher::new(&options.cargo_watch, cargo_project_root)) Some(CheckWatcher::new(config.check.clone(), cargo_project_root))
}) })
.unwrap_or_else(|| { .unwrap_or_else(|| {
log::warn!("Cargo check watching only supported for cargo workspaces, disabling"); log::warn!("Cargo check watching only supported for cargo workspaces, disabling");
@ -50,13 +50,13 @@ fn create_watcher(workspaces: &[ProjectWorkspace], options: &Options) -> Option<
} }
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
pub struct Options { pub struct Config {
pub publish_decorations: bool, pub publish_decorations: bool,
pub supports_location_link: bool, pub supports_location_link: bool,
pub line_folding_only: bool, pub line_folding_only: bool,
pub inlay_hints: InlayHintsOptions, pub inlay_hints: InlayHintsConfig,
pub rustfmt_args: Vec<String>, pub rustfmt_args: Vec<String>,
pub cargo_watch: CheckOptions, pub check: CheckConfig,
pub vscode_lldb: bool, pub vscode_lldb: bool,
} }
@ -67,7 +67,7 @@ pub struct Options {
/// incremental salsa database. /// incremental salsa database.
#[derive(Debug)] #[derive(Debug)]
pub struct WorldState { pub struct WorldState {
pub options: Options, pub config: Config,
pub feature_flags: Arc<FeatureFlags>, pub feature_flags: Arc<FeatureFlags>,
pub roots: Vec<PathBuf>, pub roots: Vec<PathBuf>,
pub workspaces: Arc<Vec<ProjectWorkspace>>, pub workspaces: Arc<Vec<ProjectWorkspace>>,
@ -81,7 +81,7 @@ pub struct WorldState {
/// An immutable snapshot of the world's state at a point in time. /// An immutable snapshot of the world's state at a point in time.
pub struct WorldSnapshot { pub struct WorldSnapshot {
pub options: Options, pub config: Config,
pub feature_flags: Arc<FeatureFlags>, pub feature_flags: Arc<FeatureFlags>,
pub workspaces: Arc<Vec<ProjectWorkspace>>, pub workspaces: Arc<Vec<ProjectWorkspace>>,
pub analysis: Analysis, pub analysis: Analysis,
@ -97,7 +97,7 @@ impl WorldState {
lru_capacity: Option<usize>, lru_capacity: Option<usize>,
exclude_globs: &[Glob], exclude_globs: &[Glob],
watch: Watch, watch: Watch,
options: Options, config: Config,
feature_flags: FeatureFlags, feature_flags: FeatureFlags,
) -> WorldState { ) -> WorldState {
let mut change = AnalysisChange::new(); let mut change = AnalysisChange::new();
@ -185,12 +185,12 @@ impl WorldState {
}); });
change.set_crate_graph(crate_graph); change.set_crate_graph(crate_graph);
let check_watcher = create_watcher(&workspaces, &options); let check_watcher = create_watcher(&workspaces, &config);
let mut analysis_host = AnalysisHost::new(lru_capacity); let mut analysis_host = AnalysisHost::new(lru_capacity);
analysis_host.apply_change(change); analysis_host.apply_change(change);
WorldState { WorldState {
options, config: config,
feature_flags: Arc::new(feature_flags), feature_flags: Arc::new(feature_flags),
roots: folder_roots, roots: folder_roots,
workspaces: Arc::new(workspaces), workspaces: Arc::new(workspaces),
@ -206,13 +206,13 @@ impl WorldState {
pub fn update_configuration( pub fn update_configuration(
&mut self, &mut self,
lru_capacity: Option<usize>, lru_capacity: Option<usize>,
options: Options, config: Config,
feature_flags: FeatureFlags, feature_flags: FeatureFlags,
) { ) {
self.feature_flags = Arc::new(feature_flags); self.feature_flags = Arc::new(feature_flags);
self.analysis_host.update_lru_capacity(lru_capacity); self.analysis_host.update_lru_capacity(lru_capacity);
self.check_watcher = create_watcher(&self.workspaces, &options); self.check_watcher = create_watcher(&self.workspaces, &config);
self.options = options; self.config = config;
} }
/// Returns a vec of libraries /// Returns a vec of libraries
@ -268,7 +268,7 @@ impl WorldState {
pub fn snapshot(&self) -> WorldSnapshot { pub fn snapshot(&self) -> WorldSnapshot {
WorldSnapshot { WorldSnapshot {
options: self.options.clone(), config: self.config.clone(),
feature_flags: Arc::clone(&self.feature_flags), feature_flags: Arc::clone(&self.feature_flags),
workspaces: Arc::clone(&self.workspaces), workspaces: Arc::clone(&self.workspaces),
analysis: self.analysis_host.analysis(), analysis: self.analysis_host.analysis(),

View file

@ -261,41 +261,57 @@
"default": [], "default": [],
"description": "Paths to exclude from analysis" "description": "Paths to exclude from analysis"
}, },
"rust-analyzer.rustfmtArgs": {
"type": "array",
"items": {
"type": "string"
},
"default": [],
"description": "Additional arguments to rustfmt"
},
"rust-analyzer.useClientWatching": { "rust-analyzer.useClientWatching": {
"type": "boolean", "type": "boolean",
"default": true, "default": true,
"description": "client provided file watching instead of notify watching." "description": "client provided file watching instead of notify watching."
}, },
"rust-analyzer.cargo-watch.enable": { "rust-analyzer.rustfmt.extraArgs": {
"type": "boolean",
"default": true,
"markdownDescription": "Run specified `cargo-watch` command for diagnostics on save"
},
"rust-analyzer.cargo-watch.arguments": {
"type": "array", "type": "array",
"items": { "items": {
"type": "string" "type": "string"
}, },
"markdownDescription": "`cargo-watch` arguments. (e.g: `--features=\"shumway,pdf\"` will run as `cargo watch -x \"check --features=\"shumway,pdf\"\"` )", "default": [],
"markdownDescription": "Additional `cargo fmt` arguments"
},
"rust-analyzer.rustfmt.overrideCommand": {
"type": "array",
"items": {
"type": "string"
},
"default": [],
"markdownDescription": "Advanced option, fully override `cargo fmt` command line"
},
"rust-analyzer.checkOnSave.enable": {
"type": "boolean",
"default": true,
"markdownDescription": "Run `cargo check` command for diagnostics on save"
},
"rust-analyzer.checkOnSave.cargoCommand": {
"type": "string",
"default": "check",
"markdownDescription": "Cargo command to run on save"
},
"rust-analyzer.checkOnSave.allTargets": {
"type": "boolean",
"default": true,
"markdownDescription": "Check all targets and tests (will be passed as `--all-targets`)"
},
"rust-analyzer.checkOnSave.extraArgs": {
"type": "array",
"items": {
"type": "string"
},
"markdownDescription": "Additional `cargo check` arguments",
"default": [] "default": []
}, },
"rust-analyzer.cargo-watch.command": { "rust-analyzer.checkOnSave.overrideCommand": {
"type": "string", "type": "array",
"markdownDescription": "`cargo-watch` command. (e.g: `clippy` will run as `cargo watch -x clippy` )", "items": {
"default": "check" "type": "string"
}, },
"rust-analyzer.cargo-watch.allTargets": { "default": [],
"type": "boolean", "markdownDescription": "Advanced option, fully override `cargo check` command line (this must include at least `--message-format=json`)"
"markdownDescription": "Check all targets and tests (will be passed as `--all-targets`)",
"default": true
}, },
"rust-analyzer.trace.server": { "rust-analyzer.trace.server": {
"type": "string", "type": "string",