Get rid of unwraps in add_new

Probably fixes #2464.
This commit is contained in:
Florian Diebold 2019-12-07 11:52:20 +01:00
parent 431836f4a0
commit de08d30b80

View file

@ -56,42 +56,39 @@ pub(crate) fn add_new(ctx: AssistCtx<impl HirDatabase>) -> Option<Assist> {
let vis = vis.as_ref().map(String::as_str).unwrap_or(""); let vis = vis.as_ref().map(String::as_str).unwrap_or("");
write!(&mut buf, " {}fn new(", vis).unwrap(); write!(&mut buf, " {}fn new(", vis).unwrap();
join(field_list.fields().map(|f| { join(field_list.fields().filter_map(|f| {
format!( Some(format!("{}: {}", f.name()?.syntax().text(), f.ascribed_type()?.syntax().text()))
"{}: {}",
f.name().unwrap().syntax().text(),
f.ascribed_type().unwrap().syntax().text()
)
})) }))
.separator(", ") .separator(", ")
.to_buf(&mut buf); .to_buf(&mut buf);
buf.push_str(") -> Self { Self {"); buf.push_str(") -> Self { Self {");
join(field_list.fields().map(|f| f.name().unwrap().syntax().text())) join(field_list.fields().filter_map(|f| Some(f.name()?.syntax().text())))
.separator(", ") .separator(", ")
.surround_with(" ", " ") .surround_with(" ", " ")
.to_buf(&mut buf); .to_buf(&mut buf);
buf.push_str("} }"); buf.push_str("} }");
let (start_offset, end_offset) = if let Some(impl_block) = impl_block { let (start_offset, end_offset) = impl_block
.and_then(|impl_block| {
buf.push('\n'); buf.push('\n');
let start = impl_block let start = impl_block
.syntax() .syntax()
.descendants_with_tokens() .descendants_with_tokens()
.find(|t| t.kind() == T!['{']) .find(|t| t.kind() == T!['{'])?
.unwrap()
.text_range() .text_range()
.end(); .end();
(start, TextUnit::from_usize(1)) Some((start, TextUnit::from_usize(1)))
} else { })
.unwrap_or_else(|| {
buf = generate_impl_text(&strukt, &buf); buf = generate_impl_text(&strukt, &buf);
let start = strukt.syntax().text_range().end(); let start = strukt.syntax().text_range().end();
(start, TextUnit::from_usize(3)) (start, TextUnit::from_usize(3))
}; });
edit.set_cursor(start_offset + TextUnit::of_str(&buf) - end_offset); edit.set_cursor(start_offset + TextUnit::of_str(&buf) - end_offset);
edit.insert(start_offset, buf); edit.insert(start_offset, buf);