557: remove Canceled from impl of ra_ide_api r=matklad a=matklad



Co-authored-by: Aleksey Kladov <aleksey.kladov@gmail.com>
This commit is contained in:
bors[bot] 2019-01-15 18:10:13 +00:00
commit 6fba078ab6
22 changed files with 254 additions and 356 deletions

View File

@ -21,8 +21,6 @@ pub struct Canceled {
_private: (),
}
pub type Cancelable<T> = Result<T, Canceled>;
impl Canceled {
pub(crate) fn new() -> Canceled {
Canceled { _private: () }

View File

@ -10,7 +10,7 @@ use std::panic;
use ra_syntax::{TextUnit, TextRange, SourceFile, TreeArc};
pub use crate::{
cancellation::{Canceled, Cancelable},
cancellation::Canceled,
syntax_ptr::LocalSyntaxPtr,
input::{
FilesDatabase, FileId, CrateId, SourceRoot, SourceRootId, CrateGraph, Dependency,

View File

@ -1,6 +1,5 @@
use std::sync::Arc;
use ra_db::Cancelable;
use ra_syntax::{
SyntaxNode,
ast::{self, NameOwner, StructFlavor, AstNode}
@ -18,8 +17,8 @@ impl Struct {
Struct { def_id }
}
pub(crate) fn variant_data(&self, db: &impl HirDatabase) -> Cancelable<Arc<VariantData>> {
Ok(db.struct_data(self.def_id).variant_data.clone())
pub(crate) fn variant_data(&self, db: &impl HirDatabase) -> Arc<VariantData> {
db.struct_data(self.def_id).variant_data.clone()
}
}

View File

@ -1,7 +1,7 @@
use std::sync::Arc;
use relative_path::RelativePathBuf;
use ra_db::{CrateId, Cancelable, FileId};
use ra_db::{CrateId, FileId};
use ra_syntax::{ast, TreeArc, SyntaxNode};
use crate::{
@ -142,10 +142,7 @@ impl Module {
self.resolve_path_impl(db, path)
}
pub fn problems(
&self,
db: &impl HirDatabase,
) -> Cancelable<Vec<(TreeArc<SyntaxNode>, Problem)>> {
pub fn problems(&self, db: &impl HirDatabase) -> Vec<(TreeArc<SyntaxNode>, Problem)> {
self.problems_impl(db)
}
}
@ -160,7 +157,7 @@ impl StructField {
pub fn name(&self) -> &Name {
&self.name
}
pub fn ty(&self, db: &impl HirDatabase) -> Cancelable<Option<Ty>> {
pub fn ty(&self, db: &impl HirDatabase) -> Option<Ty> {
db.type_for_field(self.struct_.def_id, self.name.clone())
}
}
@ -318,7 +315,7 @@ impl Function {
db.fn_signature(self.def_id)
}
pub fn infer(&self, db: &impl HirDatabase) -> Cancelable<Arc<InferenceResult>> {
pub fn infer(&self, db: &impl HirDatabase) -> Arc<InferenceResult> {
db.infer(self.def_id)
}
}

View File

@ -1,4 +1,4 @@
use ra_db::{Cancelable, SourceRootId, FileId};
use ra_db::{SourceRootId, FileId};
use ra_syntax::{ast, SyntaxNode, AstNode, TreeArc};
use crate::{
@ -176,12 +176,9 @@ impl Module {
curr_per_ns
}
pub fn problems_impl(
&self,
db: &impl HirDatabase,
) -> Cancelable<Vec<(TreeArc<SyntaxNode>, Problem)>> {
pub fn problems_impl(&self, db: &impl HirDatabase) -> Vec<(TreeArc<SyntaxNode>, Problem)> {
let loc = self.def_id.loc(db);
let module_tree = db.module_tree(loc.source_root_id);
Ok(loc.module_id.problems(&module_tree, db))
loc.module_id.problems(&module_tree, db)
}
}

View File

@ -1,7 +1,7 @@
use std::sync::Arc;
use ra_syntax::{SyntaxNode, TreeArc, SourceFile};
use ra_db::{SourceRootId, LocationIntener, SyntaxDatabase, Cancelable};
use ra_db::{SourceRootId, LocationIntener, SyntaxDatabase};
use crate::{
DefLoc, DefId, MacroCallLoc, MacroCallId, Name, HirFileId,
@ -52,17 +52,17 @@ pub trait HirDatabase: SyntaxDatabase
use fn crate::adt::EnumVariantData::enum_variant_data_query;
}
fn infer(def_id: DefId) -> Cancelable<Arc<InferenceResult>> {
fn infer(def_id: DefId) -> Arc<InferenceResult> {
type InferQuery;
use fn crate::ty::infer;
}
fn type_for_def(def_id: DefId) -> Cancelable<Ty> {
fn type_for_def(def_id: DefId) -> Ty {
type TypeForDefQuery;
use fn crate::ty::type_for_def;
}
fn type_for_field(def_id: DefId, field: Name) -> Cancelable<Option<Ty>> {
fn type_for_field(def_id: DefId, field: Name) -> Option<Ty> {
type TypeForFieldQuery;
use fn crate::ty::type_for_field;
}
@ -102,7 +102,7 @@ pub trait HirDatabase: SyntaxDatabase
use fn crate::impl_block::impls_in_module;
}
fn impls_in_crate(krate: Crate) -> Cancelable<Arc<CrateImplBlocks>> {
fn impls_in_crate(krate: Crate) -> Arc<CrateImplBlocks> {
type ImplsInCrateQuery;
use fn crate::ty::method_resolution::CrateImplBlocks::impls_in_crate_query;
}

View File

@ -5,15 +5,6 @@
//! to a particular crate instance. That is, it has cfg flags and features
//! applied. So, the relation between syntax and HIR is many-to-one.
macro_rules! ctry {
($expr:expr) => {
match $expr {
None => return Ok(None),
Some(it) => it,
}
};
}
pub mod db;
#[cfg(test)]
mod mock;

View File

@ -30,8 +30,6 @@ use ra_arena::map::ArenaMap;
use join_to_string::join;
use rustc_hash::FxHashMap;
use ra_db::Cancelable;
use crate::{
Def, DefId, Module, Function, Struct, Enum, EnumVariant, Path, Name, ImplBlock,
FnSignature, FnScopes,
@ -41,14 +39,6 @@ use crate::{
expr::{Body, Expr, Literal, ExprId, PatId, UnaryOp, BinaryOp, Statement},
};
fn transpose<T>(x: Cancelable<Option<T>>) -> Option<Cancelable<T>> {
match x {
Ok(Some(t)) => Some(Ok(t)),
Ok(None) => None,
Err(e) => Some(Err(e)),
}
}
/// The ID of a type variable.
#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
pub struct TypeVarId(u32);
@ -271,28 +261,28 @@ impl Ty {
module: &Module,
impl_block: Option<&ImplBlock>,
type_ref: &TypeRef,
) -> Cancelable<Self> {
Ok(match type_ref {
) -> Self {
match type_ref {
TypeRef::Never => Ty::Never,
TypeRef::Tuple(inner) => {
let inner_tys = inner
.iter()
.map(|tr| Ty::from_hir(db, module, impl_block, tr))
.collect::<Cancelable<Vec<_>>>()?;
.collect::<Vec<_>>();
Ty::Tuple(inner_tys.into())
}
TypeRef::Path(path) => Ty::from_hir_path(db, module, impl_block, path)?,
TypeRef::Path(path) => Ty::from_hir_path(db, module, impl_block, path),
TypeRef::RawPtr(inner, mutability) => {
let inner_ty = Ty::from_hir(db, module, impl_block, inner)?;
let inner_ty = Ty::from_hir(db, module, impl_block, inner);
Ty::RawPtr(Arc::new(inner_ty), *mutability)
}
TypeRef::Array(_inner) => Ty::Unknown, // TODO
TypeRef::Slice(inner) => {
let inner_ty = Ty::from_hir(db, module, impl_block, inner)?;
let inner_ty = Ty::from_hir(db, module, impl_block, inner);
Ty::Slice(Arc::new(inner_ty))
}
TypeRef::Reference(inner, mutability) => {
let inner_ty = Ty::from_hir(db, module, impl_block, inner)?;
let inner_ty = Ty::from_hir(db, module, impl_block, inner);
Ty::Ref(Arc::new(inner_ty), *mutability)
}
TypeRef::Placeholder => Ty::Unknown,
@ -300,7 +290,7 @@ impl Ty {
let mut inner_tys = params
.iter()
.map(|tr| Ty::from_hir(db, module, impl_block, tr))
.collect::<Cancelable<Vec<_>>>()?;
.collect::<Vec<_>>();
let return_ty = inner_tys
.pop()
.expect("TypeRef::Fn should always have at least return type");
@ -311,7 +301,7 @@ impl Ty {
Ty::FnPtr(Arc::new(sig))
}
TypeRef::Error => Ty::Unknown,
})
}
}
pub(crate) fn from_hir_opt(
@ -319,10 +309,8 @@ impl Ty {
module: &Module,
impl_block: Option<&ImplBlock>,
type_ref: Option<&TypeRef>,
) -> Cancelable<Self> {
type_ref
.map(|t| Ty::from_hir(db, module, impl_block, t))
.unwrap_or(Ok(Ty::Unknown))
) -> Self {
type_ref.map_or(Ty::Unknown, |t| Ty::from_hir(db, module, impl_block, t))
}
pub(crate) fn from_hir_path(
@ -330,19 +318,19 @@ impl Ty {
module: &Module,
impl_block: Option<&ImplBlock>,
path: &Path,
) -> Cancelable<Self> {
) -> Self {
if let Some(name) = path.as_ident() {
if let Some(int_ty) = primitive::UncertainIntTy::from_name(name) {
return Ok(Ty::Int(int_ty));
return Ty::Int(int_ty);
} else if let Some(float_ty) = primitive::UncertainFloatTy::from_name(name) {
return Ok(Ty::Float(float_ty));
return Ty::Float(float_ty);
} else if name.as_known_name() == Some(KnownName::SelfType) {
return Ty::from_hir_opt(db, module, None, impl_block.map(|i| i.target_type()));
} else if let Some(known) = name.as_known_name() {
match known {
KnownName::Bool => return Ok(Ty::Bool),
KnownName::Char => return Ok(Ty::Char),
KnownName::Str => return Ok(Ty::Str),
KnownName::Bool => return Ty::Bool,
KnownName::Char => return Ty::Char,
KnownName::Str => return Ty::Str,
_ => {}
}
}
@ -352,10 +340,9 @@ impl Ty {
let resolved = if let Some(r) = module.resolve_path(db, path).take_types() {
r
} else {
return Ok(Ty::Unknown);
return Ty::Unknown;
};
let ty = db.type_for_def(resolved)?;
Ok(ty)
db.type_for_def(resolved)
}
pub fn unit() -> Self {
@ -445,7 +432,7 @@ impl fmt::Display for Ty {
/// Compute the declared type of a function. This should not need to look at the
/// function body.
fn type_for_fn(db: &impl HirDatabase, f: Function) -> Cancelable<Ty> {
fn type_for_fn(db: &impl HirDatabase, f: Function) -> Ty {
let signature = f.signature(db);
let module = f.module(db);
let impl_block = f.impl_block(db);
@ -454,38 +441,38 @@ fn type_for_fn(db: &impl HirDatabase, f: Function) -> Cancelable<Ty> {
.params()
.iter()
.map(|tr| Ty::from_hir(db, &module, impl_block.as_ref(), tr))
.collect::<Cancelable<Vec<_>>>()?;
let output = Ty::from_hir(db, &module, impl_block.as_ref(), signature.ret_type())?;
.collect::<Vec<_>>();
let output = Ty::from_hir(db, &module, impl_block.as_ref(), signature.ret_type());
let sig = FnSig { input, output };
Ok(Ty::FnPtr(Arc::new(sig)))
Ty::FnPtr(Arc::new(sig))
}
fn type_for_struct(db: &impl HirDatabase, s: Struct) -> Cancelable<Ty> {
Ok(Ty::Adt {
fn type_for_struct(db: &impl HirDatabase, s: Struct) -> Ty {
Ty::Adt {
def_id: s.def_id(),
name: s.name(db).unwrap_or_else(Name::missing),
})
}
}
pub(crate) fn type_for_enum(db: &impl HirDatabase, s: Enum) -> Cancelable<Ty> {
Ok(Ty::Adt {
pub(crate) fn type_for_enum(db: &impl HirDatabase, s: Enum) -> Ty {
Ty::Adt {
def_id: s.def_id(),
name: s.name(db).unwrap_or_else(Name::missing),
})
}
}
pub(crate) fn type_for_enum_variant(db: &impl HirDatabase, ev: EnumVariant) -> Cancelable<Ty> {
pub(crate) fn type_for_enum_variant(db: &impl HirDatabase, ev: EnumVariant) -> Ty {
let enum_parent = ev.parent_enum(db);
type_for_enum(db, enum_parent)
}
pub(super) fn type_for_def(db: &impl HirDatabase, def_id: DefId) -> Cancelable<Ty> {
pub(super) fn type_for_def(db: &impl HirDatabase, def_id: DefId) -> Ty {
let def = def_id.resolve(db);
match def {
Def::Module(..) => {
log::debug!("trying to get type for module {:?}", def_id);
Ok(Ty::Unknown)
Ty::Unknown
}
Def::Function(f) => type_for_fn(db, f),
Def::Struct(s) => type_for_struct(db, s),
@ -497,19 +484,15 @@ pub(super) fn type_for_def(db: &impl HirDatabase, def_id: DefId) -> Cancelable<T
def_id,
def
);
Ok(Ty::Unknown)
Ty::Unknown
}
}
}
pub(super) fn type_for_field(
db: &impl HirDatabase,
def_id: DefId,
field: Name,
) -> Cancelable<Option<Ty>> {
pub(super) fn type_for_field(db: &impl HirDatabase, def_id: DefId, field: Name) -> Option<Ty> {
let def = def_id.resolve(db);
let variant_data = match def {
Def::Struct(s) => s.variant_data(db)?,
Def::Struct(s) => s.variant_data(db),
Def::EnumVariant(ev) => ev.variant_data(db),
// TODO: unions
_ => panic!(
@ -519,13 +502,8 @@ pub(super) fn type_for_field(
};
let module = def_id.module(db);
let impl_block = def_id.impl_block(db);
let type_ref = ctry!(variant_data.get_field_type_ref(&field));
Ok(Some(Ty::from_hir(
db,
&module,
impl_block.as_ref(),
&type_ref,
)?))
let type_ref = variant_data.get_field_type_ref(&field)?;
Some(Ty::from_hir(db, &module, impl_block.as_ref(), &type_ref))
}
/// The result of type inference: A mapping from expressions and patterns to types.
@ -702,7 +680,7 @@ impl<'a, D: HirDatabase> InferenceContext<'a, D> {
self.type_of_pat.insert(pat, ty);
}
fn make_ty(&self, type_ref: &TypeRef) -> Cancelable<Ty> {
fn make_ty(&self, type_ref: &TypeRef) -> Ty {
Ty::from_hir(self.db, &self.module, self.impl_block.as_ref(), type_ref)
}
@ -848,49 +826,49 @@ impl<'a, D: HirDatabase> InferenceContext<'a, D> {
})
}
fn infer_path_expr(&mut self, expr: ExprId, path: &Path) -> Cancelable<Option<Ty>> {
fn infer_path_expr(&mut self, expr: ExprId, path: &Path) -> Option<Ty> {
if path.is_ident() || path.is_self() {
// resolve locally
let name = path.as_ident().cloned().unwrap_or_else(Name::self_param);
if let Some(scope_entry) = self.scopes.resolve_local_name(expr, name) {
let ty = ctry!(self.type_of_pat.get(scope_entry.pat()));
let ty = self.type_of_pat.get(scope_entry.pat())?;
let ty = self.resolve_ty_as_possible(ty.clone());
return Ok(Some(ty));
return Some(ty);
};
};
// resolve in module
let resolved = ctry!(self.module.resolve_path(self.db, &path).take_values());
let ty = self.db.type_for_def(resolved)?;
let resolved = self.module.resolve_path(self.db, &path).take_values()?;
let ty = self.db.type_for_def(resolved);
let ty = self.insert_type_vars(ty);
Ok(Some(ty))
Some(ty)
}
fn resolve_variant(&self, path: Option<&Path>) -> Cancelable<(Ty, Option<DefId>)> {
fn resolve_variant(&self, path: Option<&Path>) -> (Ty, Option<DefId>) {
let path = if let Some(path) = path {
path
} else {
return Ok((Ty::Unknown, None));
return (Ty::Unknown, None);
};
let def_id = if let Some(def_id) = self.module.resolve_path(self.db, &path).take_types() {
def_id
} else {
return Ok((Ty::Unknown, None));
return (Ty::Unknown, None);
};
Ok(match def_id.resolve(self.db) {
match def_id.resolve(self.db) {
Def::Struct(s) => {
let ty = type_for_struct(self.db, s)?;
let ty = type_for_struct(self.db, s);
(ty, Some(def_id))
}
Def::EnumVariant(ev) => {
let ty = type_for_enum_variant(self.db, ev)?;
let ty = type_for_enum_variant(self.db, ev);
(ty, Some(def_id))
}
_ => (Ty::Unknown, None),
})
}
}
fn infer_expr(&mut self, expr: ExprId, expected: &Expectation) -> Cancelable<Ty> {
fn infer_expr(&mut self, expr: ExprId, expected: &Expectation) -> Ty {
let body = Arc::clone(&self.body); // avoid borrow checker problem
let ty = match &body[expr] {
Expr::Missing => Ty::Unknown,
@ -900,11 +878,11 @@ impl<'a, D: HirDatabase> InferenceContext<'a, D> {
else_branch,
} => {
// if let is desugared to match, so this is always simple if
self.infer_expr(*condition, &Expectation::has_type(Ty::Bool))?;
let then_ty = self.infer_expr(*then_branch, expected)?;
self.infer_expr(*condition, &Expectation::has_type(Ty::Bool));
let then_ty = self.infer_expr(*then_branch, expected);
match else_branch {
Some(else_branch) => {
self.infer_expr(*else_branch, expected)?;
self.infer_expr(*else_branch, expected);
}
None => {
// no else branch -> unit
@ -913,31 +891,31 @@ impl<'a, D: HirDatabase> InferenceContext<'a, D> {
};
then_ty
}
Expr::Block { statements, tail } => self.infer_block(statements, *tail, expected)?,
Expr::Block { statements, tail } => self.infer_block(statements, *tail, expected),
Expr::Loop { body } => {
self.infer_expr(*body, &Expectation::has_type(Ty::unit()))?;
self.infer_expr(*body, &Expectation::has_type(Ty::unit()));
// TODO handle break with value
Ty::Never
}
Expr::While { condition, body } => {
// while let is desugared to a match loop, so this is always simple while
self.infer_expr(*condition, &Expectation::has_type(Ty::Bool))?;
self.infer_expr(*body, &Expectation::has_type(Ty::unit()))?;
self.infer_expr(*condition, &Expectation::has_type(Ty::Bool));
self.infer_expr(*body, &Expectation::has_type(Ty::unit()));
Ty::unit()
}
Expr::For { iterable, body, .. } => {
let _iterable_ty = self.infer_expr(*iterable, &Expectation::none());
// TODO write type for pat
self.infer_expr(*body, &Expectation::has_type(Ty::unit()))?;
self.infer_expr(*body, &Expectation::has_type(Ty::unit()));
Ty::unit()
}
Expr::Lambda { body, .. } => {
// TODO write types for args, infer lambda type etc.
let _body_ty = self.infer_expr(*body, &Expectation::none())?;
let _body_ty = self.infer_expr(*body, &Expectation::none());
Ty::Unknown
}
Expr::Call { callee, args } => {
let callee_ty = self.infer_expr(*callee, &Expectation::none())?;
let callee_ty = self.infer_expr(*callee, &Expectation::none());
let (param_tys, ret_ty) = match &callee_ty {
Ty::FnPtr(sig) => (&sig.input[..], sig.output.clone()),
_ => {
@ -950,7 +928,7 @@ impl<'a, D: HirDatabase> InferenceContext<'a, D> {
self.infer_expr(
*arg,
&Expectation::has_type(param_tys.get(i).cloned().unwrap_or(Ty::Unknown)),
)?;
);
}
ret_ty
}
@ -959,12 +937,12 @@ impl<'a, D: HirDatabase> InferenceContext<'a, D> {
args,
method_name,
} => {
let receiver_ty = self.infer_expr(*receiver, &Expectation::none())?;
let resolved = receiver_ty.clone().lookup_method(self.db, method_name)?;
let receiver_ty = self.infer_expr(*receiver, &Expectation::none());
let resolved = receiver_ty.clone().lookup_method(self.db, method_name);
let method_ty = match resolved {
Some(def_id) => {
self.write_method_resolution(expr, def_id);
self.db.type_for_def(def_id)?
self.db.type_for_def(def_id)
}
None => Ty::Unknown,
};
@ -986,32 +964,32 @@ impl<'a, D: HirDatabase> InferenceContext<'a, D> {
self.infer_expr(
*arg,
&Expectation::has_type(param_tys.get(i).cloned().unwrap_or(Ty::Unknown)),
)?;
);
}
ret_ty
}
Expr::Match { expr, arms } => {
let _ty = self.infer_expr(*expr, &Expectation::none())?;
let _ty = self.infer_expr(*expr, &Expectation::none());
for arm in arms {
// TODO type the bindings in pats
// TODO type the guard
let _ty = self.infer_expr(arm.expr, &Expectation::none())?;
let _ty = self.infer_expr(arm.expr, &Expectation::none());
}
// TODO unify all the match arm types
Ty::Unknown
}
Expr::Path(p) => self.infer_path_expr(expr, p)?.unwrap_or(Ty::Unknown),
Expr::Path(p) => self.infer_path_expr(expr, p).unwrap_or(Ty::Unknown),
Expr::Continue => Ty::Never,
Expr::Break { expr } => {
if let Some(expr) = expr {
// TODO handle break with value
self.infer_expr(*expr, &Expectation::none())?;
self.infer_expr(*expr, &Expectation::none());
}
Ty::Never
}
Expr::Return { expr } => {
if let Some(expr) = expr {
self.infer_expr(*expr, &Expectation::has_type(self.return_ty.clone()))?;
self.infer_expr(*expr, &Expectation::has_type(self.return_ty.clone()));
}
Ty::Never
}
@ -1020,60 +998,58 @@ impl<'a, D: HirDatabase> InferenceContext<'a, D> {
fields,
spread,
} => {
let (ty, def_id) = self.resolve_variant(path.as_ref())?;
let (ty, def_id) = self.resolve_variant(path.as_ref());
for field in fields {
let field_ty = if let Some(def_id) = def_id {
self.db
.type_for_field(def_id, field.name.clone())?
.type_for_field(def_id, field.name.clone())
.unwrap_or(Ty::Unknown)
} else {
Ty::Unknown
};
self.infer_expr(field.expr, &Expectation::has_type(field_ty))?;
self.infer_expr(field.expr, &Expectation::has_type(field_ty));
}
if let Some(expr) = spread {
self.infer_expr(*expr, &Expectation::has_type(ty.clone()))?;
self.infer_expr(*expr, &Expectation::has_type(ty.clone()));
}
ty
}
Expr::Field { expr, name } => {
let receiver_ty = self.infer_expr(*expr, &Expectation::none())?;
let receiver_ty = self.infer_expr(*expr, &Expectation::none());
let ty = receiver_ty
.autoderef(self.db)
.find_map(|derefed_ty| match derefed_ty {
// this is more complicated than necessary because type_for_field is cancelable
Ty::Tuple(fields) => {
let i = name.to_string().parse::<usize>().ok();
i.and_then(|i| fields.get(i).cloned()).map(Ok)
}
Ty::Adt { def_id, .. } => {
transpose(self.db.type_for_field(def_id, name.clone()))
i.and_then(|i| fields.get(i).cloned())
}
Ty::Adt { def_id, .. } => self.db.type_for_field(def_id, name.clone()),
_ => None,
})
.unwrap_or(Ok(Ty::Unknown))?;
.unwrap_or(Ty::Unknown);
self.insert_type_vars(ty)
}
Expr::Try { expr } => {
let _inner_ty = self.infer_expr(*expr, &Expectation::none())?;
let _inner_ty = self.infer_expr(*expr, &Expectation::none());
Ty::Unknown
}
Expr::Cast { expr, type_ref } => {
let _inner_ty = self.infer_expr(*expr, &Expectation::none())?;
let _inner_ty = self.infer_expr(*expr, &Expectation::none());
let cast_ty =
Ty::from_hir(self.db, &self.module, self.impl_block.as_ref(), type_ref)?;
Ty::from_hir(self.db, &self.module, self.impl_block.as_ref(), type_ref);
let cast_ty = self.insert_type_vars(cast_ty);
// TODO check the cast...
cast_ty
}
Expr::Ref { expr, mutability } => {
// TODO pass the expectation down
let inner_ty = self.infer_expr(*expr, &Expectation::none())?;
let inner_ty = self.infer_expr(*expr, &Expectation::none());
// TODO reference coercions etc.
Ty::Ref(Arc::new(inner_ty), *mutability)
}
Expr::UnaryOp { expr, op } => {
let inner_ty = self.infer_expr(*expr, &Expectation::none())?;
let inner_ty = self.infer_expr(*expr, &Expectation::none());
match op {
Some(UnaryOp::Deref) => {
if let Some(derefed_ty) = inner_ty.builtin_deref() {
@ -1094,11 +1070,11 @@ impl<'a, D: HirDatabase> InferenceContext<'a, D> {
}
_ => Expectation::none(),
};
let lhs_ty = self.infer_expr(*lhs, &lhs_expectation)?;
let lhs_ty = self.infer_expr(*lhs, &lhs_expectation);
// TODO: find implementation of trait corresponding to operation
// symbol and resolve associated `Output` type
let rhs_expectation = binary_op_rhs_expectation(*op, lhs_ty);
let rhs_ty = self.infer_expr(*rhs, &Expectation::has_type(rhs_expectation))?;
let rhs_ty = self.infer_expr(*rhs, &Expectation::has_type(rhs_expectation));
// TODO: similar as above, return ty is often associated trait type
binary_op_return_ty(*op, rhs_ty)
@ -1108,7 +1084,7 @@ impl<'a, D: HirDatabase> InferenceContext<'a, D> {
Expr::Tuple { exprs } => {
let mut ty_vec = Vec::with_capacity(exprs.len());
for arg in exprs.iter() {
ty_vec.push(self.infer_expr(*arg, &Expectation::none())?);
ty_vec.push(self.infer_expr(*arg, &Expectation::none()));
}
Ty::Tuple(Arc::from(ty_vec))
@ -1133,7 +1109,7 @@ impl<'a, D: HirDatabase> InferenceContext<'a, D> {
self.unify(&ty, &expected.ty);
let ty = self.resolve_ty_as_possible(ty);
self.write_expr_ty(expr, ty.clone());
Ok(ty)
ty
}
fn infer_block(
@ -1141,7 +1117,7 @@ impl<'a, D: HirDatabase> InferenceContext<'a, D> {
statements: &[Statement],
tail: Option<ExprId>,
expected: &Expectation,
) -> Cancelable<Ty> {
) -> Ty {
for stmt in statements {
match stmt {
Statement::Let {
@ -1154,10 +1130,10 @@ impl<'a, D: HirDatabase> InferenceContext<'a, D> {
&self.module,
self.impl_block.as_ref(),
type_ref.as_ref(),
)?;
);
let decl_ty = self.insert_type_vars(decl_ty);
let ty = if let Some(expr) = initializer {
let expr_ty = self.infer_expr(*expr, &Expectation::has_type(decl_ty))?;
let expr_ty = self.infer_expr(*expr, &Expectation::has_type(decl_ty));
expr_ty
} else {
decl_ty
@ -1166,43 +1142,41 @@ impl<'a, D: HirDatabase> InferenceContext<'a, D> {
self.write_pat_ty(*pat, ty);
}
Statement::Expr(expr) => {
self.infer_expr(*expr, &Expectation::none())?;
self.infer_expr(*expr, &Expectation::none());
}
}
}
let ty = if let Some(expr) = tail {
self.infer_expr(expr, expected)?
self.infer_expr(expr, expected)
} else {
Ty::unit()
};
Ok(ty)
ty
}
fn collect_fn_signature(&mut self, signature: &FnSignature) -> Cancelable<()> {
fn collect_fn_signature(&mut self, signature: &FnSignature) {
let body = Arc::clone(&self.body); // avoid borrow checker problem
for (type_ref, pat) in signature.params().iter().zip(body.params()) {
let ty = self.make_ty(type_ref)?;
let ty = self.make_ty(type_ref);
let ty = self.insert_type_vars(ty);
self.write_pat_ty(*pat, ty);
}
self.return_ty = {
let ty = self.make_ty(signature.ret_type())?;
let ty = self.make_ty(signature.ret_type());
let ty = self.insert_type_vars(ty);
ty
};
Ok(())
}
fn infer_body(&mut self) -> Cancelable<()> {
fn infer_body(&mut self) {
self.infer_expr(
self.body.body_expr(),
&Expectation::has_type(self.return_ty.clone()),
)?;
Ok(())
);
}
}
pub fn infer(db: &impl HirDatabase, def_id: DefId) -> Cancelable<Arc<InferenceResult>> {
pub fn infer(db: &impl HirDatabase, def_id: DefId) -> Arc<InferenceResult> {
db.check_canceled();
let function = Function::new(def_id); // TODO: consts also need inference
let body = function.body(db);
@ -1212,9 +1186,9 @@ pub fn infer(db: &impl HirDatabase, def_id: DefId) -> Cancelable<Arc<InferenceRe
let mut ctx = InferenceContext::new(db, body, scopes, module, impl_block);
let signature = function.signature(db);
ctx.collect_fn_signature(&signature)?;
ctx.collect_fn_signature(&signature);
ctx.infer_body()?;
ctx.infer_body();
Ok(Arc::new(ctx.resolve_all()))
Arc::new(ctx.resolve_all())
}

View File

@ -6,7 +6,7 @@ use std::sync::Arc;
use rustc_hash::FxHashMap;
use ra_db::{Cancelable, SourceRootId};
use ra_db::SourceRootId;
use crate::{HirDatabase, DefId, module_tree::ModuleId, Module, Crate, Name, Function, impl_block::{ImplId, ImplBlock, ImplItem}};
use super::Ty;
@ -42,7 +42,7 @@ impl CrateImplBlocks {
&'a self,
db: &'a impl HirDatabase,
ty: &Ty,
) -> impl Iterator<Item = Cancelable<ImplBlock>> + 'a {
) -> impl Iterator<Item = ImplBlock> + 'a {
let fingerprint = TyFingerprint::for_impl(ty);
fingerprint
.and_then(|f| self.impls.get(&f))
@ -50,11 +50,11 @@ impl CrateImplBlocks {
.flat_map(|i| i.iter())
.map(move |(module_id, impl_id)| {
let module_impl_blocks = db.impls_in_module(self.source_root_id, *module_id);
Ok(ImplBlock::from_id(module_impl_blocks, *impl_id))
ImplBlock::from_id(module_impl_blocks, *impl_id)
})
}
fn collect_recursive(&mut self, db: &impl HirDatabase, module: Module) -> Cancelable<()> {
fn collect_recursive(&mut self, db: &impl HirDatabase, module: Module) {
let module_id = module.def_id.loc(db).module_id;
let module_impl_blocks = db.impls_in_module(self.source_root_id, module_id);
@ -65,7 +65,7 @@ impl CrateImplBlocks {
// ignore for now
} else {
let target_ty =
Ty::from_hir(db, &module, Some(&impl_block), impl_data.target_type())?;
Ty::from_hir(db, &module, Some(&impl_block), impl_data.target_type());
if let Some(target_ty_fp) = TyFingerprint::for_impl(&target_ty) {
self.impls
.entry(target_ty_fp)
@ -76,16 +76,14 @@ impl CrateImplBlocks {
}
for child in module.children(db) {
self.collect_recursive(db, child)?;
self.collect_recursive(db, child);
}
Ok(())
}
pub(crate) fn impls_in_crate_query(
db: &impl HirDatabase,
krate: Crate,
) -> Cancelable<Arc<CrateImplBlocks>> {
) -> Arc<CrateImplBlocks> {
let crate_graph = db.crate_graph();
let file_id = crate_graph.crate_root(krate.crate_id);
let source_root_id = db.file_source_root(file_id);
@ -94,9 +92,9 @@ impl CrateImplBlocks {
impls: FxHashMap::default(),
};
if let Some(module) = krate.root_module(db) {
crate_impl_blocks.collect_recursive(db, module)?;
crate_impl_blocks.collect_recursive(db, module);
}
Ok(Arc::new(crate_impl_blocks))
Arc::new(crate_impl_blocks)
}
}
@ -111,13 +109,13 @@ impl Ty {
// TODO: cache this as a query?
// - if so, what signature? (TyFingerprint, Name)?
// - or maybe cache all names and def_ids of methods per fingerprint?
pub fn lookup_method(self, db: &impl HirDatabase, name: &Name) -> Cancelable<Option<DefId>> {
pub fn lookup_method(self, db: &impl HirDatabase, name: &Name) -> Option<DefId> {
self.iterate_methods(db, |f| {
let sig = f.signature(db);
if sig.name() == name && sig.has_self_param() {
Ok(Some(f.def_id()))
Some(f.def_id())
} else {
Ok(None)
None
}
})
}
@ -127,8 +125,8 @@ impl Ty {
pub fn iterate_methods<T>(
self,
db: &impl HirDatabase,
mut callback: impl FnMut(Function) -> Cancelable<Option<T>>,
) -> Cancelable<Option<T>> {
mut callback: impl FnMut(Function) -> Option<T>,
) -> Option<T> {
// For method calls, rust first does any number of autoderef, and then one
// autoref (i.e. when the method takes &self or &mut self). We just ignore
// the autoref currently -- when we find a method matching the given name,
@ -143,15 +141,14 @@ impl Ty {
Some(krate) => krate,
None => continue,
};
let impls = db.impls_in_crate(krate)?;
let impls = db.impls_in_crate(krate);
for impl_block in impls.lookup_impl_blocks(db, &derefed_ty) {
let impl_block = impl_block?;
for item in impl_block.items() {
match item {
ImplItem::Method(f) => {
if let Some(result) = callback(f.clone())? {
return Ok(Some(result));
if let Some(result) = callback(f.clone()) {
return Some(result);
}
}
_ => {}
@ -159,6 +156,6 @@ impl Ty {
}
}
}
Ok(None)
None
}
}

View File

@ -321,7 +321,7 @@ fn infer(content: &str) -> String {
.filter_map(ast::FnDef::cast)
{
let func = source_binder::function_from_source(&db, file_id, fn_def).unwrap();
let inference_result = func.infer(&db).unwrap();
let inference_result = func.infer(&db);
let body_syntax_mapping = func.body_syntax_mapping(&db);
let mut types = Vec::new();
for (pat, ty) in inference_result.type_of_pat.iter() {
@ -405,7 +405,7 @@ fn typing_whitespace_inside_a_function_should_not_invalidate_types() {
let func = source_binder::function_from_position(&db, pos).unwrap();
{
let events = db.log_executed(|| {
func.infer(&db).unwrap();
func.infer(&db);
});
assert!(format!("{:?}", events).contains("infer"))
}
@ -424,7 +424,7 @@ fn typing_whitespace_inside_a_function_should_not_invalidate_types() {
{
let events = db.log_executed(|| {
func.infer(&db).unwrap();
func.infer(&db);
});
assert!(!format!("{:?}", events).contains("infer"), "{:#?}", events)
}

View File

@ -1,6 +1,6 @@
use std::cmp::{max, min};
use ra_db::{SyntaxDatabase, Cancelable};
use ra_db::SyntaxDatabase;
use ra_syntax::{
AstNode, SyntaxNode, TextUnit, TextRange,
SyntaxKind::FN_DEF,
@ -11,21 +11,23 @@ use ra_syntax::{
use crate::{FilePosition, CallInfo, db::RootDatabase};
/// Computes parameter information for the given call expression.
pub(crate) fn call_info(db: &RootDatabase, position: FilePosition) -> Cancelable<Option<CallInfo>> {
pub(crate) fn call_info(db: &RootDatabase, position: FilePosition) -> Option<CallInfo> {
let file = db.source_file(position.file_id);
let syntax = file.syntax();
// Find the calling expression and it's NameRef
let calling_node = ctry!(FnCallNode::with_node(syntax, position.offset));
let name_ref = ctry!(calling_node.name_ref());
let calling_node = FnCallNode::with_node(syntax, position.offset)?;
let name_ref = calling_node.name_ref()?;
// Resolve the function's NameRef (NOTE: this isn't entirely accurate).
let file_symbols = db.index_resolve(name_ref);
let symbol = ctry!(file_symbols.into_iter().find(|it| it.ptr.kind() == FN_DEF));
let symbol = file_symbols
.into_iter()
.find(|it| it.ptr.kind() == FN_DEF)?;
let fn_file = db.source_file(symbol.file_id);
let fn_def = symbol.ptr.resolve(&fn_file);
let fn_def = ast::FnDef::cast(&fn_def).unwrap();
let mut call_info = ctry!(CallInfo::new(fn_def));
let mut call_info = CallInfo::new(fn_def)?;
// If we have a calling expression let's find which argument we are on
let num_params = call_info.parameters.len();
let has_self = fn_def.param_list().and_then(|l| l.self_param()).is_some();
@ -61,7 +63,7 @@ pub(crate) fn call_info(db: &RootDatabase, position: FilePosition) -> Cancelable
}
}
Ok(Some(call_info))
Some(call_info)
}
enum FnCallNode<'a> {

View File

@ -12,7 +12,7 @@ use ra_db::SyntaxDatabase;
use crate::{
db,
Cancelable, FilePosition,
FilePosition,
completion::{
completion_item::{Completions, CompletionKind},
completion_context::CompletionContext,
@ -43,12 +43,9 @@ pub use crate::completion::completion_item::{CompletionItem, InsertText, Complet
/// `foo` *should* be present among the completion variants. Filtering by
/// identifier prefix/fuzzy match should be done higher in the stack, together
/// with ordering of completions (currently this is done by the client).
pub(crate) fn completions(
db: &db::RootDatabase,
position: FilePosition,
) -> Cancelable<Option<Completions>> {
pub(crate) fn completions(db: &db::RootDatabase, position: FilePosition) -> Option<Completions> {
let original_file = db.source_file(position.file_id);
let ctx = ctry!(CompletionContext::new(db, &original_file, position)?);
let ctx = CompletionContext::new(db, &original_file, position)?;
let mut acc = Completions::default();
@ -57,11 +54,11 @@ pub(crate) fn completions(
complete_keyword::complete_use_tree_keyword(&mut acc, &ctx);
complete_snippet::complete_expr_snippet(&mut acc, &ctx);
complete_snippet::complete_item_snippet(&mut acc, &ctx);
complete_path::complete_path(&mut acc, &ctx)?;
complete_scope::complete_scope(&mut acc, &ctx)?;
complete_dot::complete_dot(&mut acc, &ctx)?;
complete_path::complete_path(&mut acc, &ctx);
complete_scope::complete_scope(&mut acc, &ctx);
complete_dot::complete_dot(&mut acc, &ctx);
Ok(Some(acc))
Some(acc)
}
#[cfg(test)]
@ -72,6 +69,6 @@ fn check_completion(code: &str, expected_completions: &str, kind: CompletionKind
} else {
single_file_with_position(code)
};
let completions = completions(&analysis.db, position).unwrap().unwrap();
let completions = completions(&analysis.db, position).unwrap();
completions.assert_match(expected_completions, kind);
}

View File

@ -1,29 +1,27 @@
use hir::{Ty, Def};
use crate::Cancelable;
use crate::completion::{CompletionContext, Completions, CompletionKind, CompletionItem, CompletionItemKind};
/// Complete dot accesses, i.e. fields or methods (currently only fields).
pub(super) fn complete_dot(acc: &mut Completions, ctx: &CompletionContext) -> Cancelable<()> {
pub(super) fn complete_dot(acc: &mut Completions, ctx: &CompletionContext) {
let (function, receiver) = match (&ctx.function, ctx.dot_receiver) {
(Some(function), Some(receiver)) => (function, receiver),
_ => return Ok(()),
_ => return,
};
let infer_result = function.infer(ctx.db)?;
let infer_result = function.infer(ctx.db);
let syntax_mapping = function.body_syntax_mapping(ctx.db);
let expr = match syntax_mapping.node_expr(receiver) {
Some(expr) => expr,
None => return Ok(()),
None => return,
};
let receiver_ty = infer_result[expr].clone();
if !ctx.is_call {
complete_fields(acc, ctx, receiver_ty.clone())?;
complete_fields(acc, ctx, receiver_ty.clone());
}
complete_methods(acc, ctx, receiver_ty)?;
Ok(())
complete_methods(acc, ctx, receiver_ty);
}
fn complete_fields(acc: &mut Completions, ctx: &CompletionContext, receiver: Ty) -> Cancelable<()> {
fn complete_fields(acc: &mut Completions, ctx: &CompletionContext, receiver: Ty) {
for receiver in receiver.autoderef(ctx.db) {
match receiver {
Ty::Adt { def_id, .. } => {
@ -35,7 +33,7 @@ fn complete_fields(acc: &mut Completions, ctx: &CompletionContext, receiver: Ty)
field.name().to_string(),
)
.kind(CompletionItemKind::Field)
.set_detail(field.ty(ctx.db)?.map(|ty| ty.to_string()))
.set_detail(field.ty(ctx.db).map(|ty| ty.to_string()))
.add_to(acc);
}
}
@ -53,14 +51,9 @@ fn complete_fields(acc: &mut Completions, ctx: &CompletionContext, receiver: Ty)
_ => {}
};
}
Ok(())
}
fn complete_methods(
acc: &mut Completions,
ctx: &CompletionContext,
receiver: Ty,
) -> Cancelable<()> {
fn complete_methods(acc: &mut Completions, ctx: &CompletionContext, receiver: Ty) {
receiver.iterate_methods(ctx.db, |func| {
let sig = func.signature(ctx.db);
if sig.has_self_param() {
@ -69,9 +62,8 @@ fn complete_methods(
.kind(CompletionItemKind::Method)
.add_to(acc);
}
Ok(None::<()>)
})?;
Ok(())
None::<()>
});
}
#[cfg(test)]

View File

@ -1,16 +1,15 @@
use crate::{
Cancelable,
completion::{CompletionItem, CompletionItemKind, Completions, CompletionKind, CompletionContext},
};
pub(super) fn complete_path(acc: &mut Completions, ctx: &CompletionContext) -> Cancelable<()> {
pub(super) fn complete_path(acc: &mut Completions, ctx: &CompletionContext) {
let (path, module) = match (&ctx.path_prefix, &ctx.module) {
(Some(path), Some(module)) => (path.clone(), module),
_ => return Ok(()),
_ => return,
};
let def_id = match module.resolve_path(ctx.db, &path).take_types() {
Some(it) => it,
None => return Ok(()),
None => return,
};
match def_id.resolve(ctx.db) {
hir::Def::Module(module) => {
@ -30,9 +29,8 @@ pub(super) fn complete_path(acc: &mut Completions, ctx: &CompletionContext) -> C
.add_to(acc)
});
}
_ => return Ok(()),
_ => return,
};
Ok(())
}
#[cfg(test)]

View File

@ -1,18 +1,15 @@
use rustc_hash::FxHashSet;
use ra_syntax::TextUnit;
use crate::{
Cancelable,
completion::{CompletionItem, CompletionItemKind, Completions, CompletionKind, CompletionContext},
};
use crate::completion::{CompletionItem, CompletionItemKind, Completions, CompletionKind, CompletionContext};
pub(super) fn complete_scope(acc: &mut Completions, ctx: &CompletionContext) -> Cancelable<()> {
pub(super) fn complete_scope(acc: &mut Completions, ctx: &CompletionContext) {
if !ctx.is_trivial_path {
return Ok(());
return;
}
let module = match &ctx.module {
Some(it) => it,
None => return Ok(()),
None => return,
};
if let Some(function) = &ctx.function {
let scopes = function.scopes(ctx.db);
@ -40,7 +37,6 @@ pub(super) fn complete_scope(acc: &mut Completions, ctx: &CompletionContext) ->
.from_resolution(ctx, res)
.add_to(acc)
});
Ok(())
}
fn complete_fn(acc: &mut Completions, scopes: &hir::ScopesWithSyntaxMapping, offset: TextUnit) {

View File

@ -7,7 +7,7 @@ use ra_syntax::{
};
use hir::source_binder;
use crate::{db, FilePosition, Cancelable};
use crate::{db, FilePosition};
/// `CompletionContext` is created early during completion to figure out, where
/// exactly is the cursor, syntax-wise.
@ -41,10 +41,9 @@ impl<'a> CompletionContext<'a> {
db: &'a db::RootDatabase,
original_file: &'a SourceFile,
position: FilePosition,
) -> Cancelable<Option<CompletionContext<'a>>> {
) -> Option<CompletionContext<'a>> {
let module = source_binder::module_from_position(db, position);
let leaf =
ctry!(find_leaf_at_offset(original_file.syntax(), position.offset).left_biased());
let leaf = find_leaf_at_offset(original_file.syntax(), position.offset).left_biased()?;
let mut ctx = CompletionContext {
db,
leaf,
@ -63,7 +62,7 @@ impl<'a> CompletionContext<'a> {
is_call: false,
};
ctx.fill(original_file, position.offset);
Ok(Some(ctx))
Some(ctx)
}
fn fill(&mut self, original_file: &'a SourceFile, offset: TextUnit) {

View File

@ -1,4 +1,4 @@
use ra_db::{FileId, Cancelable, SyntaxDatabase};
use ra_db::{FileId, SyntaxDatabase};
use ra_syntax::{
AstNode, ast,
algo::find_node_at_offset,
@ -9,21 +9,18 @@ use crate::{FilePosition, NavigationTarget, db::RootDatabase, RangeInfo};
pub(crate) fn goto_definition(
db: &RootDatabase,
position: FilePosition,
) -> Cancelable<Option<RangeInfo<Vec<NavigationTarget>>>> {
) -> Option<RangeInfo<Vec<NavigationTarget>>> {
let file = db.source_file(position.file_id);
let syntax = file.syntax();
if let Some(name_ref) = find_node_at_offset::<ast::NameRef>(syntax, position.offset) {
let navs = reference_definition(db, position.file_id, name_ref)?.to_vec();
return Ok(Some(RangeInfo::new(
name_ref.syntax().range(),
navs.to_vec(),
)));
let navs = reference_definition(db, position.file_id, name_ref).to_vec();
return Some(RangeInfo::new(name_ref.syntax().range(), navs.to_vec()));
}
if let Some(name) = find_node_at_offset::<ast::Name>(syntax, position.offset) {
let navs = ctry!(name_definition(db, position.file_id, name)?);
return Ok(Some(RangeInfo::new(name.syntax().range(), navs)));
let navs = name_definition(db, position.file_id, name)?;
return Some(RangeInfo::new(name.syntax().range(), navs));
}
Ok(None)
None
}
pub(crate) enum ReferenceResult {
@ -45,7 +42,7 @@ pub(crate) fn reference_definition(
db: &RootDatabase,
file_id: FileId,
name_ref: &ast::NameRef,
) -> Cancelable<ReferenceResult> {
) -> ReferenceResult {
use self::ReferenceResult::*;
if let Some(function) =
hir::source_binder::function_from_child_node(db, file_id, name_ref.syntax())
@ -54,7 +51,7 @@ pub(crate) fn reference_definition(
// First try to resolve the symbol locally
if let Some(entry) = scope.resolve_local_name(name_ref) {
let nav = NavigationTarget::from_scope_entry(file_id, &entry);
return Ok(Exact(nav));
return Exact(nav);
};
// Next check if it is a method
@ -63,7 +60,7 @@ pub(crate) fn reference_definition(
.parent()
.and_then(ast::MethodCallExpr::cast)
{
let infer_result = function.infer(db)?;
let infer_result = function.infer(db);
let syntax_mapping = function.body_syntax_mapping(db);
let expr = ast::Expr::cast(method_call.syntax()).unwrap();
if let Some(def_id) = syntax_mapping
@ -71,7 +68,7 @@ pub(crate) fn reference_definition(
.and_then(|it| infer_result.method_resolution(it))
{
if let Some(target) = NavigationTarget::from_def(db, def_id.resolve(db)) {
return Ok(Exact(target));
return Exact(target);
}
};
}
@ -88,7 +85,7 @@ pub(crate) fn reference_definition(
let resolved = module.resolve_path(db, &path);
if let Some(def_id) = resolved.take_types().or(resolved.take_values()) {
if let Some(target) = NavigationTarget::from_def(db, def_id.resolve(db)) {
return Ok(Exact(target));
return Exact(target);
}
}
}
@ -99,25 +96,25 @@ pub(crate) fn reference_definition(
.into_iter()
.map(NavigationTarget::from_symbol)
.collect();
Ok(Approximate(navs))
Approximate(navs)
}
fn name_definition(
db: &RootDatabase,
file_id: FileId,
name: &ast::Name,
) -> Cancelable<Option<Vec<NavigationTarget>>> {
) -> Option<Vec<NavigationTarget>> {
if let Some(module) = name.syntax().parent().and_then(ast::Module::cast) {
if module.has_semi() {
if let Some(child_module) =
hir::source_binder::module_from_declaration(db, file_id, module)
{
let nav = NavigationTarget::from_module(db, child_module);
return Ok(Some(vec![nav]));
return Some(vec![nav]);
}
}
}
Ok(None)
None
}
#[cfg(test)]

View File

@ -1,4 +1,4 @@
use ra_db::{Cancelable, SyntaxDatabase};
use ra_db::{SyntaxDatabase};
use ra_syntax::{
AstNode, SyntaxNode, TreeArc,
ast::self,
@ -7,19 +7,16 @@ use ra_syntax::{
use crate::{db::RootDatabase, RangeInfo, FilePosition, FileRange, NavigationTarget};
pub(crate) fn hover(
db: &RootDatabase,
position: FilePosition,
) -> Cancelable<Option<RangeInfo<String>>> {
pub(crate) fn hover(db: &RootDatabase, position: FilePosition) -> Option<RangeInfo<String>> {
let file = db.source_file(position.file_id);
let mut res = Vec::new();
let mut range = None;
if let Some(name_ref) = find_node_at_offset::<ast::NameRef>(file.syntax(), position.offset) {
use crate::goto_definition::{ReferenceResult::*, reference_definition};
let ref_result = reference_definition(db, position.file_id, name_ref)?;
let ref_result = reference_definition(db, position.file_id, name_ref);
match ref_result {
Exact(nav) => res.extend(doc_text_for(db, nav)?),
Exact(nav) => res.extend(doc_text_for(db, nav)),
Approximate(navs) => {
let mut msg = String::from("Failed to exactly resolve the symbol. This is probably because rust_analyzer does not yet support glob imports or traits.");
if !navs.is_empty() {
@ -27,7 +24,7 @@ pub(crate) fn hover(
}
res.push(msg);
for nav in navs {
res.extend(doc_text_for(db, nav)?)
res.extend(doc_text_for(db, nav))
}
}
}
@ -39,25 +36,24 @@ pub(crate) fn hover(
let node = find_leaf_at_offset(file.syntax(), position.offset).find_map(|leaf| {
leaf.ancestors()
.find(|n| ast::Expr::cast(*n).is_some() || ast::Pat::cast(*n).is_some())
});
let node = ctry!(node);
})?;
let frange = FileRange {
file_id: position.file_id,
range: node.range(),
};
res.extend(type_of(db, frange)?.map(Into::into));
res.extend(type_of(db, frange).map(Into::into));
range = Some(node.range());
};
let range = ctry!(range);
let range = range?;
if res.is_empty() {
return Ok(None);
return None;
}
let res = RangeInfo::new(range, res.join("\n\n---\n"));
Ok(Some(res))
Some(res)
}
pub(crate) fn type_of(db: &RootDatabase, frange: FileRange) -> Cancelable<Option<String>> {
pub(crate) fn type_of(db: &RootDatabase, frange: FileRange) -> Option<String> {
let file = db.source_file(frange.file_id);
let syntax = file.syntax();
let leaf_node = find_covering_node(syntax, frange.range);
@ -67,34 +63,28 @@ pub(crate) fn type_of(db: &RootDatabase, frange: FileRange) -> Cancelable<Option
.take_while(|it| it.range() == leaf_node.range())
.find(|&it| ast::Expr::cast(it).is_some() || ast::Pat::cast(it).is_some())
.unwrap_or(leaf_node);
let parent_fn = ctry!(node.ancestors().find_map(ast::FnDef::cast));
let function = ctry!(hir::source_binder::function_from_source(
db,
frange.file_id,
parent_fn
));
let infer = function.infer(db)?;
let parent_fn = node.ancestors().find_map(ast::FnDef::cast)?;
let function = hir::source_binder::function_from_source(db, frange.file_id, parent_fn)?;
let infer = function.infer(db);
let syntax_mapping = function.body_syntax_mapping(db);
if let Some(expr) = ast::Expr::cast(node).and_then(|e| syntax_mapping.node_expr(e)) {
Ok(Some(infer[expr].to_string()))
Some(infer[expr].to_string())
} else if let Some(pat) = ast::Pat::cast(node).and_then(|p| syntax_mapping.node_pat(p)) {
Ok(Some(infer[pat].to_string()))
Some(infer[pat].to_string())
} else {
Ok(None)
None
}
}
// FIXME: this should not really use navigation target. Rather, approximatelly
// resovled symbol should return a `DefId`.
fn doc_text_for(db: &RootDatabase, nav: NavigationTarget) -> Cancelable<Option<String>> {
let result = match (nav.description(db), nav.docs(db)) {
fn doc_text_for(db: &RootDatabase, nav: NavigationTarget) -> Option<String> {
match (nav.description(db), nav.docs(db)) {
(Some(desc), Some(docs)) => Some("```rust\n".to_string() + &*desc + "\n```\n\n" + &*docs),
(Some(desc), None) => Some("```rust\n".to_string() + &*desc + "\n```"),
(None, Some(docs)) => Some(docs),
_ => None,
};
Ok(result)
}
}
impl NavigationTarget {

View File

@ -110,14 +110,11 @@ impl db::RootDatabase {
};
vec![krate.crate_id()]
}
pub(crate) fn find_all_refs(
&self,
position: FilePosition,
) -> Cancelable<Vec<(FileId, TextRange)>> {
pub(crate) fn find_all_refs(&self, position: FilePosition) -> Vec<(FileId, TextRange)> {
let file = self.source_file(position.file_id);
// Find the binding associated with the offset
let (binding, descr) = match find_binding(self, &file, position)? {
None => return Ok(Vec::new()),
let (binding, descr) = match find_binding(self, &file, position) {
None => return Vec::new(),
Some(it) => it,
};
@ -134,36 +131,30 @@ impl db::RootDatabase {
.map(|ref_desc| (position.file_id, ref_desc.range)),
);
return Ok(ret);
return ret;
fn find_binding<'a>(
db: &db::RootDatabase,
source_file: &'a SourceFile,
position: FilePosition,
) -> Cancelable<Option<(&'a ast::BindPat, hir::Function)>> {
) -> Option<(&'a ast::BindPat, hir::Function)> {
let syntax = source_file.syntax();
if let Some(binding) = find_node_at_offset::<ast::BindPat>(syntax, position.offset) {
let descr = ctry!(source_binder::function_from_child_node(
let descr = source_binder::function_from_child_node(
db,
position.file_id,
binding.syntax(),
));
return Ok(Some((binding, descr)));
)?;
return Some((binding, descr));
};
let name_ref = ctry!(find_node_at_offset::<ast::NameRef>(syntax, position.offset));
let descr = ctry!(source_binder::function_from_child_node(
db,
position.file_id,
name_ref.syntax(),
));
let name_ref = find_node_at_offset::<ast::NameRef>(syntax, position.offset)?;
let descr =
source_binder::function_from_child_node(db, position.file_id, name_ref.syntax())?;
let scope = descr.scopes(db);
let resolved = ctry!(scope.resolve_local_name(name_ref));
let resolved = scope.resolve_local_name(name_ref)?;
let resolved = resolved.ptr().resolve(source_file);
let binding = ctry!(find_node_at_offset::<ast::BindPat>(
syntax,
resolved.range().end()
));
Ok(Some((binding, descr)))
let binding = find_node_at_offset::<ast::BindPat>(syntax, resolved.range().end())?;
Some((binding, descr))
}
}
@ -180,7 +171,7 @@ impl db::RootDatabase {
})
.collect::<Vec<_>>();
if let Some(m) = source_binder::module_from_file_id(self, file_id) {
for (name_node, problem) in m.problems(self)? {
for (name_node, problem) in m.problems(self) {
let source_root = self.file_source_root(file_id);
let diag = match problem {
Problem::UnresolvedModule { candidate } => {
@ -239,13 +230,8 @@ impl db::RootDatabase {
.collect()
}
pub(crate) fn rename(
&self,
position: FilePosition,
new_name: &str,
) -> Cancelable<Vec<SourceFileEdit>> {
let res = self
.find_all_refs(position)?
pub(crate) fn rename(&self, position: FilePosition, new_name: &str) -> Vec<SourceFileEdit> {
self.find_all_refs(position)
.iter()
.map(|(file_id, text_range)| SourceFileEdit {
file_id: *file_id,
@ -255,8 +241,7 @@ impl db::RootDatabase {
builder.finish()
},
})
.collect::<Vec<_>>();
Ok(res)
.collect::<Vec<_>>()
}
pub(crate) fn index_resolve(&self, name_ref: &ast::NameRef) -> Vec<FileSymbol> {
let name = name_ref.text();

View File

@ -9,15 +9,6 @@
//!
//! The sibling `ra_ide_api_light` handles thouse bits of IDE functionality
//! which are restricted to a single file and need only syntax.
macro_rules! ctry {
($expr:expr) => {
match $expr {
None => return Ok(None),
Some(it) => it,
}
};
}
mod db;
mod imp;
pub mod mock_analysis;
@ -58,9 +49,11 @@ pub use ra_ide_api_light::{
LineIndex, LineCol, translate_offset_with_edit,
};
pub use ra_db::{
Cancelable, Canceled, CrateGraph, CrateId, FileId, FilePosition, FileRange, SourceRootId
Canceled, CrateGraph, CrateId, FileId, FilePosition, FileRange, SourceRootId
};
pub type Cancelable<T> = Result<T, Canceled>;
#[derive(Default)]
pub struct AnalysisChange {
new_roots: Vec<(SourceRootId, bool)>,
@ -393,28 +386,28 @@ impl Analysis {
position: FilePosition,
) -> Cancelable<Option<RangeInfo<Vec<NavigationTarget>>>> {
self.db
.catch_canceled(|db| goto_definition::goto_definition(db, position))?
.catch_canceled(|db| goto_definition::goto_definition(db, position))
}
/// Finds all usages of the reference at point.
pub fn find_all_refs(&self, position: FilePosition) -> Cancelable<Vec<(FileId, TextRange)>> {
self.with_db(|db| db.find_all_refs(position))?
self.with_db(|db| db.find_all_refs(position))
}
/// Returns a short text descrbing element at position.
pub fn hover(&self, position: FilePosition) -> Cancelable<Option<RangeInfo<String>>> {
self.with_db(|db| hover::hover(db, position))?
self.with_db(|db| hover::hover(db, position))
}
/// Computes parameter information for the given call expression.
pub fn call_info(&self, position: FilePosition) -> Cancelable<Option<CallInfo>> {
self.db
.catch_canceled(|db| call_info::call_info(db, position))?
.catch_canceled(|db| call_info::call_info(db, position))
}
/// Returns a `mod name;` declaration which created the current module.
pub fn parent_module(&self, position: FilePosition) -> Cancelable<Vec<NavigationTarget>> {
self.with_db(|db| parent_module::parent_module(db, position))?
self.with_db(|db| parent_module::parent_module(db, position))
}
/// Returns crates this file belongs too.
@ -430,7 +423,7 @@ impl Analysis {
/// Returns the set of possible targets to run for the current file.
pub fn runnables(&self, file_id: FileId) -> Cancelable<Vec<Runnable>> {
self.db
.catch_canceled(|db| runnables::runnables(db, file_id))?
.catch_canceled(|db| runnables::runnables(db, file_id))
}
/// Computes syntax highlighting for the given file.
@ -443,7 +436,7 @@ impl Analysis {
pub fn completions(&self, position: FilePosition) -> Cancelable<Option<Vec<CompletionItem>>> {
let completions = self
.db
.catch_canceled(|db| completion::completions(db, position))??;
.catch_canceled(|db| completion::completions(db, position))?;
Ok(completions.map(|it| it.into()))
}
@ -460,7 +453,7 @@ impl Analysis {
/// Computes the type of the expression at the given position.
pub fn type_of(&self, frange: FileRange) -> Cancelable<Option<String>> {
self.with_db(|db| hover::type_of(db, frange))?
self.with_db(|db| hover::type_of(db, frange))
}
/// Returns the edit required to rename reference at the position to the new
@ -470,7 +463,7 @@ impl Analysis {
position: FilePosition,
new_name: &str,
) -> Cancelable<Vec<SourceFileEdit>> {
self.with_db(|db| db.rename(position, new_name))?
self.with_db(|db| db.rename(position, new_name))
}
fn with_db<F: FnOnce(&db::RootDatabase) -> T + std::panic::UnwindSafe, T>(

View File

@ -1,19 +1,16 @@
use ra_db::{Cancelable, FilePosition};
use ra_db::FilePosition;
use crate::{NavigationTarget, db::RootDatabase};
/// This returns `Vec` because a module may be included from several places. We
/// don't handle this case yet though, so the Vec has length at most one.
pub(crate) fn parent_module(
db: &RootDatabase,
position: FilePosition,
) -> Cancelable<Vec<NavigationTarget>> {
pub(crate) fn parent_module(db: &RootDatabase, position: FilePosition) -> Vec<NavigationTarget> {
let module = match hir::source_binder::module_from_position(db, position) {
None => return Ok(Vec::new()),
None => return Vec::new(),
Some(it) => it,
};
let nav = NavigationTarget::from_module_to_decl(db, module);
Ok(vec![nav])
vec![nav]
}
#[cfg(test)]

View File

@ -3,7 +3,7 @@ use ra_syntax::{
TextRange, SyntaxNode,
ast::{self, AstNode, NameOwner, ModuleItemOwner},
};
use ra_db::{Cancelable, SyntaxDatabase};
use ra_db::SyntaxDatabase;
use crate::{db::RootDatabase, FileId};
@ -21,14 +21,13 @@ pub enum RunnableKind {
Bin,
}
pub(crate) fn runnables(db: &RootDatabase, file_id: FileId) -> Cancelable<Vec<Runnable>> {
pub(crate) fn runnables(db: &RootDatabase, file_id: FileId) -> Vec<Runnable> {
let source_file = db.source_file(file_id);
let res = source_file
source_file
.syntax()
.descendants()
.filter_map(|i| runnable(db, file_id, i))
.collect();
Ok(res)
.collect()
}
fn runnable(db: &RootDatabase, file_id: FileId, item: &SyntaxNode) -> Option<Runnable> {