Remove some unwraps

This commit is contained in:
Aleksey Kladov 2020-03-28 11:20:34 +01:00
parent 6596e7cddf
commit 311cbbdad5
5 changed files with 29 additions and 29 deletions

View file

@ -4,6 +4,7 @@ use std::any::Any;
use hir_expand::{db::AstDatabase, name::Name, HirFileId, InFile}; use hir_expand::{db::AstDatabase, name::Name, HirFileId, InFile};
use ra_syntax::{ast, AstNode, AstPtr, SyntaxNodePtr}; use ra_syntax::{ast, AstNode, AstPtr, SyntaxNodePtr};
use stdx::format_to;
pub use hir_def::diagnostics::UnresolvedModule; pub use hir_def::diagnostics::UnresolvedModule;
pub use hir_expand::diagnostics::{AstDiagnostic, Diagnostic, DiagnosticSink}; pub use hir_expand::diagnostics::{AstDiagnostic, Diagnostic, DiagnosticSink};
@ -37,12 +38,11 @@ pub struct MissingFields {
impl Diagnostic for MissingFields { impl Diagnostic for MissingFields {
fn message(&self) -> String { fn message(&self) -> String {
use std::fmt::Write; let mut buf = String::from("Missing structure fields:\n");
let mut message = String::from("Missing structure fields:\n");
for field in &self.missed_fields { for field in &self.missed_fields {
writeln!(message, "- {}", field).unwrap(); format_to!(buf, "- {}", field);
} }
message buf
} }
fn source(&self) -> InFile<SyntaxNodePtr> { fn source(&self) -> InFile<SyntaxNodePtr> {
InFile { file_id: self.file, value: self.field_list.into() } InFile { file_id: self.file, value: self.field_list.into() }

View file

@ -7,7 +7,6 @@ mod traits;
mod method_resolution; mod method_resolution;
mod macros; mod macros;
use std::fmt::Write;
use std::sync::Arc; use std::sync::Arc;
use hir_def::{ use hir_def::{
@ -26,6 +25,7 @@ use ra_syntax::{
algo, algo,
ast::{self, AstNode}, ast::{self, AstNode},
}; };
use stdx::format_to;
use crate::{db::HirDatabase, display::HirDisplay, test_db::TestDB, InferenceResult}; use crate::{db::HirDatabase, display::HirDisplay, test_db::TestDB, InferenceResult};
@ -63,7 +63,7 @@ fn infer(ra_fixture: &str) -> String {
fn infer_with_mismatches(content: &str, include_mismatches: bool) -> String { fn infer_with_mismatches(content: &str, include_mismatches: bool) -> String {
let (db, file_id) = TestDB::with_single_file(content); let (db, file_id) = TestDB::with_single_file(content);
let mut acc = String::new(); let mut buf = String::new();
let mut infer_def = |inference_result: Arc<InferenceResult>, let mut infer_def = |inference_result: Arc<InferenceResult>,
body_source_map: Arc<BodySourceMap>| { body_source_map: Arc<BodySourceMap>| {
@ -106,15 +106,14 @@ fn infer_with_mismatches(content: &str, include_mismatches: bool) -> String {
(src_ptr.value.range(), node.text().to_string().replace("\n", " ")) (src_ptr.value.range(), node.text().to_string().replace("\n", " "))
}; };
let macro_prefix = if src_ptr.file_id != file_id.into() { "!" } else { "" }; let macro_prefix = if src_ptr.file_id != file_id.into() { "!" } else { "" };
writeln!( format_to!(
acc, buf,
"{}{} '{}': {}", "{}{} '{}': {}\n",
macro_prefix, macro_prefix,
range, range,
ellipsize(text, 15), ellipsize(text, 15),
ty.display(&db) ty.display(&db)
) );
.unwrap();
} }
if include_mismatches { if include_mismatches {
mismatches.sort_by_key(|(src_ptr, _)| { mismatches.sort_by_key(|(src_ptr, _)| {
@ -123,15 +122,14 @@ fn infer_with_mismatches(content: &str, include_mismatches: bool) -> String {
for (src_ptr, mismatch) in &mismatches { for (src_ptr, mismatch) in &mismatches {
let range = src_ptr.value.range(); let range = src_ptr.value.range();
let macro_prefix = if src_ptr.file_id != file_id.into() { "!" } else { "" }; let macro_prefix = if src_ptr.file_id != file_id.into() { "!" } else { "" };
writeln!( format_to!(
acc, buf,
"{}{}: expected {}, got {}", "{}{}: expected {}, got {}\n",
macro_prefix, macro_prefix,
range, range,
mismatch.expected.display(&db), mismatch.expected.display(&db),
mismatch.actual.display(&db), mismatch.actual.display(&db),
) );
.unwrap();
} }
} }
}; };
@ -158,8 +156,8 @@ fn infer_with_mismatches(content: &str, include_mismatches: bool) -> String {
infer_def(infer, source_map); infer_def(infer, source_map);
} }
acc.truncate(acc.trim_end().len()); buf.truncate(buf.trim_end().len());
acc buf
} }
fn visit_module( fn visit_module(

View file

@ -6,12 +6,13 @@ mod navigation_target;
mod structure; mod structure;
mod short_label; mod short_label;
use std::fmt::{Display, Write}; use std::fmt::Display;
use ra_syntax::{ use ra_syntax::{
ast::{self, AstNode, AttrsOwner, NameOwner, TypeParamsOwner}, ast::{self, AstNode, AttrsOwner, NameOwner, TypeParamsOwner},
SyntaxKind::{ATTR, COMMENT}, SyntaxKind::{ATTR, COMMENT},
}; };
use stdx::format_to;
pub use function_signature::FunctionSignature; pub use function_signature::FunctionSignature;
pub use navigation_target::NavigationTarget; pub use navigation_target::NavigationTarget;
@ -78,18 +79,18 @@ pub(crate) fn rust_code_markup_with_doc(
doc: Option<&str>, doc: Option<&str>,
mod_path: Option<&str>, mod_path: Option<&str>,
) -> String { ) -> String {
let mut markup = "```rust\n".to_owned(); let mut buf = "```rust\n".to_owned();
if let Some(mod_path) = mod_path { if let Some(mod_path) = mod_path {
if !mod_path.is_empty() { if !mod_path.is_empty() {
write!(markup, "{}\n", mod_path).unwrap(); format_to!(buf, "{}\n", mod_path);
} }
} }
write!(markup, "{}\n```", code).unwrap(); format_to!(buf, "{}\n```", code);
if let Some(doc) = doc { if let Some(doc) = doc {
write!(markup, "\n\n{}", doc).unwrap(); format_to!(buf, "\n\n{}", doc);
} }
markup buf
} }

View file

@ -1,7 +1,7 @@
//! Fully type-check project and print various stats, like the number of type //! Fully type-check project and print various stats, like the number of type
//! errors. //! errors.
use std::{collections::HashSet, fmt::Write, path::Path, time::Instant}; use std::{collections::HashSet, path::Path, time::Instant};
use hir::{ use hir::{
db::{AstDatabase, DefDatabase, HirDatabase}, db::{AstDatabase, DefDatabase, HirDatabase},
@ -13,6 +13,7 @@ use itertools::Itertools;
use ra_db::SourceDatabaseExt; use ra_db::SourceDatabaseExt;
use ra_syntax::AstNode; use ra_syntax::AstNode;
use rand::{seq::SliceRandom, thread_rng}; use rand::{seq::SliceRandom, thread_rng};
use stdx::format_to;
use crate::cli::{load_cargo::load_cargo, progress_report::ProgressReport, Result, Verbosity}; use crate::cli::{load_cargo::load_cargo, progress_report::ProgressReport, Result, Verbosity};
@ -128,7 +129,7 @@ pub fn analysis_stats(
let original_file = src.file_id.original_file(db); let original_file = src.file_id.original_file(db);
let path = db.file_relative_path(original_file); let path = db.file_relative_path(original_file);
let syntax_range = src.value.syntax().text_range(); let syntax_range = src.value.syntax().text_range();
write!(msg, " ({:?} {})", path, syntax_range).unwrap(); format_to!(msg, " ({:?} {})", path, syntax_range);
} }
if verbosity.is_spammy() { if verbosity.is_spammy() {
bar.println(msg.to_string()); bar.println(msg.to_string());

View file

@ -3,7 +3,6 @@
//! `ra_ide` crate. //! `ra_ide` crate.
use std::{ use std::{
fmt::Write as _,
io::Write as _, io::Write as _,
process::{self, Stdio}, process::{self, Stdio},
}; };
@ -28,6 +27,7 @@ use ra_syntax::{AstNode, SyntaxKind, TextRange, TextUnit};
use rustc_hash::FxHashMap; use rustc_hash::FxHashMap;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use serde_json::to_value; use serde_json::to_value;
use stdx::format_to;
use crate::{ use crate::{
cargo_target_spec::CargoTargetSpec, cargo_target_spec::CargoTargetSpec,
@ -46,11 +46,11 @@ use crate::{
pub fn handle_analyzer_status(world: WorldSnapshot, _: ()) -> Result<String> { pub fn handle_analyzer_status(world: WorldSnapshot, _: ()) -> Result<String> {
let _p = profile("handle_analyzer_status"); let _p = profile("handle_analyzer_status");
let mut buf = world.status(); let mut buf = world.status();
writeln!(buf, "\n\nrequests:").unwrap(); format_to!(buf, "\n\nrequests:");
let requests = world.latest_requests.read(); let requests = world.latest_requests.read();
for (is_last, r) in requests.iter() { for (is_last, r) in requests.iter() {
let mark = if is_last { "*" } else { " " }; let mark = if is_last { "*" } else { " " };
writeln!(buf, "{}{:4} {:<36}{}ms", mark, r.id, r.method, r.duration.as_millis()).unwrap(); format_to!(buf, "{}{:4} {:<36}{}ms", mark, r.id, r.method, r.duration.as_millis());
} }
Ok(buf) Ok(buf)
} }