diff --git a/compiler/codegen/src/symboltable.rs b/compiler/codegen/src/symboltable.rs index 258d35771..b53e8844c 100644 --- a/compiler/codegen/src/symboltable.rs +++ b/compiler/codegen/src/symboltable.rs @@ -414,21 +414,20 @@ impl SymbolTableAnalyzer { st_typ: SymbolTableType, ) -> Option { sub_tables.iter().find_map(|st| { - st.symbols.get(name).and_then(|sym| { - if sym.scope == SymbolScope::Free || sym.flags.contains(SymbolFlags::FREE_CLASS) { - if st_typ == SymbolTableType::Class && name != "__class__" { - None - } else { - Some(SymbolScope::Cell) - } - } else if sym.scope == SymbolScope::GlobalExplicit && self.tables.is_empty() { - // the symbol is defined on the module level, and an inner scope declares - // a global that points to it - Some(SymbolScope::GlobalExplicit) - } else { + let sym = st.symbols.get(name)?; + if sym.scope == SymbolScope::Free || sym.flags.contains(SymbolFlags::FREE_CLASS) { + if st_typ == SymbolTableType::Class && name != "__class__" { None + } else { + Some(SymbolScope::Cell) } - }) + } else if sym.scope == SymbolScope::GlobalExplicit && self.tables.is_empty() { + // the symbol is defined on the module level, and an inner scope declares + // a global that points to it + Some(SymbolScope::GlobalExplicit) + } else { + None + } }) } diff --git a/stdlib/src/sqlite.rs b/stdlib/src/sqlite.rs index 6e17ee005..8982b80c0 100644 --- a/stdlib/src/sqlite.rs +++ b/stdlib/src/sqlite.rs @@ -809,7 +809,7 @@ mod _sqlite { type Args = ConnectArgs; fn py_new(cls: PyTypeRef, args: Self::Args, vm: &VirtualMachine) -> PyResult { - Self::new(args, vm).and_then(|x| x.into_ref_with_type(vm, cls).map(Into::into)) + Ok(Self::new(args, vm)?.into_ref_with_type(vm, cls)?.into()) } } diff --git a/stdlib/src/zlib.rs b/stdlib/src/zlib.rs index ceb9c95cd..f7df60185 100644 --- a/stdlib/src/zlib.rs +++ b/stdlib/src/zlib.rs @@ -248,19 +248,14 @@ mod zlib { } = args; data.with_ref(|data| { let mut d = InitOptions::new(wbits.value, vm)?.decompress(); - - _decompress(data, &mut d, bufsize.value, None, false, vm).and_then( - |(buf, stream_end)| { - if stream_end { - Ok(buf) - } else { - Err(new_zlib_error( - "Error -5 while decompressing data: incomplete or truncated stream", - vm, - )) - } - }, - ) + let (buf, stream_end) = _decompress(data, &mut d, bufsize.value, None, false, vm)?; + if !stream_end { + return Err(new_zlib_error( + "Error -5 while decompressing data: incomplete or truncated stream", + vm, + )); + } + Ok(buf) }) } diff --git a/vm/src/builtins/builtin_func.rs b/vm/src/builtins/builtin_func.rs index a57a749e3..bce858743 100644 --- a/vm/src/builtins/builtin_func.rs +++ b/vm/src/builtins/builtin_func.rs @@ -147,10 +147,10 @@ impl PyBuiltinFunction { } #[pygetset(magic)] fn text_signature(&self) -> Option { - self.value.doc.as_ref().and_then(|doc| { - type_::get_text_signature_from_internal_doc(self.value.name.as_str(), doc.as_str()) - .map(|signature| signature.to_string()) - }) + let doc = self.value.doc.as_ref()?; + let signature = + type_::get_text_signature_from_internal_doc(self.value.name.as_str(), doc.as_str())?; + Some(signature.to_owned()) } } diff --git a/vm/src/builtins/module.rs b/vm/src/builtins/module.rs index 8be692746..6a15c7ed0 100644 --- a/vm/src/builtins/module.rs +++ b/vm/src/builtins/module.rs @@ -61,10 +61,11 @@ impl PyModule { } fn name(zelf: PyRef, vm: &VirtualMachine) -> Option { - zelf.as_object() + let name = zelf + .as_object() .generic_getattr_opt(identifier!(vm, __name__).to_owned(), None, vm) - .unwrap_or(None) - .and_then(|obj| obj.downcast::().ok()) + .unwrap_or_default()?; + name.downcast::().ok() } #[pymethod(magic)] @@ -145,10 +146,9 @@ impl Representable for PyModule { fn repr(zelf: &Py, vm: &VirtualMachine) -> PyResult { let importlib = vm.import("_frozen_importlib", None, 0)?; let module_repr = importlib.get_attr("_module_repr", vm)?; - module_repr.call((zelf.to_owned(),), vm).and_then(|obj| { - obj.downcast() - .map_err(|_| vm.new_type_error("_module_repr did not return a string".into())) - }) + let repr = module_repr.call((zelf.to_owned(),), vm)?; + repr.downcast() + .map_err(|_| vm.new_type_error("_module_repr did not return a string".into())) } #[cold] diff --git a/vm/src/import.rs b/vm/src/import.rs index 435d166c7..a33db62dd 100644 --- a/vm/src/import.rs +++ b/vm/src/import.rs @@ -81,30 +81,24 @@ pub fn make_frozen(vm: &VirtualMachine, name: &str) -> PyResult> { } pub fn import_frozen(vm: &VirtualMachine, module_name: &str) -> PyResult { - make_frozen(vm, module_name).and_then(|frozen| { - let module = import_codeobj(vm, module_name, frozen, false)?; - // TODO: give a correct origname here - module.set_attr("__origname__", vm.ctx.new_str(module_name.to_owned()), vm)?; - Ok(module) - }) + let frozen = make_frozen(vm, module_name)?; + let module = import_codeobj(vm, module_name, frozen, false)?; + // TODO: give a correct origname here + module.set_attr("__origname__", vm.ctx.new_str(module_name.to_owned()), vm)?; + Ok(module) } pub fn import_builtin(vm: &VirtualMachine, module_name: &str) -> PyResult { - vm.state - .module_inits - .get(module_name) - .ok_or_else(|| { - vm.new_import_error( - format!("Cannot import builtin module {module_name}"), - module_name, - ) - }) - .and_then(|make_module_func| { - let module = make_module_func(vm); - let sys_modules = vm.sys_module.get_attr("modules", vm)?; - sys_modules.set_item(module_name, module.clone(), vm)?; - Ok(module) - }) + let make_module_func = vm.state.module_inits.get(module_name).ok_or_else(|| { + vm.new_import_error( + format!("Cannot import builtin module {module_name}"), + module_name, + ) + })?; + let module = make_module_func(vm); + let sys_modules = vm.sys_module.get_attr("modules", vm)?; + sys_modules.set_item(module_name, module.clone(), vm)?; + Ok(module) } #[cfg(feature = "rustpython-compiler")] diff --git a/vm/src/protocol/iter.rs b/vm/src/protocol/iter.rs index 94371c74b..1875d7fa2 100644 --- a/vm/src/protocol/iter.rs +++ b/vm/src/protocol/iter.rs @@ -197,7 +197,7 @@ impl ToPyResult for PyIterReturn { impl ToPyResult for PyResult { fn to_pyresult(self, vm: &VirtualMachine) -> PyResult { - self.and_then(|obj| obj.to_pyresult(vm)) + self?.to_pyresult(vm) } } @@ -234,11 +234,11 @@ where type Item = PyResult; fn next(&mut self) -> Option { - PyIter::new(self.obj.borrow()) + let obj = PyIter::new(self.obj.borrow()) .next(self.vm) .map(|iret| iret.into_result().ok()) - .transpose() - .map(|x| x.and_then(|obj| T::try_from_object(self.vm, obj))) + .transpose()?; + Some(obj.and_then(|obj| T::try_from_object(self.vm, obj))) } #[inline] diff --git a/vm/src/protocol/object.rs b/vm/src/protocol/object.rs index 9c5bd64a5..91ca092d4 100644 --- a/vm/src/protocol/object.rs +++ b/vm/src/protocol/object.rs @@ -461,20 +461,20 @@ impl PyObject { } fn abstract_isinstance(&self, cls: &PyObject, vm: &VirtualMachine) -> PyResult { - if let Ok(typ) = PyTypeRef::try_from_object(vm, cls.to_owned()) { + let r = if let Ok(typ) = PyTypeRef::try_from_object(vm, cls.to_owned()) { if self.class().fast_issubclass(&typ) { - Ok(true) + true } else if let Ok(icls) = PyTypeRef::try_from_object( vm, self.to_owned().get_attr(identifier!(vm, __class__), vm)?, ) { if icls.is(self.class()) { - Ok(false) + false } else { - Ok(icls.fast_issubclass(&typ)) + icls.fast_issubclass(&typ) } } else { - Ok(false) + false } } else { self.check_cls(cls, vm, || { @@ -482,16 +482,15 @@ impl PyObject { "isinstance() arg 2 must be a type or tuple of types, not {}", cls.class() ) - }) - .and_then(|_| { - let icls: PyObjectRef = self.to_owned().get_attr(identifier!(vm, __class__), vm)?; - if vm.is_none(&icls) { - Ok(false) - } else { - icls.abstract_issubclass(cls, vm) - } - }) - } + })?; + let icls: PyObjectRef = self.to_owned().get_attr(identifier!(vm, __class__), vm)?; + if vm.is_none(&icls) { + false + } else { + icls.abstract_issubclass(cls, vm)? + } + }; + Ok(r) } /// Determines if `self` is an instance of `cls`, either directly, indirectly or virtually via diff --git a/vm/src/stdlib/builtins.rs b/vm/src/stdlib/builtins.rs index 3c5435f31..8f5ce16da 100644 --- a/vm/src/stdlib/builtins.rs +++ b/vm/src/stdlib/builtins.rs @@ -84,14 +84,12 @@ mod builtins { #[pyfunction] fn chr(i: PyIntRef, vm: &VirtualMachine) -> PyResult { - match i + let value = i .try_to_primitive::(vm)? .to_u32() .and_then(char::from_u32) - { - Some(value) => Ok(value.to_string()), - None => Err(vm.new_value_error("chr() arg not in range(0x110000)".to_owned())), - } + .ok_or_else(|| vm.new_value_error("chr() arg not in range(0x110000)".to_owned()))?; + Ok(value.to_string()) } #[derive(FromArgs)] diff --git a/vm/src/stdlib/io.rs b/vm/src/stdlib/io.rs index 103fcf9aa..1b02f86eb 100644 --- a/vm/src/stdlib/io.rs +++ b/vm/src/stdlib/io.rs @@ -175,7 +175,7 @@ mod _io { impl OptionalSize { #[allow(clippy::wrong_self_convention)] pub fn to_usize(self) -> Option { - self.size.and_then(|v| v.to_usize()) + self.size?.to_usize() } pub fn try_usize(self, vm: &VirtualMachine) -> PyResult> { @@ -2225,11 +2225,11 @@ mod _io { codec.get_incremental_encoder(Some(errors.clone()), vm)?; let encoding_name = vm.get_attribute_opt(incremental_encoder.clone(), "name")?; let encodefunc = encoding_name.and_then(|name| { - name.payload::() - .and_then(|name| match name.as_str() { - "utf-8" => Some(textio_encode_utf8 as EncodeFunc), - _ => None, - }) + let name = name.payload::()?; + match name.as_str() { + "utf-8" => Some(textio_encode_utf8 as EncodeFunc), + _ => None, + } }); Some((incremental_encoder, encodefunc)) } else { diff --git a/vm/src/stdlib/sre.rs b/vm/src/stdlib/sre.rs index a07a048bf..3f66de06e 100644 --- a/vm/src/stdlib/sre.rs +++ b/vm/src/stdlib/sre.rs @@ -157,17 +157,17 @@ mod _sre { where F: FnOnce(&str) -> PyResult, { - string + let string = string .payload::() - .ok_or_else(|| vm.new_type_error("expected string".to_owned())) - .and_then(|x| f(x.as_str())) + .ok_or_else(|| vm.new_type_error("expected string".to_owned()))?; + f(string.as_str()) } fn with_bytes(string: &PyObject, vm: &VirtualMachine, f: F) -> PyResult where F: FnOnce(&[u8]) -> PyResult, { - PyBuffer::try_from_borrowed_object(vm, string).and_then(|x| x.contiguous_or_collect(f)) + PyBuffer::try_from_borrowed_object(vm, string)?.contiguous_or_collect(f) } #[pymethod(name = "match")] @@ -572,9 +572,8 @@ mod _sre { } #[pygetset] fn lastgroup(&self) -> Option { - self.lastindex - .to_usize() - .and_then(|i| self.pattern.indexgroup.get(i).cloned().flatten()) + let i = self.lastindex.to_usize()?; + self.pattern.indexgroup.get(i)?.clone() } #[pygetset] fn re(&self) -> PyRef { diff --git a/vm/src/stdlib/winreg.rs b/vm/src/stdlib/winreg.rs index 660df63da..efd4adcb6 100644 --- a/vm/src/stdlib/winreg.rs +++ b/vm/src/stdlib/winreg.rs @@ -188,13 +188,12 @@ mod winreg { vm: &VirtualMachine, ) -> PyResult<(PyObjectRef, usize)> { let subkey = subkey.as_ref().map_or("", |s| s.as_str()); - key.with_key(|k| k.get_raw_value(subkey)) - .map_err(|e| e.to_pyexception(vm)) - .and_then(|regval| { - #[allow(clippy::redundant_clone)] - let ty = regval.vtype.clone() as usize; - Ok((reg_to_py(regval, vm)?, ty)) - }) + let regval = key + .with_key(|k| k.get_raw_value(subkey)) + .map_err(|e| e.to_pyexception(vm))?; + #[allow(clippy::redundant_clone)] + let ty = regval.vtype.clone() as usize; + Ok((reg_to_py(regval, vm)?, ty)) } #[pyfunction] @@ -214,18 +213,17 @@ mod winreg { index: u32, vm: &VirtualMachine, ) -> PyResult<(String, PyObjectRef, usize)> { - key.with_key(|k| k.enum_values().nth(index as usize)) + let (name, value) = key + .with_key(|k| k.enum_values().nth(index as usize)) .unwrap_or_else(|| { Err(io::Error::from_raw_os_error( winerror::ERROR_NO_MORE_ITEMS as i32, )) }) - .map_err(|e| e.to_pyexception(vm)) - .and_then(|(name, value)| { - #[allow(clippy::redundant_clone)] - let ty = value.vtype.clone() as usize; - Ok((name, reg_to_py(value, vm)?, ty)) - }) + .map_err(|e| e.to_pyexception(vm))?; + #[allow(clippy::redundant_clone)] + let ty = value.vtype.clone() as usize; + Ok((name, reg_to_py(value, vm)?, ty)) } #[pyfunction]