Skip to content
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

Support for f-strings #355

Merged
merged 1 commit into from
Jul 15, 2023
Merged

Support for f-strings #355

merged 1 commit into from
Jul 15, 2023

Conversation

s-hadinger
Copy link
Contributor

Major enhancement discussed in Tasmota Berry support. The Berry parser now supports the equivalent for Python's f-strings.

This feature is pure syntactic sugar and purely re-writes the f-string as follows:

  • internally a command format("<template", <arguments>) is generated from the f-string. This is done by the lexer that re-writes the f-string (like a transpiler) and sends the re-written part to the parser. Hence there is no code difference nor any impact to the runtime.
  • { and } need to be escaped as {{ and }}
  • inserts are formed as {<expr>:<format>} and are transformed as %<format> followed by <expr> as argument
  • if <format> is omitted, the string qualifier %s is used
  • if <format> starts with %, this character is ignored
  • a special case {<expr>=:<format>} is useful for debugging are writes the literal <expr> in the format.

Examples: f-strings followed by their equivalent

# let's initialize some variables
var a = 1
var f = 3.1415
var s = 'foobar{0}'

f"foobar{{1}}"
format("foobar{1}")
# 'foobar{1}'

# integers are automatically converted to strings
f'1 + 1 is {1+1}'
format('1 + 1 is %s', 1+1)
# '1 + 1 is 2'

f"p = {f:.2f}"
format("p = %.2f", f)
# 'p = 3.14'

f"s = {s} a = {a} f = {f:.1f}"
format("s = %s a = %s f = %.1f", s, a, f)
# 's = foobar{0} a = 1 f = 3.1'

f"{s=} {a+1=} {f=:.1f}"
format("s=%s a+1=%s f=%1.f", s, a+1, f)
# 's=foobar{0} a+1=2 f=3.1'

@s-hadinger s-hadinger merged commit a216ff1 into berry-lang:master Jul 15, 2023
@s-hadinger s-hadinger mentioned this pull request Jul 15, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant