diff --git a/common/src/format.rs b/common/src/format.rs index 24f296a76..8b2fa5972 100644 --- a/common/src/format.rs +++ b/common/src/format.rs @@ -416,6 +416,19 @@ impl FormatSpec { } } + pub fn format_bool(&self, input: bool) -> Result { + let x = u8::from(input); + let result: Result = match &self.format_type { + Some(FormatType::Decimal) => Ok(x.to_string()), + None => { + let first_letter = (input.to_string().as_bytes()[0] as char).to_uppercase(); + Ok(first_letter.collect::() + &input.to_string()[1..]) + } + _ => Err(FormatSpecError::InvalidFormatSpecifier), + }; + result + } + pub fn format_float(&self, num: f64) -> Result { self.validate_format(FormatType::FixedPoint(Case::Lower))?; let precision = self.precision.unwrap_or(6); diff --git a/vm/src/builtins/bool.rs b/vm/src/builtins/bool.rs index d70af0f07..956925847 100644 --- a/vm/src/builtins/bool.rs +++ b/vm/src/builtins/bool.rs @@ -1,7 +1,8 @@ use super::{PyInt, PyStrRef, PyType, PyTypeRef}; use crate::{ class::PyClassImpl, - convert::{ToPyObject, ToPyResult}, + common::format::FormatSpec, + convert::{IntoPyException, ToPyObject, ToPyResult}, function::OptionalArg, identifier, protocol::PyNumberMethods, @@ -110,12 +111,11 @@ impl Constructor for PyBool { #[pyclass(with(Constructor, AsNumber, Representable))] impl PyBool { #[pymethod(magic)] - fn format(obj: PyObjectRef, format_spec: PyStrRef, vm: &VirtualMachine) -> PyResult { - if format_spec.is_empty() { - obj.str(vm) - } else { - Err(vm.new_type_error("unsupported format string passed to bool.__format__".to_owned())) - } + fn format(obj: PyObjectRef, spec: PyStrRef, vm: &VirtualMachine) -> PyResult { + let new_bool = obj.try_to_bool(vm)?; + FormatSpec::parse(spec.as_str()) + .and_then(|format_spec| format_spec.format_bool(new_bool)) + .map_err(|err| err.into_pyexception(vm)) } #[pymethod(name = "__ror__")]