internal: Use Cancellable in favor of Result for clarity

This commit is contained in:
Lukas Wirth 2022-11-07 17:21:37 +01:00
parent 6a06f6f724
commit fa70b0a86e
6 changed files with 44 additions and 43 deletions

View file

@ -180,7 +180,7 @@ impl fmt::Debug for InlayHintLabelPart {
pub(crate) fn inlay_hints( pub(crate) fn inlay_hints(
db: &RootDatabase, db: &RootDatabase,
file_id: FileId, file_id: FileId,
range_limit: Option<FileRange>, range_limit: Option<TextRange>,
config: &InlayHintsConfig, config: &InlayHintsConfig,
) -> Vec<InlayHint> { ) -> Vec<InlayHint> {
let _p = profile::span("inlay_hints"); let _p = profile::span("inlay_hints");
@ -195,7 +195,7 @@ pub(crate) fn inlay_hints(
let hints = |node| hints(&mut acc, &famous_defs, config, file_id, node); let hints = |node| hints(&mut acc, &famous_defs, config, file_id, node);
match range_limit { match range_limit {
Some(FileRange { range, .. }) => match file.covering_element(range) { Some(range) => match file.covering_element(range) {
NodeOrToken::Token(_) => return acc, NodeOrToken::Token(_) => return acc,
NodeOrToken::Node(n) => n NodeOrToken::Node(n) => n
.descendants() .descendants()
@ -1213,7 +1213,6 @@ fn get_callable(
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use expect_test::{expect, Expect}; use expect_test::{expect, Expect};
use ide_db::base_db::FileRange;
use itertools::Itertools; use itertools::Itertools;
use syntax::{TextRange, TextSize}; use syntax::{TextRange, TextSize};
use test_utils::extract_annotations; use test_utils::extract_annotations;
@ -1838,10 +1837,7 @@ fn main() {
.inlay_hints( .inlay_hints(
&InlayHintsConfig { type_hints: true, ..DISABLED_CONFIG }, &InlayHintsConfig { type_hints: true, ..DISABLED_CONFIG },
file_id, file_id,
Some(FileRange { Some(TextRange::new(TextSize::from(500), TextSize::from(600))),
file_id,
range: TextRange::new(TextSize::from(500), TextSize::from(600)),
}),
) )
.unwrap(); .unwrap();
let actual = let actual =

View file

@ -367,7 +367,7 @@ impl Analysis {
&self, &self,
config: &InlayHintsConfig, config: &InlayHintsConfig,
file_id: FileId, file_id: FileId,
range: Option<FileRange>, range: Option<TextRange>,
) -> Cancellable<Vec<InlayHint>> { ) -> Cancellable<Vec<InlayHint>> {
self.with_db(|db| inlay_hints::inlay_hints(db, file_id, range, config)) self.with_db(|db| inlay_hints::inlay_hints(db, file_id, range, config))
} }

View file

@ -3,11 +3,11 @@
use std::mem; use std::mem;
use cfg::{CfgAtom, CfgExpr}; use cfg::{CfgAtom, CfgExpr};
use ide::{FileId, RunnableKind, TestId}; use ide::{Cancellable, FileId, RunnableKind, TestId};
use project_model::{self, CargoFeatures, ManifestPath, TargetKind}; use project_model::{self, CargoFeatures, ManifestPath, TargetKind};
use vfs::AbsPathBuf; use vfs::AbsPathBuf;
use crate::{global_state::GlobalStateSnapshot, Result}; use crate::global_state::GlobalStateSnapshot;
/// Abstract representation of Cargo target. /// Abstract representation of Cargo target.
/// ///
@ -29,7 +29,7 @@ impl CargoTargetSpec {
spec: Option<CargoTargetSpec>, spec: Option<CargoTargetSpec>,
kind: &RunnableKind, kind: &RunnableKind,
cfg: &Option<CfgExpr>, cfg: &Option<CfgExpr>,
) -> Result<(Vec<String>, Vec<String>)> { ) -> (Vec<String>, Vec<String>) {
let mut args = Vec::new(); let mut args = Vec::new();
let mut extra_args = Vec::new(); let mut extra_args = Vec::new();
@ -111,13 +111,13 @@ impl CargoTargetSpec {
} }
} }
} }
Ok((args, extra_args)) (args, extra_args)
} }
pub(crate) fn for_file( pub(crate) fn for_file(
global_state_snapshot: &GlobalStateSnapshot, global_state_snapshot: &GlobalStateSnapshot,
file_id: FileId, file_id: FileId,
) -> Result<Option<CargoTargetSpec>> { ) -> Cancellable<Option<CargoTargetSpec>> {
let crate_id = match &*global_state_snapshot.analysis.crates_for(file_id)? { let crate_id = match &*global_state_snapshot.analysis.crates_for(file_id)? {
&[crate_id, ..] => crate_id, &[crate_id, ..] => crate_id,
_ => return Ok(None), _ => return Ok(None),

View file

@ -9,9 +9,9 @@ use std::{
use anyhow::Context; use anyhow::Context;
use ide::{ use ide::{
AnnotationConfig, AssistKind, AssistResolveStrategy, FileId, FilePosition, FileRange, AnnotationConfig, AssistKind, AssistResolveStrategy, Cancellable, FileId, FilePosition,
HoverAction, HoverGotoTypeData, Query, RangeInfo, ReferenceCategory, Runnable, RunnableKind, FileRange, HoverAction, HoverGotoTypeData, Query, RangeInfo, ReferenceCategory, Runnable,
SingleResolve, SourceChange, TextEdit, RunnableKind, SingleResolve, SourceChange, TextEdit,
}; };
use ide_db::SymbolKind; use ide_db::SymbolKind;
use lsp_server::ErrorCode; use lsp_server::ErrorCode;
@ -556,7 +556,7 @@ pub(crate) fn handle_will_rename_files(
if source_change.source_file_edits.is_empty() { if source_change.source_file_edits.is_empty() {
Ok(None) Ok(None)
} else { } else {
to_proto::workspace_edit(&snap, source_change).map(Some) Ok(Some(to_proto::workspace_edit(&snap, source_change)?))
} }
} }
@ -1313,7 +1313,7 @@ pub(crate) fn handle_ssr(
position, position,
selections, selections,
)??; )??;
to_proto::workspace_edit(&snap, source_change) to_proto::workspace_edit(&snap, source_change).map_err(Into::into)
} }
pub(crate) fn publish_diagnostics( pub(crate) fn publish_diagnostics(
@ -1354,13 +1354,12 @@ pub(crate) fn handle_inlay_hints(
) -> Result<Option<Vec<InlayHint>>> { ) -> Result<Option<Vec<InlayHint>>> {
let _p = profile::span("handle_inlay_hints"); let _p = profile::span("handle_inlay_hints");
let document_uri = &params.text_document.uri; let document_uri = &params.text_document.uri;
let file_id = from_proto::file_id(&snap, document_uri)?; let FileRange { file_id, range } = from_proto::file_range(
let line_index = snap.file_line_index(file_id)?;
let range = from_proto::file_range(
&snap, &snap,
TextDocumentIdentifier::new(document_uri.to_owned()), TextDocumentIdentifier::new(document_uri.to_owned()),
params.range, params.range,
)?; )?;
let line_index = snap.file_line_index(file_id)?;
let inlay_hints_config = snap.config.inlay_hints(); let inlay_hints_config = snap.config.inlay_hints();
Ok(Some( Ok(Some(
snap.analysis snap.analysis
@ -1369,7 +1368,7 @@ pub(crate) fn handle_inlay_hints(
.map(|it| { .map(|it| {
to_proto::inlay_hint(&snap, &line_index, inlay_hints_config.render_colons, it) to_proto::inlay_hint(&snap, &line_index, inlay_hints_config.render_colons, it)
}) })
.collect::<Result<Vec<_>>>()?, .collect::<Cancellable<Vec<_>>>()?,
)) ))
} }
@ -1426,7 +1425,7 @@ pub(crate) fn handle_call_hierarchy_prepare(
.into_iter() .into_iter()
.filter(|it| it.kind == Some(SymbolKind::Function)) .filter(|it| it.kind == Some(SymbolKind::Function))
.map(|it| to_proto::call_hierarchy_item(&snap, it)) .map(|it| to_proto::call_hierarchy_item(&snap, it))
.collect::<Result<Vec<_>>>()?; .collect::<Cancellable<Vec<_>>>()?;
Ok(Some(res)) Ok(Some(res))
} }

View file

@ -7,7 +7,7 @@ use vfs::VfsPath;
/// Holds the set of in-memory documents. /// Holds the set of in-memory documents.
/// ///
/// For these document, there true contents is maintained by the client. It /// For these document, their true contents is maintained by the client. It
/// might be different from what's on disk. /// might be different from what's on disk.
#[derive(Default, Clone)] #[derive(Default, Clone)]
pub(crate) struct MemDocs { pub(crate) struct MemDocs {
@ -19,6 +19,7 @@ impl MemDocs {
pub(crate) fn contains(&self, path: &VfsPath) -> bool { pub(crate) fn contains(&self, path: &VfsPath) -> bool {
self.mem_docs.contains_key(path) self.mem_docs.contains_key(path)
} }
pub(crate) fn insert(&mut self, path: VfsPath, data: DocumentData) -> Result<(), ()> { pub(crate) fn insert(&mut self, path: VfsPath, data: DocumentData) -> Result<(), ()> {
self.added_or_removed = true; self.added_or_removed = true;
match self.mem_docs.insert(path, data) { match self.mem_docs.insert(path, data) {
@ -26,6 +27,7 @@ impl MemDocs {
None => Ok(()), None => Ok(()),
} }
} }
pub(crate) fn remove(&mut self, path: &VfsPath) -> Result<(), ()> { pub(crate) fn remove(&mut self, path: &VfsPath) -> Result<(), ()> {
self.added_or_removed = true; self.added_or_removed = true;
match self.mem_docs.remove(path) { match self.mem_docs.remove(path) {
@ -33,17 +35,21 @@ impl MemDocs {
None => Err(()), None => Err(()),
} }
} }
pub(crate) fn get(&self, path: &VfsPath) -> Option<&DocumentData> { pub(crate) fn get(&self, path: &VfsPath) -> Option<&DocumentData> {
self.mem_docs.get(path) self.mem_docs.get(path)
} }
pub(crate) fn get_mut(&mut self, path: &VfsPath) -> Option<&mut DocumentData> { pub(crate) fn get_mut(&mut self, path: &VfsPath) -> Option<&mut DocumentData> {
// NB: don't set `self.added_or_removed` here, as that purposefully only // NB: don't set `self.added_or_removed` here, as that purposefully only
// tracks changes to the key set. // tracks changes to the key set.
self.mem_docs.get_mut(path) self.mem_docs.get_mut(path)
} }
pub(crate) fn iter(&self) -> impl Iterator<Item = &VfsPath> { pub(crate) fn iter(&self) -> impl Iterator<Item = &VfsPath> {
self.mem_docs.keys() self.mem_docs.keys()
} }
pub(crate) fn take_changes(&mut self) -> bool { pub(crate) fn take_changes(&mut self) -> bool {
mem::replace(&mut self.added_or_removed, false) mem::replace(&mut self.added_or_removed, false)
} }

View file

@ -24,7 +24,7 @@ use crate::{
line_index::{LineEndings, LineIndex, PositionEncoding}, line_index::{LineEndings, LineIndex, PositionEncoding},
lsp_ext, lsp_ext,
lsp_utils::invalid_params_error, lsp_utils::invalid_params_error,
semantic_tokens, Result, semantic_tokens,
}; };
pub(crate) fn position(line_index: &LineIndex, offset: TextSize) -> lsp_types::Position { pub(crate) fn position(line_index: &LineIndex, offset: TextSize) -> lsp_types::Position {
@ -429,7 +429,7 @@ pub(crate) fn inlay_hint(
line_index: &LineIndex, line_index: &LineIndex,
render_colons: bool, render_colons: bool,
mut inlay_hint: InlayHint, mut inlay_hint: InlayHint,
) -> Result<lsp_types::InlayHint> { ) -> Cancellable<lsp_types::InlayHint> {
match inlay_hint.kind { match inlay_hint.kind {
InlayKind::ParameterHint if render_colons => inlay_hint.label.append_str(":"), InlayKind::ParameterHint if render_colons => inlay_hint.label.append_str(":"),
InlayKind::TypeHint if render_colons => inlay_hint.label.prepend_str(": "), InlayKind::TypeHint if render_colons => inlay_hint.label.prepend_str(": "),
@ -518,7 +518,7 @@ pub(crate) fn inlay_hint(
fn inlay_hint_label( fn inlay_hint_label(
snap: &GlobalStateSnapshot, snap: &GlobalStateSnapshot,
label: InlayHintLabel, label: InlayHintLabel,
) -> Result<lsp_types::InlayHintLabel> { ) -> Cancellable<lsp_types::InlayHintLabel> {
Ok(match label.as_simple_str() { Ok(match label.as_simple_str() {
Some(s) => lsp_types::InlayHintLabel::String(s.into()), Some(s) => lsp_types::InlayHintLabel::String(s.into()),
None => lsp_types::InlayHintLabel::LabelParts( None => lsp_types::InlayHintLabel::LabelParts(
@ -536,7 +536,7 @@ fn inlay_hint_label(
command: None, command: None,
}) })
}) })
.collect::<Result<Vec<_>>>()?, .collect::<Cancellable<Vec<_>>>()?,
), ),
}) })
} }
@ -794,7 +794,7 @@ pub(crate) fn optional_versioned_text_document_identifier(
pub(crate) fn location( pub(crate) fn location(
snap: &GlobalStateSnapshot, snap: &GlobalStateSnapshot,
frange: FileRange, frange: FileRange,
) -> Result<lsp_types::Location> { ) -> Cancellable<lsp_types::Location> {
let url = url(snap, frange.file_id); let url = url(snap, frange.file_id);
let line_index = snap.file_line_index(frange.file_id)?; let line_index = snap.file_line_index(frange.file_id)?;
let range = range(&line_index, frange.range); let range = range(&line_index, frange.range);
@ -806,7 +806,7 @@ pub(crate) fn location(
pub(crate) fn location_from_nav( pub(crate) fn location_from_nav(
snap: &GlobalStateSnapshot, snap: &GlobalStateSnapshot,
nav: NavigationTarget, nav: NavigationTarget,
) -> Result<lsp_types::Location> { ) -> Cancellable<lsp_types::Location> {
let url = url(snap, nav.file_id); let url = url(snap, nav.file_id);
let line_index = snap.file_line_index(nav.file_id)?; let line_index = snap.file_line_index(nav.file_id)?;
let range = range(&line_index, nav.full_range); let range = range(&line_index, nav.full_range);
@ -818,7 +818,7 @@ pub(crate) fn location_link(
snap: &GlobalStateSnapshot, snap: &GlobalStateSnapshot,
src: Option<FileRange>, src: Option<FileRange>,
target: NavigationTarget, target: NavigationTarget,
) -> Result<lsp_types::LocationLink> { ) -> Cancellable<lsp_types::LocationLink> {
let origin_selection_range = match src { let origin_selection_range = match src {
Some(src) => { Some(src) => {
let line_index = snap.file_line_index(src.file_id)?; let line_index = snap.file_line_index(src.file_id)?;
@ -840,7 +840,7 @@ pub(crate) fn location_link(
fn location_info( fn location_info(
snap: &GlobalStateSnapshot, snap: &GlobalStateSnapshot,
target: NavigationTarget, target: NavigationTarget,
) -> Result<(lsp_types::Url, lsp_types::Range, lsp_types::Range)> { ) -> Cancellable<(lsp_types::Url, lsp_types::Range, lsp_types::Range)> {
let line_index = snap.file_line_index(target.file_id)?; let line_index = snap.file_line_index(target.file_id)?;
let target_uri = url(snap, target.file_id); let target_uri = url(snap, target.file_id);
@ -854,12 +854,12 @@ pub(crate) fn goto_definition_response(
snap: &GlobalStateSnapshot, snap: &GlobalStateSnapshot,
src: Option<FileRange>, src: Option<FileRange>,
targets: Vec<NavigationTarget>, targets: Vec<NavigationTarget>,
) -> Result<lsp_types::GotoDefinitionResponse> { ) -> Cancellable<lsp_types::GotoDefinitionResponse> {
if snap.config.location_link() { if snap.config.location_link() {
let links = targets let links = targets
.into_iter() .into_iter()
.map(|nav| location_link(snap, src, nav)) .map(|nav| location_link(snap, src, nav))
.collect::<Result<Vec<_>>>()?; .collect::<Cancellable<Vec<_>>>()?;
Ok(links.into()) Ok(links.into())
} else { } else {
let locations = targets let locations = targets
@ -867,7 +867,7 @@ pub(crate) fn goto_definition_response(
.map(|nav| { .map(|nav| {
location(snap, FileRange { file_id: nav.file_id, range: nav.focus_or_full_range() }) location(snap, FileRange { file_id: nav.file_id, range: nav.focus_or_full_range() })
}) })
.collect::<Result<Vec<_>>>()?; .collect::<Cancellable<Vec<_>>>()?;
Ok(locations.into()) Ok(locations.into())
} }
} }
@ -881,7 +881,7 @@ pub(crate) fn snippet_text_document_edit(
is_snippet: bool, is_snippet: bool,
file_id: FileId, file_id: FileId,
edit: TextEdit, edit: TextEdit,
) -> Result<lsp_ext::SnippetTextDocumentEdit> { ) -> Cancellable<lsp_ext::SnippetTextDocumentEdit> {
let text_document = optional_versioned_text_document_identifier(snap, file_id); let text_document = optional_versioned_text_document_identifier(snap, file_id);
let line_index = snap.file_line_index(file_id)?; let line_index = snap.file_line_index(file_id)?;
let mut edits: Vec<_> = let mut edits: Vec<_> =
@ -958,7 +958,7 @@ pub(crate) fn snippet_text_document_ops(
pub(crate) fn snippet_workspace_edit( pub(crate) fn snippet_workspace_edit(
snap: &GlobalStateSnapshot, snap: &GlobalStateSnapshot,
source_change: SourceChange, source_change: SourceChange,
) -> Result<lsp_ext::SnippetWorkspaceEdit> { ) -> Cancellable<lsp_ext::SnippetWorkspaceEdit> {
let mut document_changes: Vec<lsp_ext::SnippetDocumentChangeOperation> = Vec::new(); let mut document_changes: Vec<lsp_ext::SnippetDocumentChangeOperation> = Vec::new();
for op in source_change.file_system_edits { for op in source_change.file_system_edits {
@ -995,7 +995,7 @@ pub(crate) fn snippet_workspace_edit(
pub(crate) fn workspace_edit( pub(crate) fn workspace_edit(
snap: &GlobalStateSnapshot, snap: &GlobalStateSnapshot,
source_change: SourceChange, source_change: SourceChange,
) -> Result<lsp_types::WorkspaceEdit> { ) -> Cancellable<lsp_types::WorkspaceEdit> {
assert!(!source_change.is_snippet); assert!(!source_change.is_snippet);
snippet_workspace_edit(snap, source_change).map(|it| it.into()) snippet_workspace_edit(snap, source_change).map(|it| it.into())
} }
@ -1048,7 +1048,7 @@ impl From<lsp_ext::SnippetTextEdit>
pub(crate) fn call_hierarchy_item( pub(crate) fn call_hierarchy_item(
snap: &GlobalStateSnapshot, snap: &GlobalStateSnapshot,
target: NavigationTarget, target: NavigationTarget,
) -> Result<lsp_types::CallHierarchyItem> { ) -> Cancellable<lsp_types::CallHierarchyItem> {
let name = target.name.to_string(); let name = target.name.to_string();
let detail = target.description.clone(); let detail = target.description.clone();
let kind = target.kind.map(symbol_kind).unwrap_or(lsp_types::SymbolKind::FUNCTION); let kind = target.kind.map(symbol_kind).unwrap_or(lsp_types::SymbolKind::FUNCTION);
@ -1080,7 +1080,7 @@ pub(crate) fn code_action(
snap: &GlobalStateSnapshot, snap: &GlobalStateSnapshot,
assist: Assist, assist: Assist,
resolve_data: Option<(usize, lsp_types::CodeActionParams)>, resolve_data: Option<(usize, lsp_types::CodeActionParams)>,
) -> Result<lsp_ext::CodeAction> { ) -> Cancellable<lsp_ext::CodeAction> {
let mut res = lsp_ext::CodeAction { let mut res = lsp_ext::CodeAction {
title: assist.label.to_string(), title: assist.label.to_string(),
group: assist.group.filter(|_| snap.config.code_action_group()).map(|gr| gr.0), group: assist.group.filter(|_| snap.config.code_action_group()).map(|gr| gr.0),
@ -1113,13 +1113,13 @@ pub(crate) fn code_action(
pub(crate) fn runnable( pub(crate) fn runnable(
snap: &GlobalStateSnapshot, snap: &GlobalStateSnapshot,
runnable: Runnable, runnable: Runnable,
) -> Result<lsp_ext::Runnable> { ) -> Cancellable<lsp_ext::Runnable> {
let config = snap.config.runnables(); let config = snap.config.runnables();
let spec = CargoTargetSpec::for_file(snap, runnable.nav.file_id)?; let spec = CargoTargetSpec::for_file(snap, runnable.nav.file_id)?;
let workspace_root = spec.as_ref().map(|it| it.workspace_root.clone()); let workspace_root = spec.as_ref().map(|it| it.workspace_root.clone());
let target = spec.as_ref().map(|s| s.target.clone()); let target = spec.as_ref().map(|s| s.target.clone());
let (cargo_args, executable_args) = let (cargo_args, executable_args) =
CargoTargetSpec::runnable_args(snap, spec, &runnable.kind, &runnable.cfg)?; CargoTargetSpec::runnable_args(snap, spec, &runnable.kind, &runnable.cfg);
let label = runnable.label(target); let label = runnable.label(target);
let location = location_link(snap, None, runnable.nav)?; let location = location_link(snap, None, runnable.nav)?;
@ -1142,7 +1142,7 @@ pub(crate) fn code_lens(
acc: &mut Vec<lsp_types::CodeLens>, acc: &mut Vec<lsp_types::CodeLens>,
snap: &GlobalStateSnapshot, snap: &GlobalStateSnapshot,
annotation: Annotation, annotation: Annotation,
) -> Result<()> { ) -> Cancellable<()> {
let client_commands_config = snap.config.client_commands(); let client_commands_config = snap.config.client_commands();
match annotation.kind { match annotation.kind {
AnnotationKind::Runnable(run) => { AnnotationKind::Runnable(run) => {