Skip to content

Commit

Permalink
[Lang] Support f-string
Browse files Browse the repository at this point in the history
  • Loading branch information
knight42 authored Oct 29, 2021
1 parent a27036f commit c82dcbf
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 0 deletions.
22 changes: 22 additions & 0 deletions python/taichi/lang/expr_builder.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,28 @@


class ExprBuilder(Builder):
@staticmethod
def build_JoinedStr(ctx, node):
str_spec = ''
args = []
for sub_node in node.values:
if isinstance(sub_node, ast.FormattedValue):
str_spec += '{}'
args.append(build_expr(ctx, sub_node.value))
elif isinstance(sub_node, ast.Constant):
str_spec += sub_node.value
elif isinstance(sub_node, ast.Str):
# ast.Str has been deprecated in Python 3.8,
# but constant string is a ast.Str node in Python 3.6
str_spec += sub_node.s

args.insert(0, ast.copy_location(ast.Constant(value=str_spec), node))

call = ast.Call(func=parse_expr('ti.ti_format'),
args=args,
keywords=[])
return ast.copy_location(call, node)

@staticmethod
def build_Subscript(ctx, node):
def get_subscript_index(node):
Expand Down
13 changes: 13 additions & 0 deletions tests/python/test_print.py
Original file line number Diff line number Diff line change
Expand Up @@ -142,3 +142,16 @@ def func(k: ti.f32):

func(233.3)
ti.sync()


@ti.test(arch=ti.cpu)
def test_print_fstring():
def foo1(x):
return x + 1

@ti.kernel
def func(i: ti.i32, f: ti.f32):
print(f'qwe {foo1(1)} {foo1(2) * 2 - 1} {i} {f} {4} {True} {1.23}')

func(123, 4.56)
ti.sync()

0 comments on commit c82dcbf

Please sign in to comment.