diff --git a/NEWS.rst b/NEWS.rst index 476177c..36a681e 100644 --- a/NEWS.rst +++ b/NEWS.rst @@ -20,6 +20,7 @@ Bug Fixes ------------------------------ * Statements in the second argument of `assert` are now executed. * Fixed the expression of a while loop that contains statements being compiled twice. +* `hy2py` can now handle format strings. 0.17.0 ============================== diff --git a/hy/compiler.py b/hy/compiler.py index 6d09afa..34a9dd5 100755 --- a/hy/compiler.py +++ b/hy/compiler.py @@ -1784,7 +1784,7 @@ class HyASTCompiler(object): item = item[2:].lstrip() # Look for a format specifier. - format_spec = asty.Str(string, s = "") + format_spec = None if item.startswith(':'): if allow_recursion: ret += self._format_string(string, @@ -1793,6 +1793,8 @@ class HyASTCompiler(object): format_spec = ret.force_expr else: format_spec = asty.Str(string, s=item[1:]) + if PY36: + format_spec = asty.JoinedStr(string, values=[format_spec]) elif item: raise self._syntax_error(string, "f-string: trailing junk in field") @@ -1818,7 +1820,9 @@ class HyASTCompiler(object): ('!' + conversion if conversion else '') + ':{}}'), attr = 'format', ctx = ast.Load()), - args = [ret.force_expr, format_spec], + args = [ + ret.force_expr, + format_spec or asty.Str(string, s = "")], keywords = [], starargs = None, kwargs = None)) return ret + ( diff --git a/tests/resources/pydemo.hy b/tests/resources/pydemo.hy index 5611177..a23e3c2 100644 --- a/tests/resources/pydemo.hy +++ b/tests/resources/pydemo.hy @@ -49,6 +49,10 @@ Call me Ishmael. Some years ago—never mind how long precisely—having little (setv condexpr (if "" "x" "y")) (setv mylambda (fn [x] (+ x "z"))) +(setv fstring1 f"hello {(+ 1 1)} world") +(setv p "xyzzy") +(setv fstring2 f"a{p !r :9}") + (setv augassign 103) (//= augassign 4) diff --git a/tests/test_hy2py.py b/tests/test_hy2py.py index 46ef638..d19e4f6 100644 --- a/tests/test_hy2py.py +++ b/tests/test_hy2py.py @@ -79,6 +79,9 @@ def assert_stuff(m): assert type(m.mylambda) is type(lambda x: x + "z") assert m.mylambda("a") == "az" + assert m.fstring1 == "hello 2 world" + assert m.fstring2 == "a'xyzzy' " + assert m.augassign == 25 assert m.delstatement == ["a", "c", "d", "e"]