Skip to content

Improve f-string syntax. Fixes #1099 #1115

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jul 7, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion parser/src/python.lalrpop
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ grammar;
pub Top: ast::Top = {
StartProgram <p:Program> => ast::Top::Program(p),
StartStatement <s:Statement> => ast::Top::Statement(s),
StartExpression <e:Expression> => ast::Top::Expression(e),
StartExpression <e:Test> => ast::Top::Expression(e),
};

Program: ast::Program = {
Expand Down
6 changes: 6 additions & 0 deletions tests/snippets/fstrings.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,3 +39,9 @@ def __str__(self):
assert f'{v}' == 'foo'
assert f'{v!r}' == 'bar'
assert f'{v!s}' == 'baz'

# advanced expressions:

assert f'{True or True}' == 'True'
assert f'{1 == 1}' == 'True'
assert f'{"0" if True else "1"}' == '0'
14 changes: 14 additions & 0 deletions vm/src/obj/objbool.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ use crate::pyobject::{IntoPyObject, PyContext, PyObjectRef, PyResult, TryFromObj
use crate::vm::VirtualMachine;

use super::objint::PyInt;
use super::objstr::PyStringRef;
use super::objtype;

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

fn bool_format(
obj: PyObjectRef,
format_spec: PyStringRef,
vm: &VirtualMachine,
) -> PyResult<PyStringRef> {
if format_spec.value.is_empty() {
vm.to_str(&obj)
} else {
Err(vm.new_type_error("unsupported format string passed to bool.__format__".to_string()))
}
}

fn do_bool_or(vm: &VirtualMachine, lhs: &PyObjectRef, rhs: &PyObjectRef) -> PyResult {
if objtype::isinstance(lhs, &vm.ctx.bool_type())
&& objtype::isinstance(rhs, &vm.ctx.bool_type())
Expand Down