⬆️ rust-analyzer

This commit is contained in:
Laurențiu Nicola 2022-09-20 17:39:17 +03:00
parent 459bbb4222
commit f5fde4df43
76 changed files with 1613 additions and 654 deletions

View file

@ -80,7 +80,8 @@ impl flags::AnalysisStats {
Some(build_scripts_sw.elapsed())
};
let (host, vfs, _proc_macro) = load_workspace(workspace, &load_cargo_config)?;
let (host, vfs, _proc_macro) =
load_workspace(workspace, &cargo_config, &load_cargo_config)?;
let db = host.raw_database();
eprint!("{:<20} {}", "Database loaded:", db_load_sw.elapsed());
eprint!(" (metadata {}", metadata_time);

View file

@ -38,7 +38,7 @@ pub fn load_workspace_at(
workspace.set_build_scripts(build_scripts)
}
load_workspace(workspace, load_config)
load_workspace(workspace, cargo_config, load_config)
}
// Note: Since this function is used by external tools that use rust-analyzer as a library
@ -48,6 +48,7 @@ pub fn load_workspace_at(
// these tools need access to `ProjectWorkspace`, too, which `load_workspace_at` hides.
pub fn load_workspace(
ws: ProjectWorkspace,
cargo_config: &CargoConfig,
load_config: &LoadCargoConfig,
) -> Result<(AnalysisHost, vfs::Vfs, Option<ProcMacroServer>)> {
let (sender, receiver) = unbounded();
@ -75,6 +76,7 @@ pub fn load_workspace(
vfs.set_file_contents(path.clone(), contents);
vfs.file_id(&path)
},
cargo_config,
);
let project_folders = ProjectFolders::new(&[ws], &[]);

View file

@ -299,7 +299,8 @@ impl flags::Lsif {
let workspace = ProjectWorkspace::load(manifest, &cargo_config, no_progress)?;
let (host, vfs, _proc_macro) = load_workspace(workspace, &load_cargo_config)?;
let (host, vfs, _proc_macro) =
load_workspace(workspace, &cargo_config, &load_cargo_config)?;
let db = host.raw_database();
let analysis = host.analysis();

View file

@ -40,7 +40,7 @@ impl flags::Scip {
let workspace = ProjectWorkspace::load(manifest, &cargo_config, no_progress)?;
let (host, vfs, _) = load_workspace(workspace, &load_cargo_config)?;
let (host, vfs, _) = load_workspace(workspace, &cargo_config, &load_cargo_config)?;
let db = host.raw_database();
let analysis = host.analysis();

View file

@ -84,6 +84,9 @@ config_data! {
/// Use `RUSTC_WRAPPER=rust-analyzer` when running build scripts to
/// avoid checking unnecessary things.
cargo_buildScripts_useRustcWrapper: bool = "true",
/// Extra environment variables that will be set when running cargo, rustc
/// or other commands within the workspace. Useful for setting RUSTFLAGS.
cargo_extraEnv: FxHashMap<String, String> = "{}",
/// List of features to activate.
///
/// Set this to `"all"` to pass `--all-features` to cargo.
@ -105,6 +108,8 @@ config_data! {
checkOnSave_enable: bool = "true",
/// Extra arguments for `cargo check`.
checkOnSave_extraArgs: Vec<String> = "[]",
/// Extra environment variables that will be set when running `cargo check`.
checkOnSave_extraEnv: FxHashMap<String, String> = "{}",
/// List of features to activate. Defaults to
/// `#rust-analyzer.cargo.features#`.
///
@ -219,7 +224,6 @@ config_data! {
files_excludeDirs: Vec<PathBuf> = "[]",
/// Controls file watching implementation.
files_watcher: FilesWatcherDef = "\"client\"",
/// Enables highlighting of related references while the cursor is on `break`, `loop`, `while`, or `for` keywords.
highlightRelated_breakPoints_enable: bool = "true",
/// Enables highlighting of all exit points while the cursor is on any `return`, `?`, `fn`, or return type arrow (`->`).
@ -263,6 +267,8 @@ config_data! {
imports_group_enable: bool = "true",
/// Whether to allow import insertion to merge new imports into single path glob imports like `use std::fmt::*;`.
imports_merge_glob: bool = "true",
/// Prefer to unconditionally use imports of the core and alloc crate, over the std crate.
imports_prefer_no_std: bool = "false",
/// The path structure for newly inserted paths to use.
imports_prefix: ImportPrefixDef = "\"plain\"",
@ -307,6 +313,7 @@ config_data! {
/// Join lines unwraps trivial blocks.
joinLines_unwrapTrivialBlock: bool = "true",
/// Whether to show `Debug` lens. Only applies when
/// `#rust-analyzer.lens.enable#` is set.
lens_debug_enable: bool = "true",
@ -318,6 +325,8 @@ config_data! {
/// Whether to show `Implementations` lens. Only applies when
/// `#rust-analyzer.lens.enable#` is set.
lens_implementations_enable: bool = "true",
/// Where to render annotations.
lens_location: AnnotationLocation = "\"above_name\"",
/// Whether to show `References` lens for Struct, Enum, and Union.
/// Only applies when `#rust-analyzer.lens.enable#` is set.
lens_references_adt_enable: bool = "false",
@ -359,6 +368,9 @@ config_data! {
/// this is rust-analyzer itself, but we override this in tests).
procMacro_server: Option<PathBuf> = "null",
/// Exclude imports from find-all-references.
references_excludeImports: bool = "false",
/// Command to be executed instead of 'cargo' for runnables.
runnables_command: Option<String> = "null",
/// Additional arguments to be passed to cargo for runnables such as
@ -494,6 +506,25 @@ pub struct LensConfig {
pub refs_adt: bool, // for Struct, Enum, Union and Trait
pub refs_trait: bool, // for Struct, Enum, Union and Trait
pub enum_variant_refs: bool,
// annotations
pub location: AnnotationLocation,
}
#[derive(Copy, Clone, Debug, PartialEq, Eq, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum AnnotationLocation {
AboveName,
AboveWholeItem,
}
impl From<AnnotationLocation> for ide::AnnotationLocation {
fn from(location: AnnotationLocation) -> Self {
match location {
AnnotationLocation::AboveName => ide::AnnotationLocation::AboveName,
AnnotationLocation::AboveWholeItem => ide::AnnotationLocation::AboveWholeItem,
}
}
}
impl LensConfig {
@ -918,6 +949,7 @@ impl Config {
ExprFillDefaultDef::Default => ExprFillDefaultMode::Default,
},
insert_use: self.insert_use_config(),
prefer_no_std: self.data.imports_prefer_no_std,
}
}
@ -929,6 +961,16 @@ impl Config {
}
}
pub fn extra_env(&self) -> &FxHashMap<String, String> {
&self.data.cargo_extraEnv
}
pub fn check_on_save_extra_env(&self) -> FxHashMap<String, String> {
let mut extra_env = self.data.cargo_extraEnv.clone();
extra_env.extend(self.data.checkOnSave_extraEnv.clone());
extra_env
}
pub fn lru_capacity(&self) -> Option<usize> {
self.data.lru_capacity
}
@ -998,6 +1040,7 @@ impl Config {
unset_test_crates: UnsetTestCrates::Only(self.data.cargo_unsetTest.clone()),
wrap_rustc_in_build_scripts: self.data.cargo_buildScripts_useRustcWrapper,
run_build_script_command: self.data.cargo_buildScripts_overrideCommand.clone(),
extra_env: self.data.cargo_extraEnv.clone(),
}
}
@ -1023,7 +1066,11 @@ impl Config {
Some(args) if !args.is_empty() => {
let mut args = args.clone();
let command = args.remove(0);
FlycheckConfig::CustomCommand { command, args }
FlycheckConfig::CustomCommand {
command,
args,
extra_env: self.check_on_save_extra_env(),
}
}
Some(_) | None => FlycheckConfig::CargoCommand {
command: self.data.checkOnSave_command.clone(),
@ -1051,6 +1098,7 @@ impl Config {
CargoFeatures::Listed(it) => it,
},
extra_args: self.data.checkOnSave_extraArgs.clone(),
extra_env: self.check_on_save_extra_env(),
},
};
Some(flycheck_config)
@ -1133,6 +1181,7 @@ impl Config {
CallableCompletionDef::None => None,
},
insert_use: self.insert_use_config(),
prefer_no_std: self.data.imports_prefer_no_std,
snippet_cap: SnippetCap::new(try_or_def!(
self.caps
.text_document
@ -1147,6 +1196,10 @@ impl Config {
}
}
pub fn find_all_refs_exclude_imports(&self) -> bool {
self.data.references_excludeImports
}
pub fn snippet_cap(&self) -> bool {
self.experimental("snippetTextEdit")
}
@ -1156,6 +1209,7 @@ impl Config {
snippet_cap: SnippetCap::new(self.experimental("snippetTextEdit")),
allowed: None,
insert_use: self.insert_use_config(),
prefer_no_std: self.data.imports_prefer_no_std,
}
}
@ -1185,6 +1239,7 @@ impl Config {
refs_trait: self.data.lens_enable && self.data.lens_references_trait_enable,
enum_variant_refs: self.data.lens_enable
&& self.data.lens_references_enumVariant_enable,
location: self.data.lens_location,
}
}
@ -1921,6 +1976,14 @@ fn field_props(field: &str, ty: &str, doc: &[&str], default: &str) -> serde_json
"Use server-side file watching",
],
},
"AnnotationLocation" => set! {
"type": "string",
"enum": ["above_name", "above_whole_item"],
"enumDescriptions": [
"Render annotations above the name of the item.",
"Render annotations above the whole item, including documentation comments and attributes."
],
},
_ => panic!("missing entry for {}: {}", ty, default),
}

View file

@ -10,8 +10,8 @@ use std::{
use anyhow::Context;
use ide::{
AnnotationConfig, AssistKind, AssistResolveStrategy, FileId, FilePosition, FileRange,
HoverAction, HoverGotoTypeData, Query, RangeInfo, Runnable, RunnableKind, SingleResolve,
SourceChange, TextEdit,
HoverAction, HoverGotoTypeData, Query, RangeInfo, ReferenceCategory, Runnable, RunnableKind,
SingleResolve, SourceChange, TextEdit,
};
use ide_db::SymbolKind;
use lsp_server::ErrorCode;
@ -1012,6 +1012,8 @@ pub(crate) fn handle_references(
let _p = profile::span("handle_references");
let position = from_proto::file_position(&snap, params.text_document_position)?;
let exclude_imports = snap.config.find_all_refs_exclude_imports();
let refs = match snap.analysis.find_all_refs(position, None)? {
None => return Ok(None),
Some(refs) => refs,
@ -1032,7 +1034,11 @@ pub(crate) fn handle_references(
refs.references
.into_iter()
.flat_map(|(file_id, refs)| {
refs.into_iter().map(move |(range, _)| FileRange { file_id, range })
refs.into_iter()
.filter(|&(_, category)| {
!exclude_imports || category != Some(ReferenceCategory::Import)
})
.map(move |(range, _)| FileRange { file_id, range })
})
.chain(decl)
})
@ -1234,6 +1240,7 @@ pub(crate) fn handle_code_lens(
annotate_references: lens_config.refs_adt,
annotate_method_references: lens_config.method_refs,
annotate_enum_variant_references: lens_config.enum_variant_refs,
location: lens_config.location.into(),
},
file_id,
)?;
@ -1283,7 +1290,7 @@ pub(crate) fn handle_document_highlight(
.into_iter()
.map(|ide::HighlightedRange { range, category }| lsp_types::DocumentHighlight {
range: to_proto::range(&line_index, range),
kind: category.map(to_proto::document_highlight_kind),
kind: category.and_then(to_proto::document_highlight_kind),
})
.collect();
Ok(Some(res))
@ -1782,6 +1789,7 @@ fn run_rustfmt(
let mut command = match snap.config.rustfmt() {
RustfmtConfig::Rustfmt { extra_args, enable_range_formatting } => {
let mut cmd = process::Command::new(toolchain::rustfmt());
cmd.envs(snap.config.extra_env());
cmd.args(extra_args);
// try to chdir to the file so we can respect `rustfmt.toml`
// FIXME: use `rustfmt --config-path` once
@ -1839,6 +1847,7 @@ fn run_rustfmt(
}
RustfmtConfig::CustomCommand { command, args } => {
let mut cmd = process::Command::new(command);
cmd.envs(snap.config.extra_env());
cmd.args(args);
cmd
}

View file

@ -145,6 +145,7 @@ fn integrated_completion_benchmark() {
skip_glob_imports: true,
},
snippets: Vec::new(),
prefer_no_std: false,
};
let position =
FilePosition { file_id, offset: TextSize::try_from(completion_offset).unwrap() };
@ -182,6 +183,7 @@ fn integrated_completion_benchmark() {
skip_glob_imports: true,
},
snippets: Vec::new(),
prefer_no_std: false,
};
let position =
FilePosition { file_id, offset: TextSize::try_from(completion_offset).unwrap() };

View file

@ -143,6 +143,7 @@ impl GlobalState {
project_model::ProjectWorkspace::load_inline(
it.clone(),
cargo_config.target.as_deref(),
&cargo_config,
)
}
})
@ -398,7 +399,11 @@ impl GlobalState {
dummy_replacements.get(crate_name).map(|v| &**v).unwrap_or_default(),
)
};
crate_graph.extend(ws.to_crate_graph(&mut load_proc_macro, &mut load));
crate_graph.extend(ws.to_crate_graph(
&mut load_proc_macro,
&mut load,
&self.config.cargo(),
));
}
crate_graph
};

View file

@ -83,10 +83,11 @@ pub(crate) fn structure_node_kind(kind: StructureNodeKind) -> lsp_types::SymbolK
pub(crate) fn document_highlight_kind(
category: ReferenceCategory,
) -> lsp_types::DocumentHighlightKind {
) -> Option<lsp_types::DocumentHighlightKind> {
match category {
ReferenceCategory::Read => lsp_types::DocumentHighlightKind::READ,
ReferenceCategory::Write => lsp_types::DocumentHighlightKind::WRITE,
ReferenceCategory::Read => Some(lsp_types::DocumentHighlightKind::READ),
ReferenceCategory::Write => Some(lsp_types::DocumentHighlightKind::WRITE),
ReferenceCategory::Import => None,
}
}