Skip to content

Commit

Permalink
chore: eliminate unwraps
Browse files Browse the repository at this point in the history
  • Loading branch information
mtshiba committed Mar 23, 2024
1 parent f5a21ca commit d9e4dbe
Show file tree
Hide file tree
Showing 16 changed files with 65 additions and 26 deletions.
5 changes: 4 additions & 1 deletion crates/els/channels.rs
Original file line number Diff line number Diff line change
Expand Up @@ -208,7 +208,10 @@ macro_rules! impl_sendable {
) -> Result<(), mpsc::SendError<WorkerMessage<$Params>>> {
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))
}
Expand Down
6 changes: 3 additions & 3 deletions crates/els/completion.rs
Original file line number Diff line number Diff line change
Expand Up @@ -416,12 +416,12 @@ impl CompletionCache {
}

pub fn get(&self, namespace: &str) -> Option<MappedRwLockReadGuard<Vec<CompletionItem>>> {
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
}
}

Expand Down
2 changes: 1 addition & 1 deletion crates/els/definition.rs
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ impl<Checker: BuildRunnable, Parser: Parsable> Server<Checker, Parser> {
)));
}
}
} 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)) => {
Expand Down
5 changes: 4 additions & 1 deletion crates/els/diagnostics.rs
Original file line number Diff line number Diff line change
Expand Up @@ -160,7 +160,10 @@ impl<Checker: BuildRunnable, Parser: Parsable> Server<Checker, Parser> {
}
};
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
Expand Down
2 changes: 1 addition & 1 deletion crates/els/inlay_hint.rs
Original file line number Diff line number Diff line change
Expand Up @@ -318,7 +318,7 @@ impl<Checker: BuildRunnable, Parser: Parsable> Server<Checker, Parser> {
) -> ELSResult<InlayHint> {
self.send_log(format!("inlay hint resolve request: {hint:?}"))?;
if let Some(data) = &hint.data {
let Ok(uri) = data.as_str().unwrap().parse::<NormalizedUrl>() else {
let Some(uri) = data.as_str().and_then(|s| s.parse::<NormalizedUrl>().ok()) else {
return Ok(hint);
};
if let Some(module) = self.get_mod_ctx(&uri) {
Expand Down
4 changes: 2 additions & 2 deletions crates/els/server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -851,7 +851,7 @@ impl<Checker: BuildRunnable, Parser: Parsable> Server<Checker, Parser> {
HEALTH_CHECKER_ID => {
self.channels
.as_ref()
.unwrap()
.ok_or("channels not found")?
.health_check
.send(WorkerMessage::Request(0, ()))?;
}
Expand Down Expand Up @@ -982,7 +982,7 @@ impl<Checker: BuildRunnable, Parser: Parsable> Server<Checker, Parser> {
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 {
Expand Down
4 changes: 2 additions & 2 deletions crates/erg_common/levenshtein.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -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)
Expand Down
4 changes: 2 additions & 2 deletions crates/erg_common/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ pub fn open_read(filename: &str) -> std::io::Result<String> {

pub fn read_file(mut f: std::fs::File) -> std::io::Result<String> {
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)
}

Expand Down Expand Up @@ -183,7 +183,7 @@ pub fn unique_in_place<T: Eq + std::hash::Hash + Clone>(v: &mut Vec<T>) {

/// 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 {
Expand Down
2 changes: 2 additions & 0 deletions crates/erg_common/str.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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![];
Expand Down
4 changes: 3 additions & 1 deletion crates/erg_common/style.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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));
}
Expand Down
9 changes: 8 additions & 1 deletion crates/erg_compiler/declare.rs
Original file line number Diff line number Diff line change
Expand Up @@ -336,7 +336,14 @@ impl<A: ASTBuildable> GenericASTLowerer<A> {
fn fake_lower_signature(&self, sig: ast::Signature) -> LowerResult<hir::Signature> {
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())?;
Expand Down
12 changes: 8 additions & 4 deletions crates/erg_compiler/hir.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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())
}
}
}

Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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") {
Expand Down
8 changes: 7 additions & 1 deletion crates/erg_compiler/module/cache.rs
Original file line number Diff line number Diff line change
Expand Up @@ -188,7 +188,13 @@ impl ModuleCache {
}

pub fn get_similar_name(&self, name: &str) -> Option<Str> {
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) {
Expand Down
2 changes: 1 addition & 1 deletion crates/erg_compiler/ty/constructors.rs
Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,7 @@ pub fn py_module(path: TyParam) -> Type {
}

pub fn module_from_path<P: Into<PathBuf>>(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))
}

Expand Down
4 changes: 2 additions & 2 deletions crates/erg_compiler/ty/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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("::"),
)
Expand Down
18 changes: 15 additions & 3 deletions crates/erg_parser/ast.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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())
}
}
}

Expand All @@ -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())
}
}
}

Expand Down Expand Up @@ -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())
}
}
}

Expand Down

0 comments on commit d9e4dbe

Please sign in to comment.