mirror of
https://github.com/micropython/micropython.git
synced 2026-01-08 21:20:13 +01:00
py: Implement partial PEP-498 (f-string) support.
This implements (most of) the PEP-498 spec for f-strings and is based on https://github.com/micropython/micropython/pull/4998 by @klardotsh. It is implemented in the lexer as a syntax translation to `str.format`: f"{a}" --> "{}".format(a) It also supports: f"{a=}" --> "a={}".format(a) This is done by extracting the arguments into a temporary vstr buffer, then after the string has been tokenized, the lexer input queue is saved and the contents of the temporary vstr buffer are injected into the lexer instead. There are four main limitations: - raw f-strings (`fr` or `rf` prefixes) are not supported and will raise `SyntaxError: raw f-strings are not supported`. - literal concatenation of f-strings with adjacent strings will fail "{}" f"{a}" --> "{}{}".format(a) (str.format will incorrectly use the braces from the non-f-string) f"{a}" f"{a}" --> "{}".format(a) "{}".format(a) (cannot concatenate) - PEP-498 requires the full parser to understand the interpolated argument, however because this entirely runs in the lexer it cannot resolve nested braces in expressions like f"{'}'}" - The !r, !s, and !a conversions are not supported. Includes tests and cpydiffs. Signed-off-by: Jim Mussared <jim.mussared@gmail.com>
This commit is contained in:
committed by
Damien George
parent
162bf3c5d8
commit
692d36d779
@@ -1152,6 +1152,14 @@ mp_parse_tree_t mp_parse(mp_lexer_t *lex, mp_parse_input_kind_t input_kind) {
|
||||
} else if (lex->tok_kind == MP_TOKEN_DEDENT_MISMATCH) {
|
||||
exc = mp_obj_new_exception_msg(&mp_type_IndentationError,
|
||||
MP_ERROR_TEXT("unindent doesn't match any outer indent level"));
|
||||
#if MICROPY_PY_FSTRINGS
|
||||
} else if (lex->tok_kind == MP_TOKEN_MALFORMED_FSTRING) {
|
||||
exc = mp_obj_new_exception_msg(&mp_type_SyntaxError,
|
||||
MP_ERROR_TEXT("malformed f-string"));
|
||||
} else if (lex->tok_kind == MP_TOKEN_FSTRING_RAW) {
|
||||
exc = mp_obj_new_exception_msg(&mp_type_SyntaxError,
|
||||
MP_ERROR_TEXT("raw f-strings are not supported"));
|
||||
#endif
|
||||
} else {
|
||||
exc = mp_obj_new_exception_msg(&mp_type_SyntaxError,
|
||||
MP_ERROR_TEXT("invalid syntax"));
|
||||
|
||||
Reference in New Issue
Block a user