Skip to content

Commit 7e138ec

Browse files
committed
Improve f-string syntax. Fixes RustPython#1099
1 parent 93f70ab commit 7e138ec

File tree

3 files changed

+21
-1
lines changed

3 files changed

+21
-1
lines changed

parser/src/python.lalrpop

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@ grammar;
1919
pub Top: ast::Top = {
2020
StartProgram <p:Program> => ast::Top::Program(p),
2121
StartStatement <s:Statement> => ast::Top::Statement(s),
22-
StartExpression <e:Expression> => ast::Top::Expression(e),
22+
StartExpression <e:Test> => ast::Top::Expression(e),
2323
};
2424

2525
Program: ast::Program = {

tests/snippets/fstrings.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,3 +39,9 @@ def __str__(self):
3939
assert f'{v}' == 'foo'
4040
assert f'{v!r}' == 'bar'
4141
assert f'{v!s}' == 'baz'
42+
43+
# advanced expressions:
44+
45+
assert f'{True or True}' == 'True'
46+
assert f'{1 == 1}' == 'True'
47+
assert f'{"0" if True else "1"}' == '0'

vm/src/obj/objbool.rs

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ use crate::pyobject::{IntoPyObject, PyContext, PyObjectRef, PyResult, TryFromObj
55
use crate::vm::VirtualMachine;
66

77
use super::objint::PyInt;
8+
use super::objstr::PyStringRef;
89
use super::objtype;
910

1011
impl IntoPyObject for bool {
@@ -47,6 +48,7 @@ The class bool is a subclass of the class int, and cannot be subclassed.";
4748
extend_class!(context, bool_type, {
4849
"__new__" => context.new_rustfunc(bool_new),
4950
"__repr__" => context.new_rustfunc(bool_repr),
51+
"__format__" => context.new_rustfunc(bool_format),
5052
"__or__" => context.new_rustfunc(bool_or),
5153
"__ror__" => context.new_rustfunc(bool_ror),
5254
"__and__" => context.new_rustfunc(bool_and),
@@ -82,6 +84,18 @@ fn bool_repr(vm: &VirtualMachine, args: PyFuncArgs) -> Result<PyObjectRef, PyObj
8284
Ok(vm.new_str(s))
8385
}
8486

87+
fn bool_format(
88+
obj: PyObjectRef,
89+
format_spec: PyStringRef,
90+
vm: &VirtualMachine,
91+
) -> PyResult<PyStringRef> {
92+
if format_spec.value.is_empty() {
93+
vm.to_str(&obj)
94+
} else {
95+
Err(vm.new_type_error("unsupported format string passed to bool.__format__".to_string()))
96+
}
97+
}
98+
8599
fn do_bool_or(vm: &VirtualMachine, lhs: &PyObjectRef, rhs: &PyObjectRef) -> PyResult {
86100
if objtype::isinstance(lhs, &vm.ctx.bool_type())
87101
&& objtype::isinstance(rhs, &vm.ctx.bool_type())

0 commit comments

Comments
 (0)