From d9e4dbe716f9af8b2117a85a8f8c7cacfbfbd576 Mon Sep 17 00:00:00 2001 From: Shunsuke Shibayama Date: Sat, 23 Mar 2024 09:52:52 +0900 Subject: [PATCH] chore: eliminate `unwrap`s --- crates/els/channels.rs | 5 ++++- crates/els/completion.rs | 6 +++--- crates/els/definition.rs | 2 +- crates/els/diagnostics.rs | 5 ++++- crates/els/inlay_hint.rs | 2 +- crates/els/server.rs | 4 ++-- crates/erg_common/levenshtein.rs | 4 ++-- crates/erg_common/lib.rs | 4 ++-- crates/erg_common/str.rs | 2 ++ crates/erg_common/style.rs | 4 +++- crates/erg_compiler/declare.rs | 9 ++++++++- crates/erg_compiler/hir.rs | 12 ++++++++---- crates/erg_compiler/module/cache.rs | 8 +++++++- crates/erg_compiler/ty/constructors.rs | 2 +- crates/erg_compiler/ty/mod.rs | 4 ++-- crates/erg_parser/ast.rs | 18 +++++++++++++++--- 16 files changed, 65 insertions(+), 26 deletions(-) diff --git a/crates/els/channels.rs b/crates/els/channels.rs index 5672ae34a..422c76da6 100644 --- a/crates/els/channels.rs +++ b/crates/els/channels.rs @@ -208,7 +208,10 @@ macro_rules! impl_sendable { ) -> Result<(), mpsc::SendError>> { self.channels .as_ref() - .unwrap() + .ok_or_else(|| { + erg_common::lsp_log!("channels are closed"); + mpsc::SendError(WorkerMessage::Kill) + })? .$receiver .send($crate::channels::WorkerMessage::Request(id, params)) } diff --git a/crates/els/completion.rs b/crates/els/completion.rs index 93ed590e3..5c8ba6c3a 100644 --- a/crates/els/completion.rs +++ b/crates/els/completion.rs @@ -416,12 +416,12 @@ impl CompletionCache { } pub fn get(&self, namespace: &str) -> Option>> { - if self.cache.borrow().get(namespace).is_none() { - None - } else { + if self.cache.borrow().get(namespace).is_some() { Some(RwLockReadGuard::map(self.cache.borrow(), |cache| { cache.get(namespace).unwrap() })) + } else { + None } } diff --git a/crates/els/definition.rs b/crates/els/definition.rs index c7b98941d..ec6195334 100644 --- a/crates/els/definition.rs +++ b/crates/els/definition.rs @@ -73,7 +73,7 @@ impl Server { ))); } } - } else if let Expr::Accessor(acc) = def.body.block.last().unwrap() { + } else if let Some(Expr::Accessor(acc)) = def.body.block.last() { let vi = acc.var_info(); match (&vi.def_loc.module, util::loc_to_range(vi.def_loc.loc)) { (Some(path), Some(range)) => { diff --git a/crates/els/diagnostics.rs b/crates/els/diagnostics.rs index 409ff6890..430d16289 100644 --- a/crates/els/diagnostics.rs +++ b/crates/els/diagnostics.rs @@ -160,7 +160,10 @@ impl Server { } }; let ast = self.build_ast(&uri).ok(); - let ctx = checker.pop_context().unwrap(); + let Some(ctx) = checker.pop_context() else { + _log!(self, "context not found"); + return Ok(()); + }; if mode == "declare" { self.shared .py_mod_cache diff --git a/crates/els/inlay_hint.rs b/crates/els/inlay_hint.rs index 75d98ad96..f3fed4986 100644 --- a/crates/els/inlay_hint.rs +++ b/crates/els/inlay_hint.rs @@ -318,7 +318,7 @@ impl Server { ) -> ELSResult { self.send_log(format!("inlay hint resolve request: {hint:?}"))?; if let Some(data) = &hint.data { - let Ok(uri) = data.as_str().unwrap().parse::() else { + let Some(uri) = data.as_str().and_then(|s| s.parse::().ok()) else { return Ok(hint); }; if let Some(module) = self.get_mod_ctx(&uri) { diff --git a/crates/els/server.rs b/crates/els/server.rs index d9306082f..b66f8983a 100644 --- a/crates/els/server.rs +++ b/crates/els/server.rs @@ -851,7 +851,7 @@ impl Server { HEALTH_CHECKER_ID => { self.channels .as_ref() - .unwrap() + .ok_or("channels not found")? .health_check .send(WorkerMessage::Request(0, ()))?; } @@ -982,7 +982,7 @@ impl Server { let mut ctxs = vec![]; if let Ok(dir) = uri .to_file_path() - .and_then(|p| p.parent().unwrap().read_dir().map_err(|_| ())) + .and_then(|p| p.parent().ok_or(())?.read_dir().map_err(|_| ())) { for neighbor in dir { let Ok(neighbor) = neighbor else { diff --git a/crates/erg_common/levenshtein.rs b/crates/erg_common/levenshtein.rs index 1ca4f5518..6265eab40 100644 --- a/crates/erg_common/levenshtein.rs +++ b/crates/erg_common/levenshtein.rs @@ -51,7 +51,7 @@ where let most_similar_name = candidates.min_by_key(|v| levenshtein(v.borrow(), name, limit).unwrap_or(usize::MAX))?; let dist = levenshtein(most_similar_name.borrow(), name, limit); - if dist.is_none() || dist.unwrap() >= limit { + if dist.map_or(true, |d| d >= limit) { None } else { Some(most_similar_name) @@ -69,7 +69,7 @@ where let most_similar_name_and_some = candidates .min_by_key(|(_, v)| levenshtein(v.borrow(), name, limit).unwrap_or(usize::MAX))?; let dist = levenshtein(most_similar_name_and_some.1.borrow(), name, limit); - if dist.is_none() || dist.unwrap() >= limit { + if dist.map_or(true, |d| d >= limit) { None } else { Some(most_similar_name_and_some) diff --git a/crates/erg_common/lib.rs b/crates/erg_common/lib.rs index 583c24ef8..41ae32e36 100644 --- a/crates/erg_common/lib.rs +++ b/crates/erg_common/lib.rs @@ -52,7 +52,7 @@ pub fn open_read(filename: &str) -> std::io::Result { pub fn read_file(mut f: std::fs::File) -> std::io::Result { let mut s = "".to_string(); - std::io::Read::read_to_string(&mut f, &mut s).unwrap(); + std::io::Read::read_to_string(&mut f, &mut s)?; Ok(s) } @@ -183,7 +183,7 @@ pub fn unique_in_place(v: &mut Vec) { /// at least, this is necessary for Windows and macOS pub fn normalize_path(path: PathBuf) -> PathBuf { - let verbatim_replaced = path.to_str().unwrap().replace("\\\\?\\", ""); + let verbatim_replaced = path.to_string_lossy().replace("\\\\?\\", ""); let lower = if !CASE_SENSITIVE { verbatim_replaced.to_lowercase() } else { diff --git a/crates/erg_common/str.rs b/crates/erg_common/str.rs index 8e79c756c..5bf290cf6 100644 --- a/crates/erg_common/str.rs +++ b/crates/erg_common/str.rs @@ -233,6 +233,8 @@ impl Str { /// assert_eq!(s.split_with(&[".", "::"]), vec!["a", "b", "c"]); /// let s = Str::rc("ああ.いい::うう"); /// assert_eq!(s.split_with(&[".", "::"]), vec!["ああ", "いい", "うう"]); + /// let s = Str::rc("abc"); + /// assert_eq!(s.split_with(&[".", "::"]), vec!["abc"]); /// ``` pub fn split_with(&self, seps: &[&str]) -> Vec<&str> { let mut result = vec![]; diff --git a/crates/erg_common/style.rs b/crates/erg_common/style.rs index b37d42187..c83786598 100644 --- a/crates/erg_common/style.rs +++ b/crates/erg_common/style.rs @@ -521,7 +521,9 @@ impl StyledStrings { /// ``` pub fn push_str(&mut self, s: &str) { if self.color_is(Color::Gray) { - self.texts.last_mut().unwrap().text.push_str(s); + if let Some(ss) = self.texts.last_mut() { + ss.text.push_str(s) + } } else { self.texts.push(StyledString::new(s, None, None)); } diff --git a/crates/erg_compiler/declare.rs b/crates/erg_compiler/declare.rs index ff78021d1..57a1aef52 100644 --- a/crates/erg_compiler/declare.rs +++ b/crates/erg_compiler/declare.rs @@ -336,7 +336,14 @@ impl GenericASTLowerer { fn fake_lower_signature(&self, sig: ast::Signature) -> LowerResult { match sig { ast::Signature::Var(var) => { - let ident = var.ident().unwrap().clone(); + let Some(ident) = var.ident().cloned() else { + return Err(LowerErrors::from(LowerError::declare_error( + self.cfg().input.clone(), + line!() as usize, + var.loc(), + self.module.context.caused_by(), + ))); + }; let ident = hir::Identifier::bare(ident); let t_spec = if let Some(ts) = var.t_spec { let expr = self.fake_lower_expr(*ts.t_spec_as_expr.clone())?; diff --git a/crates/erg_compiler/hir.rs b/crates/erg_compiler/hir.rs index 1d77c4bd1..9c0cdf95c 100644 --- a/crates/erg_compiler/hir.rs +++ b/crates/erg_compiler/hir.rs @@ -1191,7 +1191,11 @@ impl_stream!(RecordAttrs, Def); impl Locational for RecordAttrs { fn loc(&self) -> Location { - Location::concat(self.0.first().unwrap(), self.0.last().unwrap()) + if self.is_empty() { + Location::Unknown + } else { + Location::concat(self.0.first().unwrap(), self.0.last().unwrap()) + } } } @@ -2319,8 +2323,8 @@ impl Def { } pub fn def_kind(&self) -> DefKind { - match self.body.block.first().unwrap() { - Expr::Call(call) => match call.obj.show_acc().as_ref().map(|n| &n[..]) { + match self.body.block.first() { + Some(Expr::Call(call)) => match call.obj.show_acc().as_ref().map(|n| &n[..]) { Some("Class") => DefKind::Class, Some("Inherit") => DefKind::Inherit, Some("Trait") => DefKind::Trait, @@ -2349,7 +2353,7 @@ impl Def { } pub fn get_base(&self) -> Option<&Record> { - match self.body.block.first().unwrap() { + match self.body.block.first()? { Expr::Call(call) => match call.obj.show_acc().as_ref().map(|n| &n[..]) { Some("Class") | Some("Trait") => { if let Some(Expr::Record(rec)) = call.args.get_left_or_key("Base") { diff --git a/crates/erg_compiler/module/cache.rs b/crates/erg_compiler/module/cache.rs index c858357fc..2ece56e77 100644 --- a/crates/erg_compiler/module/cache.rs +++ b/crates/erg_compiler/module/cache.rs @@ -188,7 +188,13 @@ impl ModuleCache { } pub fn get_similar_name(&self, name: &str) -> Option { - get_similar_name(self.cache.iter().map(|(v, _)| v.to_str().unwrap()), name).map(Str::rc) + get_similar_name( + self.cache + .iter() + .map(|(v, _)| v.to_str().unwrap_or_default()), + name, + ) + .map(Str::rc) } pub fn rename_path(&mut self, old: &NormalizedPathBuf, new: NormalizedPathBuf) { diff --git a/crates/erg_compiler/ty/constructors.rs b/crates/erg_compiler/ty/constructors.rs index 57d6dc864..79b7cee73 100644 --- a/crates/erg_compiler/ty/constructors.rs +++ b/crates/erg_compiler/ty/constructors.rs @@ -105,7 +105,7 @@ pub fn py_module(path: TyParam) -> Type { } pub fn module_from_path>(path: P) -> Type { - let s = ValueObj::Str(Str::rc(path.into().to_str().unwrap())); + let s = ValueObj::Str(Str::rc(&path.into().to_string_lossy())); module(TyParam::Value(s)) } diff --git a/crates/erg_compiler/ty/mod.rs b/crates/erg_compiler/ty/mod.rs index fb50541da..d6399d84e 100644 --- a/crates/erg_compiler/ty/mod.rs +++ b/crates/erg_compiler/ty/mod.rs @@ -2770,9 +2770,9 @@ impl Type { Self::Refinement(refine) => refine.t.namespace(), Self::Mono(name) | Self::Poly { name, .. } => { let namespaces = name.split_with(&[".", "::"]); - if namespaces.len() > 1 { + if let Some(last) = namespaces.last() { Str::rc( - name.trim_end_matches(namespaces.last().unwrap()) + name.trim_end_matches(last) .trim_end_matches('.') .trim_end_matches("::"), ) diff --git a/crates/erg_parser/ast.rs b/crates/erg_parser/ast.rs index 0ef138bc5..9b25dfa70 100644 --- a/crates/erg_parser/ast.rs +++ b/crates/erg_parser/ast.rs @@ -1205,7 +1205,11 @@ impl NestedDisplay for ClassAttrs { impl Locational for ClassAttrs { fn loc(&self) -> Location { - Location::concat(self.0.first().unwrap(), self.0.last().unwrap()) + if self.is_empty() { + Location::Unknown + } else { + Location::concat(self.0.first().unwrap(), self.0.last().unwrap()) + } } } @@ -1231,7 +1235,11 @@ impl NestedDisplay for RecordAttrs { impl Locational for RecordAttrs { fn loc(&self) -> Location { - Location::concat(self.0.first().unwrap(), self.0.last().unwrap()) + if self.is_empty() { + Location::Unknown + } else { + Location::concat(self.0.first().unwrap(), self.0.last().unwrap()) + } } } @@ -6125,7 +6133,11 @@ impl_display_from_nested!(Module); impl Locational for Module { fn loc(&self) -> Location { - Location::concat(self.0.first().unwrap(), self.0.last().unwrap()) + if self.is_empty() { + Location::Unknown + } else { + Location::concat(self.0.first().unwrap(), self.0.last().unwrap()) + } } }