Skip to content

Add a fix that inserts a missing method #19950

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Draft
wants to merge 8 commits into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions crates/hir-ty/src/infer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -229,6 +229,7 @@ pub enum InferenceDiagnostic {
expr: ExprId,
receiver: Ty,
name: Name,
arg_types: Vec<Ty>,
/// Contains the type the field resolves to
field_with_same_name: Option<Ty>,
assoc_func_with_same_name: Option<FunctionId>,
Expand Down
5 changes: 5 additions & 0 deletions crates/hir-ty/src/infer/expr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1886,10 +1886,15 @@ impl InferenceContext<'_> {
},
);

let arg_types = args
.iter()
.map(|&arg| self.infer_expr_inner(arg, &Expectation::none(), ExprIsRead::Yes))
.collect();
self.push_diagnostic(InferenceDiagnostic::UnresolvedMethodCall {
expr: tgt_expr,
receiver: receiver_ty.clone(),
name: method_name.clone(),
arg_types,
field_with_same_name: field_with_same_name_exists.clone(),
assoc_func_with_same_name,
});
Expand Down
3 changes: 3 additions & 0 deletions crates/hir/src/diagnostics.rs
Original file line number Diff line number Diff line change
Expand Up @@ -260,6 +260,7 @@ pub struct UnresolvedMethodCall<'db> {
pub expr: InFile<ExprOrPatPtr>,
pub receiver: Type<'db>,
pub name: Name,
pub arg_types: Vec<Type<'db>>,
pub field_with_same_name: Option<Type<'db>>,
pub assoc_func_with_same_name: Option<Function>,
}
Expand Down Expand Up @@ -688,13 +689,15 @@ impl<'db> AnyDiagnostic<'db> {
expr,
receiver,
name,
arg_types,
field_with_same_name,
assoc_func_with_same_name,
} => {
let expr = expr_syntax(*expr)?;
UnresolvedMethodCall {
expr,
name: name.clone(),
arg_types: arg_types.iter().map(|ty| Type::new(db, def, ty.clone())).collect(),
receiver: Type::new(db, def, receiver.clone()),
field_with_same_name: field_with_same_name
.clone()
Expand Down
13 changes: 12 additions & 1 deletion crates/hir/src/has_source.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ use syntax::ast;
use tt::TextRange;

use crate::{
Adt, Callee, Const, Enum, ExternCrateDecl, Field, FieldSource, Function, Impl,
Adt, AssocItem, Callee, Const, Enum, ExternCrateDecl, Field, FieldSource, Function, Impl,
InlineAsmOperand, Label, LifetimeParam, LocalSource, Macro, Module, Param, SelfParam, Static,
Struct, Trait, TraitAlias, TypeAlias, TypeOrConstParam, Union, Variant, VariantDef,
db::HirDatabase,
Expand Down Expand Up @@ -100,6 +100,17 @@ impl HasSource for Field {
Some(field_source)
}
}
impl HasSource for AssocItem {
type Ast = ast::AssocItem;

fn source(self, db: &dyn HirDatabase) -> Option<InFile<Self::Ast>> {
match self {
AssocItem::Const(c) => Some(c.source(db)?.map(ast::AssocItem::Const)),
AssocItem::Function(f) => Some(f.source(db)?.map(ast::AssocItem::Fn)),
AssocItem::TypeAlias(t) => Some(t.source(db)?.map(ast::AssocItem::TypeAlias)),
}
}
}
impl HasSource for Adt {
type Ast = ast::Adt;
fn source(self, db: &dyn HirDatabase) -> Option<InFile<Self::Ast>> {
Expand Down
179 changes: 178 additions & 1 deletion crates/ide-diagnostics/src/handlers/unresolved_method.rs
Original file line number Diff line number Diff line change
@@ -1,17 +1,20 @@
use hir::HasSource;
use hir::{FileRange, HirDisplay, InFile, db::ExpandDatabase};
use ide_db::assists::ExprFillDefaultMode;
use ide_db::text_edit::TextEdit;
use ide_db::{
assists::{Assist, AssistId},
label::Label,
source_change::SourceChange,
};
use itertools::Itertools;
use syntax::{
AstNode, SmolStr, TextRange, ToSmolStr,
ast::{self, HasArgList, make},
format_smolstr,
};

use crate::{Diagnostic, DiagnosticCode, DiagnosticsContext, adjusted_display_range};
use crate::{Diagnostic, DiagnosticCode, DiagnosticsContext, adjusted_display_range, fix};

// Diagnostic: unresolved-method
//
Expand Down Expand Up @@ -67,9 +70,73 @@ fn fixes(ctx: &DiagnosticsContext<'_>, d: &hir::UnresolvedMethodCall<'_>) -> Opt
fixes.push(assoc_func_fix);
}

if let Some(method_fix) = add_method_fix(ctx, d) {
fixes.push(method_fix);
}

if fixes.is_empty() { None } else { Some(fixes) }
}

/// Fix to add the missing method.
fn add_method_fix(
ctx: &DiagnosticsContext<'_>,
d: &hir::UnresolvedMethodCall<'_>,
) -> Option<Assist> {
let root = ctx.sema.db.parse_or_expand(d.expr.file_id);
let expr = d.expr.value.to_node(&root).left()?;

let db = ctx.sema.db;
let ty = d.receiver.clone();

let mut all_impl_blocks = hir::Impl::all_for_type(db, ty.clone())
.into_iter()
.chain(hir::Impl::all_for_type(db, ty.strip_reference()));
let impl_block = all_impl_blocks.find(|block| block.trait_(db).is_none())?;

let items = impl_block.items(db);
let last_item = items.last()?;
let source = last_item.source(db)?;
let file_id = match source.file_id {
hir::HirFileId::FileId(file_id) => file_id,
hir::HirFileId::MacroFile(_) => return None,
};
let module_id = last_item.module(db);
let end_of_last_item = source.node_file_range().file_range()?.range.end();

let method_body = match ctx.config.expr_fill_default {
ExprFillDefaultMode::Default | ExprFillDefaultMode::Todo => "todo!()",
ExprFillDefaultMode::Underscore => "_",
};

let method_name = d.name.as_str();
let params: Vec<String> = d
.arg_types
.iter()
.enumerate()
.map(|(i, ty)| {
let name = format!("arg{}", i + 1);
let ty = ty.display_source_code(db, module_id.into(), true).unwrap();
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this unwrap panicked on some real code. if there's an error just put in '()' or something for the type

format!("{name}: {ty}")
})
.collect();
let param_list = if params.is_empty() {
"&self".to_owned()
} else {
format!("&self, {}", params.into_iter().join(","))
};

let text_to_insert = format!("\n fn {method_name}({param_list}) {{ {method_body} }}");
Some(fix(
"add-missing-method",
"Add missing method",
SourceChange::from_text_edit(
file_id.file_id(db),
TextEdit::insert(end_of_last_item, text_to_insert),
),
ctx.sema.original_range(expr.syntax()).range,
))
}

fn field_fix(
ctx: &DiagnosticsContext<'_>,
d: &hir::UnresolvedMethodCall<'_>,
Expand Down Expand Up @@ -286,6 +353,116 @@ fn main() {
);
}

#[test]
fn test_add_method_fix_ref_self() {
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this test currently fails. we're calling a non-existent method on &Dolphin (not Dolphin) so no fix is generated. In such a case we should look for an impl Dolphin block and add a method that takes &self, or look for an impl &Dolphin block and add a method that takes self. What if both exist?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Haven't yet tested cases with &mut SomeType but probably need to handle that too.

check_fix(
r#"
struct Dolphin;

impl Dolphin {
fn do_trick(&self) {}
}

#[allow(unused)]
fn say_hi_to(dolphin: &Dolphin) {
"hello " + dolphin.name$0();
}"#,
r#"
struct Dolphin;

impl Dolphin {
fn do_trick(&self) {}
fn name(&self) { todo!() }
}

#[allow(unused)]
fn say_hi_to(dolphin: &Dolphin) {
"hello " + dolphin.name();
}"#,
);
}

#[test]
fn test_add_method_fix_self() {
check_fix(
r#"
struct Tiger;

impl Tiger {
fn sleep(&self) {}
}

fn main() {
let t = Tiger;
t.roar$0();
}"#,
r#"
struct Tiger;

impl Tiger {
fn sleep(&self) {}
fn roar(&self) { todo!() }
}

fn main() {
let t = Tiger;
t.roar();
}"#,
);
}

#[test]
fn test_add_method_from_same_impl_block() {
check_fix(
r#"
struct Tiger;

impl Tiger {
fn sleep(&self) {}
fn do_stuff(self) {
self.sleep();
self.roar$0();
self.sleep();
}
}"#,
r#"
struct Tiger;

impl Tiger {
fn sleep(&self) {}
fn do_stuff(self) {
self.sleep();
self.roar();
self.sleep();
}
fn roar(&self) { todo!() }
}"#,
);
}

#[test]
fn test_add_method_with_args() {
check_fix(
r#"
struct Speaker;

impl Speaker {
fn greet(&self) {
self.say("hello")$0;
}
}"#,
r#"
struct Speaker;

impl Speaker {
fn greet(&self) {
self.say("hello");
}
fn say(&self, arg1: &'static str) { todo!() }
}"#,
);
}

#[test]
fn smoke_test_in_macro_def_site() {
check_diagnostics(
Expand Down
Loading